Sources/OrgCore/Export/HTMLExport.swift
912 lines · 43145 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 += "&"
167 case "<": out += "<"
168 case ">": out += ">"
169 case "\"": out += """
170 default: out.append(c)
171 }
172 }
173 return out
174 }
175
176 // MARK: - Document
177
178 func document(_ text: String) -> String {
179 let tree = OrgParser.parse(text, defaults: settings)
180 collectDefinitions(tree.root)
181 selected = Self.selection(tree, tags: options.selectTags)
182 var out = ""
183 rendering(tree, text) {
184 for child in tree.root.children { out += element(child) }
185 }
186 out += footnoteSection()
187 return out
188 }
189
190 private var source: ExportSource?
191
192 /// `body` with `tree` as the source of `:exports`.
193 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
194 let saved = source
195 source = ExportSource(tree: tree, text: text)
196 defer { source = saved }
197 return body()
198 }
199
200 private func collectDefinitions(_ node: SyntaxNode) {
201 for child in node.children {
202 if child.kind == .footnoteDefinition {
203 let text = child.text
204 if let m = text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
205 definitions[String(m.1)] = String(text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
206 }
207 } else {
208 collectDefinitions(child)
209 }
210 }
211 }
212
213 private func footnoteSection() -> String {
214 guard !footnoteOrder.isEmpty else { return "" }
215 var out = "<section class=\"footnotes\" aria-label=\"Footnotes\">\n<hr>\n<ol>\n"
216 for (index, note) in footnoteOrder.enumerated() {
217 let n = index + 1
218 let content: String
219 switch note.content {
220 case .definition(let text): content = blocks(text).trimmingCharacters(in: .newlines)
221 case .inline(let text): content = inlineString(text)
222 }
223 out += "<li id=\"fn-\(n)\">\(content)\n <a class=\"footnote-back\" href=\"#fnr-\(n)\" aria-label=\"Back to reference \(n)\">↩</a></li>\n"
224 }
225 return out + "</ol>\n</section>\n"
226 }
227
228 /// Org text rendered as elements, for block and footnote contents.
229 func blocks(_ text: String) -> String {
230 let tree = OrgParser.parse(text, defaults: settings)
231 var out = ""
232 rendering(tree, text) {
233 for child in tree.root.children { out += element(child) }
234 }
235 return out
236 }
237
238 /// One line of org text rendered inline.
239 func inlineString(_ text: String) -> String {
240 let tree = OrgParser.parse(text, defaults: settings)
241 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
242 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
243 }
244
245 /// A citation's or a bibliography entry's pieces: text escaped, prefixes and suffixes as
246 /// Org markup with their blanks kept.
247 private func render(_ pieces: [CiteProcessor.Piece]) -> String {
248 pieces.map { piece in
249 switch piece {
250 case .text(let s): Self.escape(s)
251 case .italic(let s): "<i>" + Self.escape(s) + "</i>"
252 case .org(let s) where s.allSatisfy(\.isWhitespace): s
253 case .org(let s):
254 String(s.prefix { $0.isWhitespace }) + inlineString(s) + (s.allSatisfy(\.isWhitespace) ? "" : String(s.reversed().prefix { $0.isWhitespace }))
255 }
256 }.joined()
257 }
258
259 // MARK: - Elements
260
261 private var affiliated: [String: String] = [:]
262 /// `:exports` of the last src block or call: its results are exported only for `results`
263 /// and `both`; nothing runs.
264 private var lastExports = "code"
265
266 func element(_ node: SyntaxNode) -> String {
267 defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
268 if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
269 defer { lastExports = "code" }
270 if lastExports != "results", lastExports != "both" { return "" }
271 }
272 if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
273 lastExports = exports
274 if exports == "results" || exports == "none" { return "" }
275 }
276 switch node.kind {
277 case .section:
278 guard let heading = node.firstChild(.heading) else { fallthrough }
279 switch Self.sectionExport(heading, options: options, selected: selected) {
280 case .nothing: return ""
281 case .heading: return self.heading(heading)
282 case .all: break
283 }
284 var out = ""
285 for child in node.children { out += element(child) }
286 return out
287 case .zerothSection, .document:
288 var out = ""
289 for child in node.children { out += element(child) }
290 return out
291 case .heading:
292 return heading(node)
293 case .affiliatedKeyword:
294 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
295 if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
296 affiliated[m.1.uppercased()] = String(m.2)
297 }
298 return ""
299 case .paragraph:
300 return paragraph(node)
301 case .keyword where citations != nil && node.text.range(of: "^[ \\t]*#\\+print_bibliography:", options: [.regularExpression, .caseInsensitive]) != nil:
302 return citations!.bibliography.map { "<p>" + render($0) + "</p>\n" }.joined()
303 case .plainList:
304 return list(node)
305 case .table:
306 return table(node)
307 case .block:
308 return block(node)
309 case .horizontalRule:
310 return "<hr>\n"
311 case .inlineTask:
312 // As ox-html: the title in bold, then the contents.
313 var out = "<div class=\"inlinetask\">\n"
314 for child in node.children {
315 if child.kind == .heading {
316 guard child.range.lowerBound == node.range.lowerBound else { continue }
317 let title = child.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
318 let todo = options.todo ? child.tokens.first { $0.kind == .todoKeyword }.map { "<span class=\"todo \(Self.escape($0.text))\">\(Self.escape($0.text))</span> " } ?? "" : ""
319 out += "<b>\(todo)\(title)</b><br>\n"
320 } else {
321 out += element(child)
322 }
323 }
324 return out + "</div>\n"
325 case .latexEnvironment:
326 // For MathJax, as ox-html leaves it with `tex:t`.
327 guard options.tex else { return "" }
328 hasMath = true
329 return Self.escape(node.text.trimmingCharacters(in: .newlines)) + "\n"
330 case .fixedWidth:
331 let lines = node.text.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
332 let trimmed = line.drop { $0 == " " || $0 == "\t" }
333 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
334 }
335 return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
336 case .tableEl:
337 let lines = node.text.components(separatedBy: "\n").filter { !$0.lowercased().contains("#+tblfm") }
338 // As `org-html-table--table.el-table`: cells with their spans, lines kept apart.
339 if let cells = TableEl.cells(lines.joined(separator: "\n")) {
340 var out = "<table class=\"table-el\">\n"
341 for row in Dictionary(grouping: cells, by: \.row).keys.sorted() {
342 out += "<tr>"
343 for cell in cells where cell.row == row {
344 let spans = (cell.colspan > 1 ? " colspan=\"\(cell.colspan)\"" : "") + (cell.rowspan > 1 ? " rowspan=\"\(cell.rowspan)\"" : "")
345 let content = cell.lines.reversed().drop { $0.isEmpty }.reversed().map(Self.escape).joined(separator: "<br>")
346 out += "<td\(spans)>\(content)</td>"
347 }
348 out += "</tr>\n"
349 }
350 return out + "</table>\n"
351 }
352 return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
353 case .dynamicBlock:
354 let lines = node.text.components(separatedBy: "\n")
355 return blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))
356 default:
357 // Keywords, comments, drawers, planning, clocks, footnote definitions, formulas.
358 return ""
359 }
360 }
361
362 private func slug(_ text: String) -> String {
363 var slug = ""
364 var dash = false
365 for c in text.lowercased() {
366 if c.isLetter || c.isNumber {
367 if dash, !slug.isEmpty { slug.append("-") }
368 slug.append(c)
369 dash = false
370 } else {
371 dash = true
372 }
373 }
374 if slug.isEmpty { slug = "section" }
375 var candidate = slug
376 var n = 1
377 while ids.contains(candidate) {
378 candidate = "\(slug)-\(n)"
379 n += 1
380 }
381 ids.insert(candidate)
382 return candidate
383 }
384
385 /// `org-export--selected-trees`: headings with a select tag, everything below them and
386 /// their ancestors; nil when no heading has one.
387 enum SectionExport {
388 case all, heading, nothing
389 }
390
391 /// `org-export--skip-p` for the section under `heading`: excluded tags, COMMENT and
392 /// unselected trees export nothing, archived trees their heading only.
393 static func sectionExport(_ heading: SyntaxNode, options: ExportOptions, selected: Set<Int>?) -> SectionExport {
394 let tags = heading.tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? []
395 let title = heading.firstChild(.title)?.text.trimmingCharacters(in: .whitespaces) ?? ""
396 if tags.contains(where: options.excludeTags.contains) || title == "COMMENT" || title.hasPrefix("COMMENT ") { return .nothing }
397 if let selected, !selected.contains(heading.range.lowerBound) { return .nothing }
398 return tags.contains("ARCHIVE") ? .heading : .all
399 }
400
401 static func selection(_ tree: OrgTree, tags: [String]) -> Set<Int>? {
402 let model = DocumentModel(tree: tree)
403 let picked = model.headings.indices.filter { model.headings[$0].localTags.contains(where: tags.contains) }
404 guard !picked.isEmpty else { return nil }
405 var set: Set<Int> = []
406 for index in picked {
407 set.insert(model.headings[index].headingRange.lowerBound)
408 for a in model.ancestors(of: index) { set.insert(model.headings[a].headingRange.lowerBound) }
409 let level = model.headings[index].level
410 for d in model.headings[(index + 1)...].prefix(while: { $0.level > level }) { set.insert(d.headingRange.lowerBound) }
411 }
412 return set
413 }
414
415 /// The table of contents, as ox-html writes it, or nothing.
416 func tableOfContents() -> String {
417 guard options.toc != nil, !tocEntries.isEmpty else { return "" }
418 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"
419 var depth = 0
420 var open: [Bool] = []
421 let base = tocEntries.map(\.level).min() ?? 1
422 for entry in tocEntries {
423 let level = entry.level - base + 1
424 if level > depth {
425 while depth < level {
426 out += "\n<ul>\n"
427 depth += 1
428 open.append(false)
429 }
430 } else {
431 out += "</li>\n"
432 while depth > level {
433 out += "</ul>\n</li>\n"
434 depth -= 1
435 open.removeLast()
436 }
437 }
438 out += "<li><a href=\"#\(Self.escape(entry.id))\">\(entry.html)</a>"
439 }
440 out += "</li>\n"
441 while depth > 1 {
442 out += "</ul>\n</li>\n"
443 depth -= 1
444 }
445 return out + "</ul>\n</div>\n</div>\n"
446 }
447
448 private func heading(_ node: SyntaxNode) -> String {
449 let tokens = node.tokens
450 let level = tokens.first { $0.kind == .stars }?.text.count ?? 1
451 let title = node.firstChild(.title)
452 let titleText = title?.text.trimmingCharacters(in: .whitespaces) ?? ""
453 // `CUSTOM_ID` from the property drawer that follows.
454 var customID: String?
455 if let section = node.parent, let drawer = section.firstChild(.propertyDrawer) {
456 for property in drawer.children where property.kind == .nodeProperty {
457 if let m = property.text.firstMatch(of: /^[ \t]*:CUSTOM_ID:[ \t]*(\S+)/) { customID = String(m.1) }
458 }
459 }
460 let id = customID ?? slug(titleText)
461 if customID != nil { ids.insert(id) }
462 var parts: [String] = []
463 let h = min(level + 1, 6)
464 if let num = options.num, level <= num {
465 if numbers.count < level { numbers += Array(repeating: 0, count: level - numbers.count) }
466 numbers = Array(numbers.prefix(level))
467 numbers[level - 1] += 1
468 parts.append("<span class=\"section-number-\(h)\">\(numbers.map(String.init).joined(separator: ".")).</span>")
469 }
470 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
471 parts.append("<span class=\"todo \(settings.isDone(todo) ? "done " : "")\(Self.escape(todo))\">\(Self.escape(todo))</span>")
472 }
473 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text {
474 parts.append("<span class=\"priority\">\(Self.escape(priority))</span>")
475 }
476 if let title, !titleText.isEmpty { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
477 var tagParts: [String] = []
478 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
479 tagParts = tags.split(separator: ":").map { "<span class=\"tag\">\(Self.escape(String($0)))</span>" }
480 }
481 if let toc = options.toc, level <= toc {
482 tocEntries.append((level, id, (parts + (options.tagsInTOC ? tagParts : [])).joined(separator: " ")))
483 }
484 parts += tagParts
485 return "<h\(h) id=\"\(Self.escape(id))\">\(parts.joined(separator: " "))</h\(h)>\n"
486 }
487
488 private func paragraph(_ node: SyntaxNode) -> String {
489 let body = inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
490 if let image = soleImage(node), affiliated["CAPTION"] != nil || affiliated["ATTR_HTML"] != nil {
491 var out = "<figure>\n" + image + "\n"
492 if let caption = affiliated["CAPTION"] {
493 figures += 1
494 out += "<figcaption>Figure \(figures): \(inlineString(caption))</figcaption>\n"
495 }
496 return out + "</figure>\n"
497 }
498 return "<p>\(body)</p>\n"
499 }
500
501 /// The `<img>` of a paragraph that is only an image link.
502 private func soleImage(_ node: SyntaxNode) -> String? {
503 let links = node.children.filter { $0.kind == .link }
504 guard links.count == 1, node.children.count == 1,
505 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else { return nil }
506 let html = link(links[0])
507 return html.hasPrefix("<img") ? html : nil
508 }
509
510 // MARK: - Lists
511
512 private func isOrdered(_ item: SyntaxNode) -> Bool {
513 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
514 return bullet.first.map { $0.isNumber || $0.isLetter } ?? false
515 }
516
517 /// As orgo does, a change between ordered and unordered bullets starts another list.
518 private func list(_ node: SyntaxNode) -> String {
519 var runs: [[SyntaxNode]] = []
520 for item in node.children where item.kind == .item {
521 if let last = runs.last?.last, isOrdered(last) == isOrdered(item) {
522 runs[runs.count - 1].append(item)
523 } else {
524 runs.append([item])
525 }
526 }
527 return runs.map(list).joined()
528 }
529
530 private func list(_ items: [SyntaxNode]) -> String {
531 guard let first = items.first else { return "" }
532 let ordered = isOrdered(first)
533 // `org-list-get-list-type`: descriptive when the first item has a tag.
534 let description = !ordered && first.firstChild(.itemTag) != nil
535 if description {
536 var out = "<dl>\n"
537 for item in items {
538 let (term, rest) = descriptionParts(item)
539 out += "<dt>\(term)</dt>\n<dd>\(rest)</dd>\n"
540 }
541 return out + "</dl>\n"
542 }
543 let tag = ordered ? "ol" : "ul"
544 var out = "<\(tag)>\n"
545 for item in items { out += listItem(item) }
546 return out + "</\(tag)>\n"
547 }
548
549 /// A description item's term, `(no term)` without one, and the rest of the item.
550 private func descriptionParts(_ item: SyntaxNode) -> (String, String) {
551 var term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
552 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
553 term = "<code>\(box == "[ ]" ? "[ ]" : box.uppercased())</code> " + term
554 }
555 var rest = ""
556 for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
557 rest += index == 0 && child.kind == .paragraph ? inline(child).trimmingCharacters(in: .whitespacesAndNewlines) : element(child)
558 }
559 return (term, rest.trimmingCharacters(in: .whitespacesAndNewlines))
560 }
561
562 private func listItem(_ item: SyntaxNode) -> String {
563 // ox-html gives an ordered item's counter as its value.
564 var open = "<li>"
565 if isOrdered(item), let counter = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+|[A-Za-z])\]/) {
566 open = "<li value=\"\(counter.1)\">"
567 }
568 var prefix = ""
569 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
570 switch box {
571 case "[X]", "[x]":
572 open = "<li class=\"on\">"
573 prefix = "<code>[X]</code> "
574 case "[-]":
575 open = "<li class=\"trans\">"
576 prefix = "<code>[-]</code> "
577 default:
578 open = "<li class=\"off\">"
579 prefix = "<code>[ ]</code> "
580 }
581 }
582 let paragraphs = item.children.filter { $0.kind == .paragraph }.count
583 var body = ""
584 for child in item.children {
585 if child.kind == .paragraph {
586 let content = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
587 body += paragraphs >= 2 ? "<p>\(content)</p>\n" : content
588 } else {
589 body += element(child)
590 }
591 }
592 if paragraphs >= 2 {
593 body = prefix + body
594 } else {
595 body = prefix + body
596 }
597 return open + body + (body.hasSuffix("\n") ? "" : "") + "</li>\n"
598 }
599
600 // MARK: - Tables
601
602 private func table(_ node: SyntaxNode) -> String {
603 let rows = node.children.filter { $0.kind == .tableRow }
604 var groups: [[SyntaxNode]] = [[]]
605 for row in rows {
606 if row.children.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
607 if !groups[groups.count - 1].isEmpty { groups.append([]) }
608 } else {
609 groups[groups.count - 1].append(row)
610 }
611 }
612 groups.removeAll { $0.isEmpty }
613 var out = "<table>\n"
614 if let caption = affiliated["CAPTION"] { out += "<caption>\(inlineString(caption))</caption>\n" }
615 let hasHeader = groups.count > 1
616 for (index, group) in groups.enumerated() {
617 let header = hasHeader && index == 0
618 if header { out += "<thead>\n" } else if index == (hasHeader ? 1 : 0) { out += "<tbody>\n" }
619 for row in group {
620 out += "<tr>" + row.children.filter { $0.kind == .tableCell }.map { cell in
621 let content = inline(cell).trimmingCharacters(in: .whitespaces)
622 return header ? "<th>\(content)</th>" : "<td>\(content)</td>"
623 }.joined() + "</tr>\n"
624 }
625 if header { out += "</thead>\n" }
626 }
627 if !groups.isEmpty, !(hasHeader && groups.count == 1) { out += "</tbody>\n" }
628 return out + "</table>\n"
629 }
630
631 // MARK: - Blocks
632
633 private func block(_ node: SyntaxNode) -> String {
634 var lines = node.text.components(separatedBy: "\n")
635 if lines.last == "" { lines.removeLast() }
636 guard let first = lines.first,
637 let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
638 let type = m.1.lowercased()
639 let parameters = String(m.2)
640 let body = Array(lines.dropFirst().dropLast())
641 // Commas protect `*` and `#+` lines inside blocks.
642 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
643 let text = unescaped.joined(separator: "\n")
644 switch type {
645 case "src":
646 let language = parameters.split(separator: " ").first.map(String.init)
647 let source = dedent(unescaped).joined(separator: "\n")
648 let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source)
649 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
650 return "<pre><code\(cls)>\(code)</code></pre>\n"
651 case "example":
652 return "<pre>\(Self.escape(dedent(unescaped).joined(separator: "\n")))</pre>\n"
653 case "quote":
654 return "<blockquote>\n\(blocks(text))</blockquote>\n"
655 case "center":
656 return "<div class=\"center\">\n\(blocks(text))</div>\n"
657 case "verse":
658 let rendered = unescaped.map { line -> String in
659 let indent = line.prefix { $0 == " " }.count
660 return String(repeating: " ", count: indent) + inlineString(String(line.dropFirst(indent)))
661 }
662 return "<p class=\"verse\">\n" + rendered.joined(separator: "<br>\n") + "\n</p>\n"
663 case "export":
664 return parameters.lowercased().hasPrefix("html") ? text + "\n" : ""
665 case "comment":
666 return ""
667 default:
668 return "<div class=\"\(Self.escape(type))\">\n\(blocks(text))</div>\n"
669 }
670 }
671
672 private func dedent(_ lines: [String]) -> [String] {
673 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
674 let common = indents.min() ?? 0
675 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
676 }
677
678 // MARK: - Inline
679
680 func inline(_ node: SyntaxNode) -> String {
681 var out = ""
682 for element in node.elements {
683 switch element {
684 case .token(let token):
685 switch token.kind {
686 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority:
687 continue
688 default:
689 out += entities(token.text)
690 }
691 case .node(let child):
692 out += object(child)
693 }
694 }
695 return out
696 }
697
698 /// Text: LaTeX fragments left for MathJax, `\alpha` and friends as characters, `_` and `^`
699 /// scripts as `<sub>` and `<sup>`, as `#+OPTIONS` says.
700 static let textObjects = try! NSRegularExpression(pattern: [
701 #"\\\((.+?)\\\)"#, #"\\\[(.+?)\\\]"#, #"\$\$(.+?)\$\$"#,
702 #"(?<![$\w])\$([^\s$.,;](?:[^$]*?[^\s$.,\\])?)\$(?=[\s.,;:!?'")\]-]|$)"#,
703 #"\\([a-zA-Z]+)(\{\})?"#,
704 #"(?<=\S)([_^])(\{[^{}]*\}|[+-]?[\p{L}\p{N}.,\\]*[\p{L}\p{N}])"#,
705 ].joined(separator: "|"))
706
707 private func entities(_ text: String) -> String {
708 guard text.contains(where: { $0 == "\\" || $0 == "$" || $0 == "_" || $0 == "^" }) else { return Self.escape(text) }
709 let ns = text as NSString
710 var out = ""
711 var at = 0
712 for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
713 out += Self.escape(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
714 at = NSMaxRange(m.range)
715 let whole = ns.substring(with: m.range)
716 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
717 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
718 guard options.tex else { continue }
719 hasMath = true
720 out += Self.escape(whole)
721 } else if let name = group(5) {
722 out += Self.escape(OrgEntities.display[name] ?? whole)
723 } else if let marker = group(7), let body = group(8) {
724 let braced = body.hasPrefix("{")
725 if options.scripts == .off || (options.scripts == .braces && !braced) {
726 out += Self.escape(whole)
727 continue
728 }
729 let inner = braced ? String(body.dropFirst().dropLast()) : body
730 out += marker == "_" ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
731 } else {
732 out += Self.escape(whole)
733 }
734 }
735 return out + Self.escape(ns.substring(from: at))
736 }
737
738 private func object(_ node: SyntaxNode) -> String {
739 switch node.kind {
740 case .bold: return "<strong>\(inline(node))</strong>"
741 case .italic: return "<em>\(inline(node))</em>"
742 case .underline: return "<u>\(inline(node))</u>"
743 case .strikeThrough: return "<del>\(inline(node))</del>"
744 case .verbatim: return "<code class=\"verbatim\">\(inline(node))</code>"
745 case .code: return "<code>\(inline(node))</code>"
746 case .link: return link(node)
747 case .linkDescription: return inline(node)
748 case .timestamp: return timestamp(node.text)
749 case .footnoteReference: return footnote(node.text)
750 case .entity:
751 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
752 return Self.escape(OrgEntities.display[name] ?? node.text)
753 case .radioTarget:
754 let inner = String(node.text.dropFirst(3).dropLast(3))
755 return "<a id=\"\(Self.escape(slugOnly(inner)))\">\(Self.escape(inner))</a>"
756 case .superscript, .subscript:
757 let text = node.text
758 let body = text.dropFirst()
759 let braced = body.hasPrefix("{") && body.hasSuffix("}")
760 if options.scripts == .off || (options.scripts == .braces && !braced) { return Self.escape(text) }
761 let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
762 return text.hasPrefix("_") ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
763 case .lineBreak: return "<br>\n"
764 case .macro:
765 guard case .some(let value) = source?.resultsMacro(node) else { return "" }
766 return value.map(inlineString) ?? ""
767 case .target: return ""
768 case .inlineSourceBlock:
769 let exports = source?.exports(at: node.range.lowerBound) ?? "results"
770 source?.inlineResults = exports == "results" || exports == "both"
771 guard exports == "code" || exports == "both" else { return "" }
772 if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "<code>\(Self.escape(String(m.1)))</code>" }
773 return Self.escape(node.text)
774 case .latexFragment:
775 // For MathJax, as ox-html leaves them with `tex:t`; `tex:nil` drops them.
776 guard options.tex else { return "" }
777 hasMath = true
778 return Self.escape(node.text)
779 case .statisticsCookie: return Self.escape(node.text)
780 // `org-html-export-snippet`: only HTML snippets.
781 case .exportSnippet:
782 guard node.tokens.first?.text == "@@html:" else { return "" }
783 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
784 case .citation:
785 if inTitle { return "" }
786 guard let pieces = citations?.next(node.text) else { return Self.escape(node.text) }
787 return render(pieces)
788 case .inlineBabelCall:
789 source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
790 return ""
791 default: return inline(node)
792 }
793 }
794
795 static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "avif"]
796
797 private func link(_ node: SyntaxNode) -> String {
798 let path = node.tokens.first { $0.kind == .linkPath }?.text
799 let description = node.firstChild(.linkDescription)
800 guard let path else {
801 // A radio link goes to its target.
802 if !node.text.hasPrefix("<"), !node.text.contains(":") {
803 return "<a href=\"#\(Self.escape(slugOnly(node.text)))\">\(Self.escape(node.text))</a>"
804 }
805 // A plain or angle link.
806 var target = node.text
807 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
808 return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
809 }
810 var href = path
811 var label = path
812 if path.hasPrefix("file:") {
813 href = String(path.dropFirst(5))
814 label = href
815 } else if path.hasPrefix("id:") {
816 href = "#" + path.dropFirst(3)
817 label = String(path.dropFirst(3))
818 } else if path.hasPrefix("*") {
819 href = "#" + slugOnly(String(path.dropFirst()))
820 } else if !path.hasPrefix("#"), !path.contains(":"), !path.contains("/"), !path.contains(".") {
821 href = "#" + slugOnly(path)
822 }
823 let isFile = path.hasPrefix("file:") || (!path.contains(":") && (path.contains("/") || path.contains(".")))
824 if isFile, href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".html" }
825 if isFile, let range = href.range(of: ".org::") { href = String(href[..<range.lowerBound]) + ".html" }
826 let ext = (href.split(separator: "?").first.map(String.init) ?? href).split(separator: ".").last.map { $0.lowercased() } ?? ""
827 if description == nil, Self.imageExtensions.contains(ext) {
828 var attributes = ""
829 if let attrs = affiliated["ATTR_HTML"] {
830 for (key, value) in parseAttributes(attrs) where key != "src" {
831 attributes += " \(key)=\"\(Self.escape(value))\""
832 }
833 }
834 if !attributes.contains(" alt=") { attributes = " alt=\"\(Self.escape((href as NSString).lastPathComponent))\"" + attributes }
835 return "<img src=\"\(Self.escape(href))\"\(attributes)>"
836 }
837 let text = description.map(inline) ?? Self.escape(label)
838 return "<a href=\"\(Self.escape(href))\">\(text)</a>"
839 }
840
841 private func slugOnly(_ text: String) -> String {
842 var slug = ""
843 var dash = false
844 for c in text.lowercased() {
845 if c.isLetter || c.isNumber {
846 if dash, !slug.isEmpty { slug.append("-") }
847 slug.append(c)
848 dash = false
849 } else {
850 dash = true
851 }
852 }
853 return slug
854 }
855
856 /// `:key value :other "quoted value"`.
857 private func parseAttributes(_ text: String) -> [(String, String)] {
858 var pairs: [(String, String)] = []
859 let regex = try! NSRegularExpression(pattern: ":([A-Za-z_-]+)[ \\t]+(\"[^\"]*\"|[^:\\s][^\\s]*)")
860 let ns = text as NSString
861 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
862 var value = ns.substring(with: m.range(at: 2))
863 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
864 pairs.append((ns.substring(with: m.range(at: 1)), value))
865 }
866 return pairs
867 }
868
869 private func timestamp(_ text: String) -> String {
870 guard let stamp = Timestamp.parse(text) else { return Self.escape(text) }
871 func date(_ p: Timestamp.Point) -> String { String(format: "%04d-%02d-%02d", p.year, p.month, p.day) }
872 func time(_ p: Timestamp.Point) -> String? {
873 guard let h = p.hour, let m = p.minute else { return nil }
874 return String(format: "%02d:%02d", h, m)
875 }
876 func element(_ p: Timestamp.Point, full: Bool) -> String {
877 let datetime = date(p) + (time(p).map { "T" + $0 } ?? "")
878 let shown = full ? date(p) + (time(p).map { " " + $0 } ?? "") : (time(p) ?? date(p))
879 return "<time class=\"timestamp\" datetime=\"\(datetime)\">\(shown)</time>"
880 }
881 guard let end = stamp.end else { return element(stamp.start, full: true) }
882 let sameDay = end.year == stamp.start.year && end.month == stamp.start.month && end.day == stamp.start.day
883 return element(stamp.start, full: true) + "–" + element(end, full: !sameDay)
884 }
885
886 private func footnote(_ text: String) -> String {
887 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return Self.escape(text) }
888 var label = String(m.1)
889 let inlineText = m.2.map(String.init)
890 if label.isEmpty {
891 anonymous += 1
892 label = "anonymous-\(anonymous)"
893 }
894 let number: Int
895 if let existing = footnoteNumbers[label] {
896 number = existing
897 } else {
898 let content: FootnoteContent
899 if let inlineText {
900 content = .inline(inlineText)
901 } else if let definition = definitions[label] {
902 content = .definition(definition)
903 } else {
904 return Self.escape(text)
905 }
906 footnoteOrder.append((label, content))
907 number = footnoteOrder.count
908 footnoteNumbers[label] = number
909 }
910 return "<sup class=\"footnote-ref\"><a id=\"fnr-\(number)\" href=\"#fn-\(number)\">\(number)</a></sup>"
911 }
912}