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