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