Sources/OrgCore/Export/HTMLExport.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Export/HTMLExport.swift history · blame · raw

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