Sources/OrgCore/Export/HTMLExport.swift

433d982dfac259414e8cbec24352502a4499fccf
orgstar/Sources/OrgCore/Export/HTMLExport.swift

835 lines · 39566 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 : 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            return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
291        case .dynamicBlock:
292            let lines = node.text.components(separatedBy: "\n")
293            return blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))
294        default:
295            // Keywords, comments, drawers, planning, clocks, footnote definitions, formulas.
296            return ""
297        }
298    }
299
300    /// The `:exports` value of a src block, or nil for other blocks.
301    static func srcExports(_ node: SyntaxNode) -> String? {
302        guard DocumentModel.isSrcBlock(node) else { return nil }
303        let first = node.text.components(separatedBy: "\n").first ?? ""
304        if let m = first.firstMatch(of: /:exports[ \t]+(\S+)/) { return m.1.lowercased() }
305        return "code"
306    }
307
308    private func slug(_ text: String) -> String {
309        var slug = ""
310        var dash = false
311        for c in text.lowercased() {
312            if c.isLetter || c.isNumber {
313                if dash, !slug.isEmpty { slug.append("-") }
314                slug.append(c)
315                dash = false
316            } else {
317                dash = true
318            }
319        }
320        if slug.isEmpty { slug = "section" }
321        var candidate = slug
322        var n = 1
323        while ids.contains(candidate) {
324            candidate = "\(slug)-\(n)"
325            n += 1
326        }
327        ids.insert(candidate)
328        return candidate
329    }
330
331    /// `org-export--selected-trees`: headings with a select tag, everything below them and
332    /// their ancestors; nil when no heading has one.
333    static func selection(_ tree: OrgTree, tags: [String]) -> Set<Int>? {
334        let model = DocumentModel(tree: tree)
335        let picked = model.headings.indices.filter { model.headings[$0].localTags.contains(where: tags.contains) }
336        guard !picked.isEmpty else { return nil }
337        var set: Set<Int> = []
338        for index in picked {
339            set.insert(model.headings[index].headingRange.lowerBound)
340            for a in model.ancestors(of: index) { set.insert(model.headings[a].headingRange.lowerBound) }
341            let level = model.headings[index].level
342            for d in model.headings[(index + 1)...].prefix(while: { $0.level > level }) { set.insert(d.headingRange.lowerBound) }
343        }
344        return set
345    }
346
347    /// The table of contents, as ox-html writes it, or nothing.
348    func tableOfContents() -> String {
349        guard options.toc != nil, !tocEntries.isEmpty else { return "" }
350        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"
351        var depth = 0
352        var open: [Bool] = []
353        let base = tocEntries.map(\.level).min() ?? 1
354        for entry in tocEntries {
355            let level = entry.level - base + 1
356            if level > depth {
357                while depth < level {
358                    out += "\n<ul>\n"
359                    depth += 1
360                    open.append(false)
361                }
362            } else {
363                out += "</li>\n"
364                while depth > level {
365                    out += "</ul>\n</li>\n"
366                    depth -= 1
367                    open.removeLast()
368                }
369            }
370            out += "<li><a href=\"#\(Self.escape(entry.id))\">\(entry.html)</a>"
371        }
372        out += "</li>\n"
373        while depth > 1 {
374            out += "</ul>\n</li>\n"
375            depth -= 1
376        }
377        return out + "</ul>\n</div>\n</div>\n"
378    }
379
380    private func heading(_ node: SyntaxNode) -> String {
381        let tokens = node.tokens
382        let level = tokens.first { $0.kind == .stars }?.text.count ?? 1
383        let title = node.firstChild(.title)
384        let titleText = title?.text.trimmingCharacters(in: .whitespaces) ?? ""
385        // `CUSTOM_ID` from the property drawer that follows.
386        var customID: String?
387        if let section = node.parent, let drawer = section.firstChild(.propertyDrawer) {
388            for property in drawer.children where property.kind == .nodeProperty {
389                if let m = property.text.firstMatch(of: /^[ \t]*:CUSTOM_ID:[ \t]*(\S+)/) { customID = String(m.1) }
390            }
391        }
392        let id = customID ?? slug(titleText)
393        if customID != nil { ids.insert(id) }
394        var parts: [String] = []
395        let h = min(level + 1, 6)
396        if let num = options.num, level <= num {
397            if numbers.count < level { numbers += Array(repeating: 0, count: level - numbers.count) }
398            numbers = Array(numbers.prefix(level))
399            numbers[level - 1] += 1
400            parts.append("<span class=\"section-number-\(h)\">\(numbers.map(String.init).joined(separator: ".")).</span>")
401        }
402        if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
403            parts.append("<span class=\"todo \(settings.isDone(todo) ? "done " : "")\(Self.escape(todo))\">\(Self.escape(todo))</span>")
404        }
405        if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text {
406            parts.append("<span class=\"priority\">\(Self.escape(priority))</span>")
407        }
408        if let title, !titleText.isEmpty { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
409        var tagParts: [String] = []
410        if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
411            tagParts = tags.split(separator: ":").map { "<span class=\"tag\">\(Self.escape(String($0)))</span>" }
412        }
413        if let toc = options.toc, level <= toc {
414            tocEntries.append((level, id, (parts + (options.tagsInTOC ? tagParts : [])).joined(separator: " ")))
415        }
416        parts += tagParts
417        return "<h\(h) id=\"\(Self.escape(id))\">\(parts.joined(separator: " "))</h\(h)>\n"
418    }
419
420    private func paragraph(_ node: SyntaxNode) -> String {
421        let body = inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
422        if let image = soleImage(node), affiliated["CAPTION"] != nil || affiliated["ATTR_HTML"] != nil {
423            var out = "<figure>\n" + image + "\n"
424            if let caption = affiliated["CAPTION"] {
425                figures += 1
426                out += "<figcaption>Figure \(figures): \(inlineString(caption))</figcaption>\n"
427            }
428            return out + "</figure>\n"
429        }
430        return "<p>\(body)</p>\n"
431    }
432
433    /// The `<img>` of a paragraph that is only an image link.
434    private func soleImage(_ node: SyntaxNode) -> String? {
435        let links = node.children.filter { $0.kind == .link }
436        guard links.count == 1, node.children.count == 1,
437              node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else { return nil }
438        let html = link(links[0])
439        return html.hasPrefix("<img") ? html : nil
440    }
441
442    // MARK: - Lists
443
444    private func isOrdered(_ item: SyntaxNode) -> Bool {
445        let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
446        return bullet.first.map { $0.isNumber || $0.isLetter } ?? false
447    }
448
449    /// As orgo does, a change between ordered and unordered bullets starts another list.
450    private func list(_ node: SyntaxNode) -> String {
451        var runs: [[SyntaxNode]] = []
452        for item in node.children where item.kind == .item {
453            if let last = runs.last?.last, isOrdered(last) == isOrdered(item) {
454                runs[runs.count - 1].append(item)
455            } else {
456                runs.append([item])
457            }
458        }
459        return runs.map(list).joined()
460    }
461
462    private func list(_ items: [SyntaxNode]) -> String {
463        guard let first = items.first else { return "" }
464        let ordered = isOrdered(first)
465        // `org-list-get-list-type`: descriptive when the first item has a tag.
466        let description = !ordered && first.firstChild(.itemTag) != nil
467        if description {
468            var out = "<dl>\n"
469            for item in items {
470                let (term, rest) = descriptionParts(item)
471                out += "<dt>\(term)</dt>\n<dd>\(rest)</dd>\n"
472            }
473            return out + "</dl>\n"
474        }
475        let tag = ordered ? "ol" : "ul"
476        var out = "<\(tag)>\n"
477        for item in items { out += listItem(item) }
478        return out + "</\(tag)>\n"
479    }
480
481    /// A description item's term, `(no term)` without one, and the rest of the item.
482    private func descriptionParts(_ item: SyntaxNode) -> (String, String) {
483        var term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
484        if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
485            term = "<code>\(box == "[ ]" ? "[&nbsp;]" : box.uppercased())</code> " + term
486        }
487        var rest = ""
488        for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
489            rest += index == 0 && child.kind == .paragraph ? inline(child).trimmingCharacters(in: .whitespacesAndNewlines) : element(child)
490        }
491        return (term, rest.trimmingCharacters(in: .whitespacesAndNewlines))
492    }
493
494    private func listItem(_ item: SyntaxNode) -> String {
495        // ox-html gives an ordered item's counter as its value.
496        var open = "<li>"
497        if isOrdered(item), let counter = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+|[A-Za-z])\]/) {
498            open = "<li value=\"\(counter.1)\">"
499        }
500        var prefix = ""
501        if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
502            switch box {
503            case "[X]", "[x]":
504                open = "<li class=\"on\">"
505                prefix = "<code>[X]</code> "
506            case "[-]":
507                open = "<li class=\"trans\">"
508                prefix = "<code>[-]</code> "
509            default:
510                open = "<li class=\"off\">"
511                prefix = "<code>[&nbsp;]</code> "
512            }
513        }
514        let paragraphs = item.children.filter { $0.kind == .paragraph }.count
515        var body = ""
516        for child in item.children {
517            if child.kind == .paragraph {
518                let content = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
519                body += paragraphs >= 2 ? "<p>\(content)</p>\n" : content
520            } else {
521                body += element(child)
522            }
523        }
524        if paragraphs >= 2 {
525            body = prefix + body
526        } else {
527            body = prefix + body
528        }
529        return open + body + (body.hasSuffix("\n") ? "" : "") + "</li>\n"
530    }
531
532    // MARK: - Tables
533
534    private func table(_ node: SyntaxNode) -> String {
535        let rows = node.children.filter { $0.kind == .tableRow }
536        var groups: [[SyntaxNode]] = [[]]
537        for row in rows {
538            if row.children.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
539                if !groups[groups.count - 1].isEmpty { groups.append([]) }
540            } else {
541                groups[groups.count - 1].append(row)
542            }
543        }
544        groups.removeAll { $0.isEmpty }
545        var out = "<table>\n"
546        if let caption = affiliated["CAPTION"] { out += "<caption>\(inlineString(caption))</caption>\n" }
547        let hasHeader = groups.count > 1
548        for (index, group) in groups.enumerated() {
549            let header = hasHeader && index == 0
550            if header { out += "<thead>\n" } else if index == (hasHeader ? 1 : 0) { out += "<tbody>\n" }
551            for row in group {
552                out += "<tr>" + row.children.filter { $0.kind == .tableCell }.map { cell in
553                    let content = inline(cell).trimmingCharacters(in: .whitespaces)
554                    return header ? "<th>\(content)</th>" : "<td>\(content)</td>"
555                }.joined() + "</tr>\n"
556            }
557            if header { out += "</thead>\n" }
558        }
559        if !groups.isEmpty, !(hasHeader && groups.count == 1) { out += "</tbody>\n" }
560        return out + "</table>\n"
561    }
562
563    // MARK: - Blocks
564
565    private func block(_ node: SyntaxNode) -> String {
566        var lines = node.text.components(separatedBy: "\n")
567        if lines.last == "" { lines.removeLast() }
568        guard let first = lines.first,
569              let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
570        let type = m.1.lowercased()
571        let parameters = String(m.2)
572        let body = Array(lines.dropFirst().dropLast())
573        // Commas protect `*` and `#+` lines inside blocks.
574        let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
575        let text = unescaped.joined(separator: "\n")
576        switch type {
577        case "src":
578            let language = parameters.split(separator: " ").first.map(String.init)
579            let code = Self.escape(dedent(unescaped).joined(separator: "\n"))
580            let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
581            return "<pre><code\(cls)>\(code)</code></pre>\n"
582        case "example":
583            return "<pre>\(Self.escape(dedent(unescaped).joined(separator: "\n")))</pre>\n"
584        case "quote":
585            return "<blockquote>\n\(blocks(text))</blockquote>\n"
586        case "center":
587            return "<div class=\"center\">\n\(blocks(text))</div>\n"
588        case "verse":
589            let rendered = unescaped.map { line -> String in
590                let indent = line.prefix { $0 == " " }.count
591                return String(repeating: "&nbsp;", count: indent) + inlineString(String(line.dropFirst(indent)))
592            }
593            return "<p class=\"verse\">\n" + rendered.joined(separator: "<br>\n") + "\n</p>\n"
594        case "export":
595            return parameters.lowercased().hasPrefix("html") ? text + "\n" : ""
596        case "comment":
597            return ""
598        default:
599            return "<div class=\"\(Self.escape(type))\">\n\(blocks(text))</div>\n"
600        }
601    }
602
603    private func dedent(_ lines: [String]) -> [String] {
604        let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
605        let common = indents.min() ?? 0
606        return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
607    }
608
609    // MARK: - Inline
610
611    func inline(_ node: SyntaxNode) -> String {
612        var out = ""
613        for element in node.elements {
614            switch element {
615            case .token(let token):
616                switch token.kind {
617                case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority:
618                    continue
619                default:
620                    out += entities(token.text)
621                }
622            case .node(let child):
623                out += object(child)
624            }
625        }
626        return out
627    }
628
629    /// Text: LaTeX fragments left for MathJax, `\alpha` and friends as characters, `_` and `^`
630    /// scripts as `<sub>` and `<sup>`, as `#+OPTIONS` says.
631    static let textObjects = try! NSRegularExpression(pattern: [
632        #"\\\((.+?)\\\)"#, #"\\\[(.+?)\\\]"#, #"\$\$(.+?)\$\$"#,
633        #"(?<![$\w])\$([^\s$.,;](?:[^$]*?[^\s$.,\\])?)\$(?=[\s.,;:!?'")\]-]|$)"#,
634        #"\\([a-zA-Z]+)(\{\})?"#,
635        #"(?<=\S)([_^])(\{[^{}]*\}|[+-]?[\p{L}\p{N}.,\\]*[\p{L}\p{N}])"#,
636    ].joined(separator: "|"))
637
638    private func entities(_ text: String) -> String {
639        guard text.contains(where: { $0 == "\\" || $0 == "$" || $0 == "_" || $0 == "^" }) else { return Self.escape(text) }
640        let ns = text as NSString
641        var out = ""
642        var at = 0
643        for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
644            out += Self.escape(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
645            at = NSMaxRange(m.range)
646            let whole = ns.substring(with: m.range)
647            func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
648            if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
649                guard options.tex else { continue }
650                hasMath = true
651                out += Self.escape(whole)
652            } else if let name = group(5) {
653                out += Self.escape(OrgEntities.display[name] ?? whole)
654            } else if let marker = group(7), let body = group(8) {
655                let braced = body.hasPrefix("{")
656                if options.scripts == .off || (options.scripts == .braces && !braced) {
657                    out += Self.escape(whole)
658                    continue
659                }
660                let inner = braced ? String(body.dropFirst().dropLast()) : body
661                out += marker == "_" ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
662            } else {
663                out += Self.escape(whole)
664            }
665        }
666        return out + Self.escape(ns.substring(from: at))
667    }
668
669    private func object(_ node: SyntaxNode) -> String {
670        switch node.kind {
671        case .bold: return "<strong>\(inline(node))</strong>"
672        case .italic: return "<em>\(inline(node))</em>"
673        case .underline: return "<u>\(inline(node))</u>"
674        case .strikeThrough: return "<del>\(inline(node))</del>"
675        case .verbatim: return "<code class=\"verbatim\">\(inline(node))</code>"
676        case .code: return "<code>\(inline(node))</code>"
677        case .link: return link(node)
678        case .linkDescription: return inline(node)
679        case .timestamp: return timestamp(node.text)
680        case .footnoteReference: return footnote(node.text)
681        case .entity:
682            let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
683            return Self.escape(OrgEntities.display[name] ?? node.text)
684        case .radioTarget:
685            let inner = String(node.text.dropFirst(3).dropLast(3))
686            return "<a id=\"\(Self.escape(slugOnly(inner)))\">\(Self.escape(inner))</a>"
687        case .superscript, .subscript:
688            let text = node.text
689            let body = text.dropFirst()
690            let braced = body.hasPrefix("{") && body.hasSuffix("}")
691            if options.scripts == .off || (options.scripts == .braces && !braced) { return Self.escape(text) }
692            let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
693            return text.hasPrefix("_") ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
694        case .lineBreak: return "<br>\n"
695        case .target, .macro: return ""
696        case .inlineSourceBlock:
697            if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "<code>\(Self.escape(String(m.1)))</code>" }
698            return Self.escape(node.text)
699        case .latexFragment:
700            // For MathJax, as ox-html leaves them with `tex:t`; `tex:nil` drops them.
701            guard options.tex else { return "" }
702            hasMath = true
703            return Self.escape(node.text)
704        case .statisticsCookie: return Self.escape(node.text)
705        // `org-html-export-snippet`: only HTML snippets.
706        case .exportSnippet:
707            guard node.tokens.first?.text == "@@html:" else { return "" }
708            return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
709        case .citation:
710            if inTitle { return "" }
711            guard let pieces = citations?.next(node.text) else { return Self.escape(node.text) }
712            return render(pieces)
713        case .inlineBabelCall: return Self.escape(node.text)
714        default: return inline(node)
715        }
716    }
717
718    static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "avif"]
719
720    private func link(_ node: SyntaxNode) -> String {
721        let path = node.tokens.first { $0.kind == .linkPath }?.text
722        let description = node.firstChild(.linkDescription)
723        guard let path else {
724            // A radio link goes to its target.
725            if !node.text.hasPrefix("<"), !node.text.contains(":") {
726                return "<a href=\"#\(Self.escape(slugOnly(node.text)))\">\(Self.escape(node.text))</a>"
727            }
728            // A plain or angle link.
729            var target = node.text
730            if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
731            return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
732        }
733        var href = path
734        var label = path
735        if path.hasPrefix("file:") {
736            href = String(path.dropFirst(5))
737            label = href
738        } else if path.hasPrefix("id:") {
739            href = "#" + path.dropFirst(3)
740            label = String(path.dropFirst(3))
741        } else if path.hasPrefix("*") {
742            href = "#" + slugOnly(String(path.dropFirst()))
743        } else if !path.hasPrefix("#"), !path.contains(":"), !path.contains("/"), !path.contains(".") {
744            href = "#" + slugOnly(path)
745        }
746        let isFile = path.hasPrefix("file:") || (!path.contains(":") && (path.contains("/") || path.contains(".")))
747        if isFile, href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".html" }
748        if isFile, let range = href.range(of: ".org::") { href = String(href[..<range.lowerBound]) + ".html" }
749        let ext = (href.split(separator: "?").first.map(String.init) ?? href).split(separator: ".").last.map { $0.lowercased() } ?? ""
750        if description == nil, Self.imageExtensions.contains(ext) {
751            var attributes = ""
752            if let attrs = affiliated["ATTR_HTML"] {
753                for (key, value) in parseAttributes(attrs) where key != "src" {
754                    attributes += " \(key)=\"\(Self.escape(value))\""
755                }
756            }
757            if !attributes.contains(" alt=") { attributes = " alt=\"\(Self.escape((href as NSString).lastPathComponent))\"" + attributes }
758            return "<img src=\"\(Self.escape(href))\"\(attributes)>"
759        }
760        let text = description.map(inline) ?? Self.escape(label)
761        return "<a href=\"\(Self.escape(href))\">\(text)</a>"
762    }
763
764    private func slugOnly(_ text: String) -> String {
765        var slug = ""
766        var dash = false
767        for c in text.lowercased() {
768            if c.isLetter || c.isNumber {
769                if dash, !slug.isEmpty { slug.append("-") }
770                slug.append(c)
771                dash = false
772            } else {
773                dash = true
774            }
775        }
776        return slug
777    }
778
779    /// `:key value :other "quoted value"`.
780    private func parseAttributes(_ text: String) -> [(String, String)] {
781        var pairs: [(String, String)] = []
782        let regex = try! NSRegularExpression(pattern: ":([A-Za-z_-]+)[ \\t]+(\"[^\"]*\"|[^:\\s][^\\s]*)")
783        let ns = text as NSString
784        for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
785            var value = ns.substring(with: m.range(at: 2))
786            if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
787            pairs.append((ns.substring(with: m.range(at: 1)), value))
788        }
789        return pairs
790    }
791
792    private func timestamp(_ text: String) -> String {
793        guard let stamp = Timestamp.parse(text) else { return Self.escape(text) }
794        func date(_ p: Timestamp.Point) -> String { String(format: "%04d-%02d-%02d", p.year, p.month, p.day) }
795        func time(_ p: Timestamp.Point) -> String? {
796            guard let h = p.hour, let m = p.minute else { return nil }
797            return String(format: "%02d:%02d", h, m)
798        }
799        func element(_ p: Timestamp.Point, full: Bool) -> String {
800            let datetime = date(p) + (time(p).map { "T" + $0 } ?? "")
801            let shown = full ? date(p) + (time(p).map { " " + $0 } ?? "") : (time(p) ?? date(p))
802            return "<time class=\"timestamp\" datetime=\"\(datetime)\">\(shown)</time>"
803        }
804        guard let end = stamp.end else { return element(stamp.start, full: true) }
805        let sameDay = end.year == stamp.start.year && end.month == stamp.start.month && end.day == stamp.start.day
806        return element(stamp.start, full: true) + "–" + element(end, full: !sameDay)
807    }
808
809    private func footnote(_ text: String) -> String {
810        guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return Self.escape(text) }
811        var label = String(m.1)
812        let inlineText = m.2.map(String.init)
813        if label.isEmpty {
814            anonymous += 1
815            label = "anonymous-\(anonymous)"
816        }
817        let number: Int
818        if let existing = footnoteNumbers[label] {
819            number = existing
820        } else {
821            let content: FootnoteContent
822            if let inlineText {
823                content = .inline(inlineText)
824            } else if let definition = definitions[label] {
825                content = .definition(definition)
826            } else {
827                return Self.escape(text)
828            }
829            footnoteOrder.append((label, content))
830            number = footnoteOrder.count
831            footnoteNumbers[label] = number
832        }
833        return "<sup class=\"footnote-ref\"><a id=\"fnr-\(number)\" href=\"#fn-\(number)\">\(number)</a></sup>"
834    }
835}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form