Sources/OrgCore/Export/HTMLExport.swift

6c7e17cffd372d46e92a8c9dccad1de263844541
orgstar/Sources/OrgCore/Export/HTMLExport.swift

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