Sources/OrgCore/Export/HTMLExport.swift

3e80720dbff31d31d0bb2f4b66335e8b8b81f78e
orgstar/Sources/OrgCore/Export/HTMLExport.swift history · blame · raw

849 lines · 40484 bytes

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