Sources/OrgCore/Export/HTMLExport.swift

988 lines · 47923 bytes

  1import Foundation
  2
  3/// Document metadata from `#+TITLE`, `#+AUTHOR`, `#+DATE` and `#+LANGUAGE`.
  4public struct ExportMetadata: Sendable, Equatable {
  5    public var title: String?
  6    public var author: String?
  7    public var date: String?
  8    public var language: String?
  9}
 10
 11/// HTML export. The body follows the shape orgo produces, which the org-conformance corpus
 12/// holds as the reference: headings one level down (`*` is `<h2>`), timestamps as `<time>`,
 13/// footnotes collected at the end, captioned images as figures.
 14public enum HTMLExport {
 15    public static func body(_ text: String, settings: OrgSettings = .default) -> String {
 16        let renderer = HTMLRenderer(settings: settings, options: .orgo)
 17        return renderer.document(text)
 18    }
 19
 20    public static func metadata(_ text: String, settings: OrgSettings = .default) -> ExportMetadata {
 21        let tree = OrgParser.parse(text, defaults: settings)
 22        var meta = ExportMetadata()
 23        // Setup files' keywords come first, as Org reads them where `#+SETUPFILE` is.
 24        let setup = settings.setupKeywords.split(separator: "\n").map(String.init)
 25        let own = tree.root.children.filter { $0.kind == .zerothSection }.flatMap { $0.children.filter { $0.kind == .keyword } }.map(\.text)
 26        for text in setup + own {
 27            let line = text.trimmingCharacters(in: .whitespacesAndNewlines)
 28            guard let colon = line.firstIndex(of: ":") else { continue }
 29            let key = line.dropFirst(2).prefix { $0 != ":" }.uppercased()
 30            let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
 31            switch key {
 32            case "TITLE": meta.title = value
 33            case "AUTHOR": meta.author = value
 34            case "DATE": meta.date = value
 35            case "LANGUAGE": meta.language = value.isEmpty ? nil : value
 36            default: break
 37            }
 38        }
 39        return meta
 40    }
 41
 42    /// The tag that loads MathJax on a page with math.
 43    public static let mathJaxScript = #"<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>"#
 44
 45    /// A standalone page: the body under the document's title, with a small stylesheet, as
 46    /// `#+OPTIONS` and the export keywords ask. `path` is the file's, for `#+INCLUDE` and
 47    /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and
 48    /// byline: the table of contents, the document and its footnotes, as Org's body-only export.
 49    /// `language` is `org-export-default-language`, for files without `#+LANGUAGE`.
 50    public static func page(
 51        _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
 52        codeStyle: HTMLCodeStyle? = nil, language: String = "en"
 53    ) -> String {
 54        let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
 55        let expanded = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
 56        let text = ExportPreprocess.attachments(expanded, path: path, settings: settings)
 57        let options = ExportOptions.parse(settings.setupKeywords + text)
 58        let meta = metadata(text, settings: settings)
 59        let title = meta.title ?? fallbackTitle
 60        let renderer = HTMLRenderer(settings: settings, options: options)
 61        renderer.codeStyle = codeStyle
 62        renderer.language = meta.language ?? language
 63        // The title isn't part of the document Org processes citations in: they drop out.
 64        renderer.inTitle = true
 65        let titleHTML = renderer.inlineString(title)
 66        renderer.inTitle = false
 67        renderer.citations = CiteProcessor(text: text, directory: directory)
 68        var header = options.title ? "<h1 class=\"title\">\(titleHTML)</h1>\n" : ""
 69        let byline = [options.author ? meta.author : nil, options.date ? meta.date : nil].compactMap { $0 }.filter { !$0.isEmpty }
 70        if !byline.isEmpty { header += "<p class=\"byline\">\(byline.map(HTMLRenderer.escape).joined(separator: " · "))</p>\n" }
 71        let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
 72        let contents = renderer.tableOfContents()
 73        if bodyOnly { return contents + body }
 74        header += contents
 75        var head = options.htmlHead.map { $0 + "\n" }.joined()
 76        if renderer.hasMath {
 77            head += """
 78            <script>window.MathJax = { tex: { inlineMath: [['\\\\(', '\\\\)']], displayMath: [['\\\\[', '\\\\]'], ['$$', '$$']] } };</script>
 79            \(mathJaxScript)
 80
 81            """
 82        }
 83        return """
 84        <!DOCTYPE html>
 85        <html lang="\(HTMLRenderer.escape(renderer.language))">
 86        <head>
 87        <meta charset="utf-8">
 88        <meta name="viewport" content="width=device-width, initial-scale=1">
 89        <title>\(HTMLRenderer.escape(title))</title>
 90        <style>
 91        body { font: 16px/1.55 -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif; max-width: 46em; margin: 2em auto; padding: 0 1em; color: #222; }
 92        @media (prefers-color-scheme: dark) { body { background: #1d1d1f; color: #ddd; } a { color: #6cb6ff; } }
 93        pre { background: rgba(127, 127, 127, 0.12); padding: 0.75em; overflow-x: auto; }
 94        code { font: 0.9em ui-monospace, Menlo, monospace; }
 95        table { border-collapse: collapse; } th, td { border: 1px solid rgba(127, 127, 127, 0.4); padding: 0.25em 0.6em; }
 96        blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid rgba(127, 127, 127, 0.4); }
 97        .tag { font-size: 0.75em; padding: 0 0.3em; border-radius: 3px; background: rgba(127, 127, 127, 0.18); }
 98        .todo { color: #c33; } .done { color: #393; } .byline { color: #888; } .center { text-align: center; }
 99        figure { margin: 1em 0; } img { max-width: 100%; }
100        #table-of-contents ul { list-style: none; padding-left: 1.2em; } #table-of-contents > div > ul { padding-left: 0; }
101        \(codeStyle?.css ?? "")</style>
102        \(head)</head>
103        <body>
104        \(header)\(body)</body>
105        </html>
106
107        """
108    }
109}
110
111/// The tree being exported, for what its src blocks, calls and inline blocks export.
112final class ExportSource {
113    let tree: OrgTree
114    let text: NSString
115    private lazy var model = DocumentModel(tree: tree)
116    /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show;
117    /// nil when nothing asks.
118    var inlineResults: Bool?
119    /// Whether the languages' own `:exports` defaults apply.
120    let languages: Bool
121
122    init(tree: OrgTree, text: String, languages: Bool = true) {
123        self.tree = tree
124        self.text = text as NSString
125        self.languages = languages
126    }
127
128    func exports(at offset: Int) -> String? {
129        Babel.exports(at: offset, tree: tree, model: model, text: text, languages: languages)
130    }
131
132    /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows:
133    /// nil for other macros, the text to show (or nil) for this one.
134    func resultsMacro(_ node: SyntaxNode) -> String?? {
135        guard let m = node.text.firstMatch(of: /(?i)^\{\{\{results\((.*)\)\}\}\}$/) else { return .none }
136        defer { inlineResults = nil }
137        return inlineResults ?? true ? ExportPreprocess.arguments(String(m.1)).first : .some(nil)
138    }
139}
140
141final class HTMLRenderer {
142    let settings: OrgSettings
143    let options: ExportOptions
144    /// With select tags in the document: the sections to export, by heading start.
145    private var selected: Set<Int>?
146    private var numbers: [Int] = []
147    private var tocEntries: [(level: Int, id: String, html: String)] = []
148    /// `#+LANGUAGE`, for the words the exporter writes (`org-export-translate`).
149    var language = "en"
150    /// A LaTeX fragment was exported, for MathJax.
151    private(set) var hasMath = false
152    private var footnoteNumbers: [String: Int] = [:]
153    private var footnoteOrder: [(label: String, content: FootnoteContent)] = []
154    private var definitions: [String: String] = [:]
155    private var anonymous = 0
156    private var figures = 0
157    private var ids: Set<String> = []
158    /// Citations and the bibliography, as `oc-basic` exports them.
159    var citations: CiteProcessor?
160    /// Rendering the title, where Org exports citations as nothing.
161    var inTitle = false
162    /// Colors for source blocks; plain without.
163    var codeStyle: HTMLCodeStyle?
164
165    enum FootnoteContent {
166        case definition(String)
167        case inline(String)
168    }
169
170    init(settings: OrgSettings, options: ExportOptions = .orgo) {
171        self.settings = settings
172        self.options = options
173    }
174
175    static func escape(_ s: String) -> String {
176        var out = ""
177        for c in s {
178            switch c {
179            case "&": out += "&amp;"
180            case "<": out += "&lt;"
181            case ">": out += "&gt;"
182            case "\"": out += "&quot;"
183            default: out.append(c)
184            }
185        }
186        return out
187    }
188
189    // MARK: - Document
190
191    /// The document's tree, for code references, and each src and example block's
192    /// `org-export-get-loc`, by the block's text, in order.
193    private var documentTree: OrgTree?
194    private var blockLocs: [String: [Int?]] = [:]
195
196    func document(_ text: String) -> String {
197        let tree = OrgParser.parse(text, defaults: settings)
198        documentTree = tree
199        let codeBlocks = Coderef.blocks(tree)
200        for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
201            blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
202        }
203        collectDefinitions(tree.root)
204        selected = Self.selection(tree, tags: options.selectTags)
205        var out = ""
206        rendering(tree, text) {
207            for child in tree.root.children { out += element(child) }
208        }
209        out += footnoteSection()
210        return out
211    }
212
213    private var source: ExportSource?
214
215    /// `body` with `tree` as the source of `:exports`.
216    private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
217        let saved = source
218        source = ExportSource(tree: tree, text: text)
219        defer { source = saved }
220        return body()
221    }
222
223    private func collectDefinitions(_ node: SyntaxNode) {
224        for child in node.children {
225            if child.kind == .footnoteDefinition {
226                let text = child.text
227                if let m = text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
228                    definitions[String(m.1)] = String(text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
229                }
230            } else {
231                collectDefinitions(child)
232            }
233        }
234    }
235
236    private func footnoteSection() -> String {
237        guard !footnoteOrder.isEmpty else { return "" }
238        var out = "<section class=\"footnotes\" aria-label=\"\(ExportDictionary.translate("Footnotes", language: language, encoding: .html))\">\n<hr>\n<ol>\n"
239        for (index, note) in footnoteOrder.enumerated() {
240            let n = index + 1
241            let content: String
242            switch note.content {
243            case .definition(let text): content = blocks(text).trimmingCharacters(in: .newlines)
244            case .inline(let text): content = inlineString(text)
245            }
246            out += "<li id=\"fn-\(n)\">\(content)\n <a class=\"footnote-back\" href=\"#fnr-\(n)\" aria-label=\"Back to reference \(n)\">&#8617;</a></li>\n"
247        }
248        return out + "</ol>\n</section>\n"
249    }
250
251    /// Org text rendered as elements, for block and footnote contents.
252    func blocks(_ text: String) -> String {
253        let tree = OrgParser.parse(text, defaults: settings)
254        var out = ""
255        rendering(tree, text) {
256            for child in tree.root.children { out += element(child) }
257        }
258        return out
259    }
260
261    /// One line of org text rendered inline.
262    func inlineString(_ text: String) -> String {
263        let tree = OrgParser.parse(text, defaults: settings)
264        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
265        return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
266    }
267
268    /// A citation's or a bibliography entry's pieces: text escaped, prefixes and suffixes as
269    /// Org markup with their blanks kept.
270    private func render(_ pieces: [CiteProcessor.Piece]) -> String {
271        pieces.map { piece in
272            switch piece {
273            case .text(let s): Self.escape(s)
274            case .italic(let s): "<i>" + Self.escape(s) + "</i>"
275            case .org(let s) where s.allSatisfy(\.isWhitespace): s
276            case .org(let s):
277                String(s.prefix { $0.isWhitespace }) + inlineString(s) + (s.allSatisfy(\.isWhitespace) ? "" : String(s.reversed().prefix { $0.isWhitespace }))
278            }
279        }.joined()
280    }
281
282    // MARK: - Elements
283
284    private var affiliated: [String: String] = [:]
285    /// `:exports` of the last src block or call: its results are exported only for `results`
286    /// and `both`; nothing runs.
287    private var lastExports = "code"
288
289    func element(_ node: SyntaxNode) -> String {
290        defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
291        if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
292            defer { lastExports = "code" }
293            if lastExports != "results", lastExports != "both" { return "" }
294        }
295        if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
296            lastExports = exports
297            if exports == "results" || exports == "none" { return "" }
298        }
299        switch node.kind {
300        case .section:
301            guard let heading = node.firstChild(.heading) else { fallthrough }
302            switch Self.sectionExport(heading, options: options, selected: selected) {
303            case .nothing: return ""
304            case .heading: return self.heading(heading)
305            case .all: break
306            }
307            var out = ""
308            for child in node.children { out += element(child) }
309            return out
310        case .zerothSection, .document:
311            var out = ""
312            for child in node.children { out += element(child) }
313            return out
314        case .heading:
315            return heading(node)
316        case .affiliatedKeyword:
317            let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
318            if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
319                affiliated[m.1.uppercased()] = String(m.2)
320            }
321            return ""
322        case .paragraph:
323            return paragraph(node)
324        case .keyword where citations != nil && node.text.range(of: "^[ \\t]*#\\+print_bibliography:", options: [.regularExpression, .caseInsensitive]) != nil:
325            return citations!.bibliography.map { "<p>" + render($0) + "</p>\n" }.joined()
326        case .plainList:
327            return list(node)
328        case .table:
329            return table(node)
330        case .block:
331            return block(node)
332        case .horizontalRule:
333            return "<hr>\n"
334        case .inlineTask:
335            // As ox-html: the title in bold, then the contents.
336            var out = "<div class=\"inlinetask\">\n"
337            for child in node.children {
338                if child.kind == .heading {
339                    guard child.range.lowerBound == node.range.lowerBound else { continue }
340                    let title = child.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
341                    let todo = options.todo ? child.tokens.first { $0.kind == .todoKeyword }.map { "<span class=\"todo \(Self.escape($0.text))\">\(Self.escape($0.text))</span> " } ?? "" : ""
342                    out += "<b>\(todo)\(title)</b><br>\n"
343                } else {
344                    out += element(child)
345                }
346            }
347            return out + "</div>\n"
348        case .latexEnvironment:
349            // For MathJax, as ox-html leaves it with `tex:t`.
350            guard options.tex else { return "" }
351            hasMath = true
352            return Self.escape(node.text.trimmingCharacters(in: .newlines)) + "\n"
353        case .fixedWidth:
354            let lines = node.text.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
355                let trimmed = line.drop { $0 == " " || $0 == "\t" }
356                return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
357            }
358            return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
359        case .tableEl:
360            let lines = node.text.components(separatedBy: "\n").filter { !$0.lowercased().contains("#+tblfm") }
361            // As `org-html-table--table.el-table`: cells with their spans, lines kept apart.
362            if let cells = TableEl.cells(lines.joined(separator: "\n")) {
363                var out = "<table class=\"table-el\">\n"
364                for row in Dictionary(grouping: cells, by: \.row).keys.sorted() {
365                    out += "<tr>"
366                    for cell in cells where cell.row == row {
367                        let spans = (cell.colspan > 1 ? " colspan=\"\(cell.colspan)\"" : "") + (cell.rowspan > 1 ? " rowspan=\"\(cell.rowspan)\"" : "")
368                        let content = cell.lines.reversed().drop { $0.isEmpty }.reversed().map(Self.escape).joined(separator: "<br>")
369                        out += "<td\(spans)>\(content)</td>"
370                    }
371                    out += "</tr>\n"
372                }
373                return out + "</table>\n"
374            }
375            return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
376        case .dynamicBlock:
377            let lines = node.text.components(separatedBy: "\n")
378            return blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))
379        default:
380            // Keywords, comments, drawers, planning, clocks, footnote definitions, formulas.
381            return ""
382        }
383    }
384
385    private func slug(_ text: String) -> String {
386        var slug = ""
387        var dash = false
388        for c in text.lowercased() {
389            if c.isLetter || c.isNumber {
390                if dash, !slug.isEmpty { slug.append("-") }
391                slug.append(c)
392                dash = false
393            } else {
394                dash = true
395            }
396        }
397        if slug.isEmpty { slug = "section" }
398        var candidate = slug
399        var n = 1
400        while ids.contains(candidate) {
401            candidate = "\(slug)-\(n)"
402            n += 1
403        }
404        ids.insert(candidate)
405        return candidate
406    }
407
408    /// `org-export--selected-trees`: headings with a select tag, everything below them and
409    /// their ancestors; nil when no heading has one.
410    enum SectionExport {
411        case all, heading, nothing
412    }
413
414    /// `org-export--skip-p` for the section under `heading`: excluded tags, COMMENT and
415    /// unselected trees export nothing, archived trees their heading only.
416    static func sectionExport(_ heading: SyntaxNode, options: ExportOptions, selected: Set<Int>?) -> SectionExport {
417        let tags = heading.tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? []
418        let title = heading.firstChild(.title)?.text.trimmingCharacters(in: .whitespaces) ?? ""
419        if tags.contains(where: options.excludeTags.contains) || title == "COMMENT" || title.hasPrefix("COMMENT ") { return .nothing }
420        if let selected, !selected.contains(heading.range.lowerBound) { return .nothing }
421        return tags.contains("ARCHIVE") ? .heading : .all
422    }
423
424    static func selection(_ tree: OrgTree, tags: [String]) -> Set<Int>? {
425        let model = DocumentModel(tree: tree)
426        let picked = model.headings.indices.filter { model.headings[$0].localTags.contains(where: tags.contains) }
427        guard !picked.isEmpty else { return nil }
428        var set: Set<Int> = []
429        for index in picked {
430            set.insert(model.headings[index].headingRange.lowerBound)
431            for a in model.ancestors(of: index) { set.insert(model.headings[a].headingRange.lowerBound) }
432            let level = model.headings[index].level
433            for d in model.headings[(index + 1)...].prefix(while: { $0.level > level }) { set.insert(d.headingRange.lowerBound) }
434        }
435        return set
436    }
437
438    /// The table of contents, as ox-html writes it, or nothing.
439    func tableOfContents() -> String {
440        guard options.toc != nil, !tocEntries.isEmpty else { return "" }
441        var out = "<div id=\"table-of-contents\" role=\"doc-toc\">\n<h2>\(ExportDictionary.translate("Table of Contents", language: language, encoding: .html))</h2>\n<div id=\"text-table-of-contents\" role=\"doc-toc\">\n"
442        var depth = 0
443        var open: [Bool] = []
444        let base = tocEntries.map(\.level).min() ?? 1
445        for entry in tocEntries {
446            let level = entry.level - base + 1
447            if level > depth {
448                while depth < level {
449                    out += "\n<ul>\n"
450                    depth += 1
451                    open.append(false)
452                }
453            } else {
454                out += "</li>\n"
455                while depth > level {
456                    out += "</ul>\n</li>\n"
457                    depth -= 1
458                    open.removeLast()
459                }
460            }
461            out += "<li><a href=\"#\(Self.escape(entry.id))\">\(entry.html)</a>"
462        }
463        out += "</li>\n"
464        while depth > 1 {
465            out += "</ul>\n</li>\n"
466            depth -= 1
467        }
468        return out + "</ul>\n</div>\n</div>\n"
469    }
470
471    private func heading(_ node: SyntaxNode) -> String {
472        let tokens = node.tokens
473        let level = tokens.first { $0.kind == .stars }?.text.count ?? 1
474        let title = node.firstChild(.title)
475        let titleText = title?.text.trimmingCharacters(in: .whitespaces) ?? ""
476        // `CUSTOM_ID` from the property drawer that follows.
477        var customID: String?
478        if let section = node.parent, let drawer = section.firstChild(.propertyDrawer) {
479            for property in drawer.children where property.kind == .nodeProperty {
480                if let m = property.text.firstMatch(of: /^[ \t]*:CUSTOM_ID:[ \t]*(\S+)/) { customID = String(m.1) }
481            }
482        }
483        let id = customID ?? slug(titleText)
484        if customID != nil { ids.insert(id) }
485        var parts: [String] = []
486        let h = min(level + 1, 6)
487        if let num = options.num, level <= num {
488            if numbers.count < level { numbers += Array(repeating: 0, count: level - numbers.count) }
489            numbers = Array(numbers.prefix(level))
490            numbers[level - 1] += 1
491            parts.append("<span class=\"section-number-\(h)\">\(numbers.map(String.init).joined(separator: ".")).</span>")
492        }
493        if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
494            parts.append("<span class=\"todo \(settings.isDone(todo) ? "done " : "")\(Self.escape(todo))\">\(Self.escape(todo))</span>")
495        }
496        if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text {
497            parts.append("<span class=\"priority\">\(Self.escape(priority))</span>")
498        }
499        if let title, !titleText.isEmpty { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
500        var tagParts: [String] = []
501        if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
502            tagParts = tags.split(separator: ":").map { "<span class=\"tag\">\(Self.escape(String($0)))</span>" }
503        }
504        if let toc = options.toc, level <= toc {
505            tocEntries.append((level, id, (parts + (options.tagsInTOC ? tagParts : [])).joined(separator: " ")))
506        }
507        parts += tagParts
508        return "<h\(h) id=\"\(Self.escape(id))\">\(parts.joined(separator: " "))</h\(h)>\n"
509    }
510
511    private func paragraph(_ node: SyntaxNode) -> String {
512        let body = inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
513        if let image = soleImage(node), affiliated["CAPTION"] != nil || affiliated["ATTR_HTML"] != nil {
514            var out = "<figure>\n" + image + "\n"
515            if let caption = affiliated["CAPTION"] {
516                figures += 1
517                let label = ExportDictionary.translate("Figure %d:", language: language, encoding: .html).replacingOccurrences(of: "%d", with: String(figures))
518                out += "<figcaption>\(label) \(inlineString(caption))</figcaption>\n"
519            }
520            return out + "</figure>\n"
521        }
522        return "<p>\(body)</p>\n"
523    }
524
525    /// The `<img>` of a paragraph that is only an image link.
526    private func soleImage(_ node: SyntaxNode) -> String? {
527        let links = node.children.filter { $0.kind == .link }
528        guard links.count == 1, node.children.count == 1,
529              node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else { return nil }
530        let html = link(links[0])
531        return html.hasPrefix("<img") ? html : nil
532    }
533
534    // MARK: - Lists
535
536    private func isOrdered(_ item: SyntaxNode) -> Bool {
537        let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
538        return bullet.first.map { $0.isNumber || $0.isLetter } ?? false
539    }
540
541    /// As orgo does, a change between ordered and unordered bullets starts another list.
542    private func list(_ node: SyntaxNode) -> String {
543        var runs: [[SyntaxNode]] = []
544        for item in node.children where item.kind == .item {
545            if let last = runs.last?.last, isOrdered(last) == isOrdered(item) {
546                runs[runs.count - 1].append(item)
547            } else {
548                runs.append([item])
549            }
550        }
551        return runs.map(list).joined()
552    }
553
554    private func list(_ items: [SyntaxNode]) -> String {
555        guard let first = items.first else { return "" }
556        let ordered = isOrdered(first)
557        // `org-list-get-list-type`: descriptive when the first item has a tag.
558        let description = !ordered && first.firstChild(.itemTag) != nil
559        if description {
560            var out = "<dl>\n"
561            for item in items {
562                let (term, rest) = descriptionParts(item)
563                out += "<dt>\(term)</dt>\n<dd>\(rest)</dd>\n"
564            }
565            return out + "</dl>\n"
566        }
567        let tag = ordered ? "ol" : "ul"
568        var out = "<\(tag)>\n"
569        for item in items { out += listItem(item) }
570        return out + "</\(tag)>\n"
571    }
572
573    /// A description item's term, `(no term)` without one, and the rest of the item.
574    private func descriptionParts(_ item: SyntaxNode) -> (String, String) {
575        var term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
576        if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
577            term = "<code>\(box == "[ ]" ? "[&nbsp;]" : box.uppercased())</code> " + term
578        }
579        var rest = ""
580        for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
581            rest += index == 0 && child.kind == .paragraph ? inline(child).trimmingCharacters(in: .whitespacesAndNewlines) : element(child)
582        }
583        return (term, rest.trimmingCharacters(in: .whitespacesAndNewlines))
584    }
585
586    private func listItem(_ item: SyntaxNode) -> String {
587        // ox-html gives an ordered item's counter as its value.
588        var open = "<li>"
589        if isOrdered(item), let counter = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+|[A-Za-z])\]/) {
590            open = "<li value=\"\(counter.1)\">"
591        }
592        var prefix = ""
593        if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
594            switch box {
595            case "[X]", "[x]":
596                open = "<li class=\"on\">"
597                prefix = "<code>[X]</code> "
598            case "[-]":
599                open = "<li class=\"trans\">"
600                prefix = "<code>[-]</code> "
601            default:
602                open = "<li class=\"off\">"
603                prefix = "<code>[&nbsp;]</code> "
604            }
605        }
606        let paragraphs = item.children.filter { $0.kind == .paragraph }.count
607        var body = ""
608        for child in item.children {
609            if child.kind == .paragraph {
610                let content = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
611                body += paragraphs >= 2 ? "<p>\(content)</p>\n" : content
612            } else {
613                body += element(child)
614            }
615        }
616        if paragraphs >= 2 {
617            body = prefix + body
618        } else {
619            body = prefix + body
620        }
621        return open + body + (body.hasSuffix("\n") ? "" : "") + "</li>\n"
622    }
623
624    // MARK: - Tables
625
626    private func table(_ node: SyntaxNode) -> String {
627        let rows = node.children.filter { $0.kind == .tableRow }
628        var groups: [[SyntaxNode]] = [[]]
629        for row in rows {
630            if row.children.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
631                if !groups[groups.count - 1].isEmpty { groups.append([]) }
632            } else {
633                groups[groups.count - 1].append(row)
634            }
635        }
636        groups.removeAll { $0.isEmpty }
637        var out = "<table>\n"
638        if let caption = affiliated["CAPTION"] { out += "<caption>\(inlineString(caption))</caption>\n" }
639        let hasHeader = groups.count > 1
640        for (index, group) in groups.enumerated() {
641            let header = hasHeader && index == 0
642            if header { out += "<thead>\n" } else if index == (hasHeader ? 1 : 0) { out += "<tbody>\n" }
643            for row in group {
644                out += "<tr>" + row.children.filter { $0.kind == .tableCell }.map { cell in
645                    let content = inline(cell).trimmingCharacters(in: .whitespaces)
646                    return header ? "<th>\(content)</th>" : "<td>\(content)</td>"
647                }.joined() + "</tr>\n"
648            }
649            if header { out += "</thead>\n" }
650        }
651        if !groups.isEmpty, !(hasHeader && groups.count == 1) { out += "</tbody>\n" }
652        return out + "</table>\n"
653    }
654
655    // MARK: - Blocks
656
657    private func block(_ node: SyntaxNode) -> String {
658        var lines = node.text.components(separatedBy: "\n")
659        if lines.last == "" { lines.removeLast() }
660        guard let first = lines.first,
661              let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
662        let type = m.1.lowercased()
663        let parameters = String(m.2)
664        let body = Array(lines.dropFirst().dropLast())
665        // Commas protect `*` and `#+` lines inside blocks.
666        let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
667        let text = unescaped.joined(separator: "\n")
668        switch type {
669        case "src":
670            let language = parameters.split(separator: " ").first.map(String.init)
671            let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
672            let source = lines.joined(separator: "\n")
673            let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source)
674            let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
675            return "<pre><code\(cls)>\(numbered(code, loc: loc, refs: refs, retain: switches.retainLabels))</code></pre>\n"
676        case "example":
677            let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
678            return "<pre>\(numbered(Self.escape(lines.joined(separator: "\n")), loc: loc, refs: refs, retain: switches.retainLabels))</pre>\n"
679        case "quote":
680            return "<blockquote>\n\(blocks(text))</blockquote>\n"
681        case "center":
682            return "<div class=\"center\">\n\(blocks(text))</div>\n"
683        case "verse":
684            let rendered = unescaped.map { line -> String in
685                let indent = line.prefix { $0 == " " }.count
686                return String(repeating: "&nbsp;", count: indent) + inlineString(String(line.dropFirst(indent)))
687            }
688            return "<p class=\"verse\">\n" + rendered.joined(separator: "<br>\n") + "\n</p>\n"
689        case "export":
690            return parameters.lowercased().hasPrefix("html") ? text + "\n" : ""
691        case "comment":
692            return ""
693        default:
694            return "<div class=\"\(Self.escape(type))\">\n\(blocks(text))</div>\n"
695        }
696    }
697
698    /// A src or example block's code without its labels (`org-export-unravel-code`), the lines
699    /// numbered before it, its switches, and its labels by line.
700    private func code(_ block: [String], _ body: [String]) -> (lines: [String], loc: Int?, switches: Coderef.Switches, refs: [Int: String]) {
701        let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
702        let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
703        let key = block.joined(separator: "\n")
704        let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
705        return (lines, switches.numberLines == nil ? nil : loc, switches, refs)
706    }
707
708    /// `org-html-do-format-code`: lines numbered from `loc`, and lines with a label marked as
709    /// its `coderef-` anchor, the label kept after them with `retain`.
710    private func numbered(_ html: String, loc: Int?, refs: [Int: String], retain: Bool) -> String {
711        guard loc != nil || !refs.isEmpty else { return html }
712        let lines = Self.splitLines(html)
713        let width = loc.map { String($0 + lines.count).count } ?? 0
714        return lines.enumerated().map { index, line in
715            var out = loc.map { "<span class=\"linenr\">" + String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1): </span>" } ?? ""
716            out += line
717            guard let ref = refs[index + 1] else { return out }
718            if retain { out += " (\(Self.escape(ref)))" }
719            return "<span id=\"coderef-\(Self.escape(ref))\" class=\"coderef-off\">\(out)</span>"
720        }.joined(separator: "\n")
721    }
722
723    /// Highlighted code split into lines, spans open at a line's end closed there and opened
724    /// again on the next.
725    static func splitLines(_ html: String) -> [String] {
726        var open: [String] = []
727        return html.components(separatedBy: "\n").map { line in
728            var out = open.joined() + line
729            for m in line.matches(of: /<span[^>]*>|<\/span>/) {
730                if m.output.hasPrefix("</") { if !open.isEmpty { open.removeLast() } } else { open.append(String(m.output)) }
731            }
732            out += String(repeating: "</span>", count: open.count)
733            return out
734        }
735    }
736
737    private func dedent(_ lines: [String]) -> [String] {
738        let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
739        let common = indents.min() ?? 0
740        return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
741    }
742
743    // MARK: - Inline
744
745    func inline(_ node: SyntaxNode) -> String {
746        var out = ""
747        for element in node.elements {
748            switch element {
749            case .token(let token):
750                switch token.kind {
751                case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority:
752                    continue
753                default:
754                    out += entities(token.text)
755                }
756            case .node(let child):
757                out += object(child)
758            }
759        }
760        return out
761    }
762
763    /// Text: LaTeX fragments left for MathJax, `\alpha` and friends as characters, `_` and `^`
764    /// scripts as `<sub>` and `<sup>`, as `#+OPTIONS` says.
765    static let textObjects = try! NSRegularExpression(pattern: [
766        #"\\\((.+?)\\\)"#, #"\\\[(.+?)\\\]"#, #"\$\$(.+?)\$\$"#,
767        #"(?<![$\w])\$([^\s$.,;](?:[^$]*?[^\s$.,\\])?)\$(?=[\s.,;:!?'")\]-]|$)"#,
768        #"\\([a-zA-Z]+)(\{\})?"#,
769        #"(?<=\S)([_^])(\{[^{}]*\}|[+-]?[\p{L}\p{N}.,\\]*[\p{L}\p{N}])"#,
770    ].joined(separator: "|"))
771
772    private func entities(_ text: String) -> String {
773        guard text.contains(where: { $0 == "\\" || $0 == "$" || $0 == "_" || $0 == "^" }) else { return Self.escape(text) }
774        let ns = text as NSString
775        var out = ""
776        var at = 0
777        for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
778            out += Self.escape(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
779            at = NSMaxRange(m.range)
780            let whole = ns.substring(with: m.range)
781            func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
782            if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
783                guard options.tex else { continue }
784                hasMath = true
785                out += Self.escape(whole)
786            } else if let name = group(5) {
787                out += Self.escape(OrgEntities.display[name] ?? whole)
788            } else if let marker = group(7), let body = group(8) {
789                let braced = body.hasPrefix("{")
790                if options.scripts == .off || (options.scripts == .braces && !braced) {
791                    out += Self.escape(whole)
792                    continue
793                }
794                let inner = braced ? String(body.dropFirst().dropLast()) : body
795                out += marker == "_" ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
796            } else {
797                out += Self.escape(whole)
798            }
799        }
800        return out + Self.escape(ns.substring(from: at))
801    }
802
803    private func object(_ node: SyntaxNode) -> String {
804        switch node.kind {
805        case .bold: return "<strong>\(inline(node))</strong>"
806        case .italic: return "<em>\(inline(node))</em>"
807        case .underline: return "<u>\(inline(node))</u>"
808        case .strikeThrough: return "<del>\(inline(node))</del>"
809        case .verbatim: return "<code class=\"verbatim\">\(inline(node))</code>"
810        case .code: return "<code>\(inline(node))</code>"
811        case .link: return link(node)
812        case .linkDescription: return inline(node)
813        case .timestamp: return timestamp(node.text)
814        case .footnoteReference: return footnote(node.text)
815        case .entity:
816            let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
817            return Self.escape(OrgEntities.display[name] ?? node.text)
818        case .radioTarget:
819            let inner = String(node.text.dropFirst(3).dropLast(3))
820            return "<a id=\"\(Self.escape(slugOnly(inner)))\">\(Self.escape(inner))</a>"
821        case .superscript, .subscript:
822            let text = node.text
823            let body = text.dropFirst()
824            let braced = body.hasPrefix("{") && body.hasSuffix("}")
825            if options.scripts == .off || (options.scripts == .braces && !braced) { return Self.escape(text) }
826            let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
827            return text.hasPrefix("_") ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
828        case .lineBreak: return "<br>\n"
829        case .macro:
830            guard case .some(let value) = source?.resultsMacro(node) else { return "" }
831            return value.map(inlineString) ?? ""
832        case .target: return ""
833        case .inlineSourceBlock:
834            let exports = source?.exports(at: node.range.lowerBound) ?? "results"
835            source?.inlineResults = exports == "results" || exports == "both"
836            guard exports == "code" || exports == "both" else { return "" }
837            if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "<code>\(Self.escape(String(m.1)))</code>" }
838            return Self.escape(node.text)
839        case .latexFragment:
840            // For MathJax, as ox-html leaves them with `tex:t`; `tex:nil` drops them.
841            guard options.tex else { return "" }
842            hasMath = true
843            return Self.escape(node.text)
844        case .statisticsCookie: return Self.escape(node.text)
845        // `org-html-export-snippet`: only HTML snippets.
846        case .exportSnippet:
847            guard node.tokens.first?.text == "@@html:" else { return "" }
848            return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
849        case .citation:
850            if inTitle { return "" }
851            guard let pieces = citations?.next(node.text) else { return Self.escape(node.text) }
852            return render(pieces)
853        case .inlineBabelCall:
854            source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
855            return ""
856        default: return inline(node)
857        }
858    }
859
860    static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "avif"]
861
862    private func link(_ node: SyntaxNode) -> String {
863        let path = node.linkPath
864        let description = node.firstChild(.linkDescription)
865        guard let path else {
866            // A radio link goes to its target.
867            if !node.text.hasPrefix("<"), !node.text.contains(":") {
868                return "<a href=\"#\(Self.escape(slugOnly(node.text)))\">\(Self.escape(node.text))</a>"
869            }
870            // A plain or angle link.
871            var target = node.text
872            if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
873            return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
874        }
875        // A code reference: the label, or its line's number.
876        if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
877            let name = String(path.dropFirst().dropLast())
878            let resolved = documentTree.flatMap { Coderef.resolve(name, in: $0) } ?? name
879            let text = Coderef.linkText(resolved, description: description.map { $0.text })
880            return "<a href=\"#coderef-\(Self.escape(name))\" class=\"coderef\">\(Self.escape(text))</a>"
881        }
882        // A regexp search has nowhere to go in the export.
883        if path.count >= 2, path.hasPrefix("/"), path.hasSuffix("/") {
884            return description.map(inline) ?? Self.escape(path)
885        }
886        var href = path
887        var label = path
888        if path.hasPrefix("file:") {
889            href = String(path.dropFirst(5))
890            label = href
891        } else if path.hasPrefix("id:") {
892            href = "#" + path.dropFirst(3)
893            label = String(path.dropFirst(3))
894        } else if path.hasPrefix("*") {
895            href = "#" + slugOnly(String(path.dropFirst()))
896        } else if !path.hasPrefix("#"), !path.contains(":"), !path.contains("/"), !path.contains(".") {
897            href = "#" + slugOnly(path)
898        }
899        let isFile = path.hasPrefix("file:") || (!path.contains(":") && (path.contains("/") || path.contains(".")))
900        if isFile, href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".html" }
901        if isFile, let range = href.range(of: ".org::") { href = String(href[..<range.lowerBound]) + ".html" }
902        let ext = (href.split(separator: "?").first.map(String.init) ?? href).split(separator: ".").last.map { $0.lowercased() } ?? ""
903        if description == nil, Self.imageExtensions.contains(ext) {
904            var attributes = ""
905            if let attrs = affiliated["ATTR_HTML"] {
906                for (key, value) in parseAttributes(attrs) where key != "src" {
907                    attributes += " \(key)=\"\(Self.escape(value))\""
908                }
909            }
910            if !attributes.contains(" alt=") { attributes = " alt=\"\(Self.escape((href as NSString).lastPathComponent))\"" + attributes }
911            return "<img src=\"\(Self.escape(href))\"\(attributes)>"
912        }
913        let text = description.map(inline) ?? Self.escape(label)
914        return "<a href=\"\(Self.escape(href))\">\(text)</a>"
915    }
916
917    private func slugOnly(_ text: String) -> String {
918        var slug = ""
919        var dash = false
920        for c in text.lowercased() {
921            if c.isLetter || c.isNumber {
922                if dash, !slug.isEmpty { slug.append("-") }
923                slug.append(c)
924                dash = false
925            } else {
926                dash = true
927            }
928        }
929        return slug
930    }
931
932    /// `:key value :other "quoted value"`.
933    private func parseAttributes(_ text: String) -> [(String, String)] {
934        var pairs: [(String, String)] = []
935        let regex = try! NSRegularExpression(pattern: ":([A-Za-z_-]+)[ \\t]+(\"[^\"]*\"|[^:\\s][^\\s]*)")
936        let ns = text as NSString
937        for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
938            var value = ns.substring(with: m.range(at: 2))
939            if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
940            pairs.append((ns.substring(with: m.range(at: 1)), value))
941        }
942        return pairs
943    }
944
945    private func timestamp(_ text: String) -> String {
946        guard let stamp = Timestamp.parse(text) else { return Self.escape(text) }
947        func date(_ p: Timestamp.Point) -> String { String(format: "%04d-%02d-%02d", p.year, p.month, p.day) }
948        func time(_ p: Timestamp.Point) -> String? {
949            guard let h = p.hour, let m = p.minute else { return nil }
950            return String(format: "%02d:%02d", h, m)
951        }
952        func element(_ p: Timestamp.Point, full: Bool) -> String {
953            let datetime = date(p) + (time(p).map { "T" + $0 } ?? "")
954            let shown = full ? date(p) + (time(p).map { " " + $0 } ?? "") : (time(p) ?? date(p))
955            return "<time class=\"timestamp\" datetime=\"\(datetime)\">\(shown)</time>"
956        }
957        guard let end = stamp.end else { return element(stamp.start, full: true) }
958        let sameDay = end.year == stamp.start.year && end.month == stamp.start.month && end.day == stamp.start.day
959        return element(stamp.start, full: true) + "–" + element(end, full: !sameDay)
960    }
961
962    private func footnote(_ text: String) -> String {
963        guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return Self.escape(text) }
964        var label = String(m.1)
965        let inlineText = m.2.map(String.init)
966        if label.isEmpty {
967            anonymous += 1
968            label = "anonymous-\(anonymous)"
969        }
970        let number: Int
971        if let existing = footnoteNumbers[label] {
972            number = existing
973        } else {
974            let content: FootnoteContent
975            if let inlineText {
976                content = .inline(inlineText)
977            } else if let definition = definitions[label] {
978                content = .definition(definition)
979            } else {
980                return Self.escape(text)
981            }
982            footnoteOrder.append((label, content))
983            number = footnoteOrder.count
984            footnoteNumbers[label] = number
985        }
986        return "<sup class=\"footnote-ref\"><a id=\"fnr-\(number)\" href=\"#fn-\(number)\">\(number)</a></sup>"
987    }
988}