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