Sources/OrgCore/Export/HTMLExport.swift
775 lines · 35712 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 .fixedWidth:
239 let lines = node.text.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
240 let trimmed = line.drop { $0 == " " || $0 == "\t" }
241 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
242 }
243 return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
244 case .dynamicBlock:
245 let lines = node.text.components(separatedBy: "\n")
246 return blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))
247 default:
248 // Keywords, comments, drawers, planning, clocks, footnote definitions, formulas.
249 return ""
250 }
251 }
252
253 /// The `:exports` value of a src block, or nil for other blocks.
254 static func srcExports(_ node: SyntaxNode) -> String? {
255 guard DocumentModel.isSrcBlock(node) else { return nil }
256 let first = node.text.components(separatedBy: "\n").first ?? ""
257 if let m = first.firstMatch(of: /:exports[ \t]+(\S+)/) { return m.1.lowercased() }
258 return "code"
259 }
260
261 private func slug(_ text: String) -> String {
262 var slug = ""
263 var dash = false
264 for c in text.lowercased() {
265 if c.isLetter || c.isNumber {
266 if dash, !slug.isEmpty { slug.append("-") }
267 slug.append(c)
268 dash = false
269 } else {
270 dash = true
271 }
272 }
273 if slug.isEmpty { slug = "section" }
274 var candidate = slug
275 var n = 1
276 while ids.contains(candidate) {
277 candidate = "\(slug)-\(n)"
278 n += 1
279 }
280 ids.insert(candidate)
281 return candidate
282 }
283
284 /// `org-export--selected-trees`: headings with a select tag, everything below them and
285 /// their ancestors; nil when no heading has one.
286 static func selection(_ tree: OrgTree, tags: [String]) -> Set<Int>? {
287 let model = DocumentModel(tree: tree)
288 let picked = model.headings.indices.filter { model.headings[$0].localTags.contains(where: tags.contains) }
289 guard !picked.isEmpty else { return nil }
290 var set: Set<Int> = []
291 for index in picked {
292 set.insert(model.headings[index].headingRange.lowerBound)
293 for a in model.ancestors(of: index) { set.insert(model.headings[a].headingRange.lowerBound) }
294 let level = model.headings[index].level
295 for d in model.headings[(index + 1)...].prefix(while: { $0.level > level }) { set.insert(d.headingRange.lowerBound) }
296 }
297 return set
298 }
299
300 /// The table of contents, as ox-html writes it, or nothing.
301 func tableOfContents() -> String {
302 guard options.toc != nil, !tocEntries.isEmpty else { return "" }
303 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"
304 var depth = 0
305 var open: [Bool] = []
306 let base = tocEntries.map(\.level).min() ?? 1
307 for entry in tocEntries {
308 let level = entry.level - base + 1
309 if level > depth {
310 while depth < level {
311 out += "\n<ul>\n"
312 depth += 1
313 open.append(false)
314 }
315 } else {
316 out += "</li>\n"
317 while depth > level {
318 out += "</ul>\n</li>\n"
319 depth -= 1
320 open.removeLast()
321 }
322 }
323 out += "<li><a href=\"#\(Self.escape(entry.id))\">\(entry.html)</a>"
324 }
325 out += "</li>\n"
326 while depth > 1 {
327 out += "</ul>\n</li>\n"
328 depth -= 1
329 }
330 return out + "</ul>\n</div>\n</div>\n"
331 }
332
333 private func heading(_ node: SyntaxNode) -> String {
334 let tokens = node.tokens
335 let level = tokens.first { $0.kind == .stars }?.text.count ?? 1
336 let title = node.firstChild(.title)
337 let titleText = title?.text.trimmingCharacters(in: .whitespaces) ?? ""
338 // `CUSTOM_ID` from the property drawer that follows.
339 var customID: String?
340 if let section = node.parent, let drawer = section.firstChild(.propertyDrawer) {
341 for property in drawer.children where property.kind == .nodeProperty {
342 if let m = property.text.firstMatch(of: /^[ \t]*:CUSTOM_ID:[ \t]*(\S+)/) { customID = String(m.1) }
343 }
344 }
345 let id = customID ?? slug(titleText)
346 if customID != nil { ids.insert(id) }
347 var parts: [String] = []
348 let h = min(level + 1, 6)
349 if let num = options.num, level <= num {
350 if numbers.count < level { numbers += Array(repeating: 0, count: level - numbers.count) }
351 numbers = Array(numbers.prefix(level))
352 numbers[level - 1] += 1
353 parts.append("<span class=\"section-number-\(h)\">\(numbers.map(String.init).joined(separator: ".")).</span>")
354 }
355 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
356 parts.append("<span class=\"todo \(settings.isDone(todo) ? "done " : "")\(Self.escape(todo))\">\(Self.escape(todo))</span>")
357 }
358 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text {
359 parts.append("<span class=\"priority\">\(Self.escape(priority))</span>")
360 }
361 if let title, !titleText.isEmpty { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
362 var tagParts: [String] = []
363 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
364 tagParts = tags.split(separator: ":").map { "<span class=\"tag\">\(Self.escape(String($0)))</span>" }
365 }
366 if let toc = options.toc, level <= toc {
367 tocEntries.append((level, id, (parts + (options.tagsInTOC ? tagParts : [])).joined(separator: " ")))
368 }
369 parts += tagParts
370 return "<h\(h) id=\"\(Self.escape(id))\">\(parts.joined(separator: " "))</h\(h)>\n"
371 }
372
373 private func paragraph(_ node: SyntaxNode) -> String {
374 let body = inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
375 if let image = soleImage(node), affiliated["CAPTION"] != nil || affiliated["ATTR_HTML"] != nil {
376 var out = "<figure>\n" + image + "\n"
377 if let caption = affiliated["CAPTION"] {
378 figures += 1
379 out += "<figcaption>Figure \(figures): \(inlineString(caption))</figcaption>\n"
380 }
381 return out + "</figure>\n"
382 }
383 return "<p>\(body)</p>\n"
384 }
385
386 /// The `<img>` of a paragraph that is only an image link.
387 private func soleImage(_ node: SyntaxNode) -> String? {
388 let links = node.children.filter { $0.kind == .link }
389 guard links.count == 1, node.children.count == 1,
390 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else { return nil }
391 let html = link(links[0])
392 return html.hasPrefix("<img") ? html : nil
393 }
394
395 // MARK: - Lists
396
397 private func isOrdered(_ item: SyntaxNode) -> Bool {
398 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
399 return bullet.first.map { $0.isNumber || $0.isLetter } ?? false
400 }
401
402 /// As orgo does, a change between ordered and unordered bullets starts another list.
403 private func list(_ node: SyntaxNode) -> String {
404 var runs: [[SyntaxNode]] = []
405 for item in node.children where item.kind == .item {
406 if let last = runs.last?.last, isOrdered(last) == isOrdered(item) {
407 runs[runs.count - 1].append(item)
408 } else {
409 runs.append([item])
410 }
411 }
412 return runs.map(list).joined()
413 }
414
415 private func list(_ items: [SyntaxNode]) -> String {
416 guard let first = items.first else { return "" }
417 let ordered = isOrdered(first)
418 let description = !ordered && firstLine(first).contains(" :: ")
419 if description {
420 var out = "<dl>\n"
421 for item in items {
422 let (term, rest) = descriptionParts(item)
423 out += "<dt>\(term)</dt>\n<dd>\(rest)</dd>\n"
424 }
425 return out + "</dl>\n"
426 }
427 let tag = ordered ? "ol" : "ul"
428 var out = "<\(tag)>\n"
429 for item in items { out += listItem(item) }
430 return out + "</\(tag)>\n"
431 }
432
433 private func firstLine(_ item: SyntaxNode) -> String {
434 item.firstChild(.paragraph)?.text.components(separatedBy: "\n").first ?? ""
435 }
436
437 private func descriptionParts(_ item: SyntaxNode) -> (String, String) {
438 guard let paragraph = item.firstChild(.paragraph) else { return ("", "") }
439 let text = paragraph.text
440 guard let separator = text.range(of: " :: ") ?? text.range(of: " ::\n") else { return ("", inline(paragraph)) }
441 let term = inlineString(String(text[..<separator.lowerBound]))
442 var rest = inlineParagraphText(String(text[separator.upperBound...]))
443 for child in item.children where child.kind != .paragraph || child.range != paragraph.range {
444 rest += element(child)
445 }
446 return (term, rest.trimmingCharacters(in: .whitespacesAndNewlines))
447 }
448
449 /// Paragraph text, possibly spanning lines, rendered inline.
450 private func inlineParagraphText(_ text: String) -> String {
451 let tree = OrgParser.parse(text, defaults: settings)
452 let paragraphs = tree.root.descendants().filter { $0.kind == .paragraph }
453 guard !paragraphs.isEmpty else { return Self.escape(text.trimmingCharacters(in: .whitespacesAndNewlines)) }
454 return paragraphs.map { inline($0).trimmingCharacters(in: .whitespacesAndNewlines) }.joined(separator: "\n")
455 }
456
457 private func listItem(_ item: SyntaxNode) -> String {
458 var open = "<li>"
459 var prefix = ""
460 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
461 switch box {
462 case "[X]", "[x]":
463 open = "<li class=\"on\">"
464 prefix = "<code>[X]</code> "
465 case "[-]":
466 open = "<li class=\"trans\">"
467 prefix = "<code>[-]</code> "
468 default:
469 open = "<li class=\"off\">"
470 prefix = "<code>[ ]</code> "
471 }
472 }
473 let paragraphs = item.children.filter { $0.kind == .paragraph }.count
474 var body = ""
475 for child in item.children {
476 if child.kind == .paragraph {
477 let content = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
478 body += paragraphs >= 2 ? "<p>\(content)</p>\n" : content
479 } else {
480 body += element(child)
481 }
482 }
483 if paragraphs >= 2 {
484 body = prefix + body
485 } else {
486 body = prefix + body
487 }
488 return open + body + (body.hasSuffix("\n") ? "" : "") + "</li>\n"
489 }
490
491 // MARK: - Tables
492
493 private func table(_ node: SyntaxNode) -> String {
494 let rows = node.children.filter { $0.kind == .tableRow }
495 var groups: [[SyntaxNode]] = [[]]
496 for row in rows {
497 if row.children.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
498 if !groups[groups.count - 1].isEmpty { groups.append([]) }
499 } else {
500 groups[groups.count - 1].append(row)
501 }
502 }
503 groups.removeAll { $0.isEmpty }
504 var out = "<table>\n"
505 if let caption = affiliated["CAPTION"] { out += "<caption>\(inlineString(caption))</caption>\n" }
506 let hasHeader = groups.count > 1
507 for (index, group) in groups.enumerated() {
508 let header = hasHeader && index == 0
509 if header { out += "<thead>\n" } else if index == (hasHeader ? 1 : 0) { out += "<tbody>\n" }
510 for row in group {
511 out += "<tr>" + row.children.filter { $0.kind == .tableCell }.map { cell in
512 let content = inline(cell).trimmingCharacters(in: .whitespaces)
513 return header ? "<th>\(content)</th>" : "<td>\(content)</td>"
514 }.joined() + "</tr>\n"
515 }
516 if header { out += "</thead>\n" }
517 }
518 if !groups.isEmpty, !(hasHeader && groups.count == 1) { out += "</tbody>\n" }
519 return out + "</table>\n"
520 }
521
522 // MARK: - Blocks
523
524 private func block(_ node: SyntaxNode) -> String {
525 var lines = node.text.components(separatedBy: "\n")
526 if lines.last == "" { lines.removeLast() }
527 guard let first = lines.first,
528 let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
529 let type = m.1.lowercased()
530 let parameters = String(m.2)
531 let body = Array(lines.dropFirst().dropLast())
532 // Commas protect `*` and `#+` lines inside blocks.
533 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
534 let text = unescaped.joined(separator: "\n")
535 switch type {
536 case "src":
537 let language = parameters.split(separator: " ").first.map(String.init)
538 let code = Self.escape(dedent(unescaped).joined(separator: "\n"))
539 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
540 return "<pre><code\(cls)>\(code)</code></pre>\n"
541 case "example":
542 return "<pre>\(Self.escape(dedent(unescaped).joined(separator: "\n")))</pre>\n"
543 case "quote":
544 return "<blockquote>\n\(blocks(text))</blockquote>\n"
545 case "center":
546 return "<div class=\"center\">\n\(blocks(text))</div>\n"
547 case "verse":
548 let rendered = unescaped.map { line -> String in
549 let indent = line.prefix { $0 == " " }.count
550 return String(repeating: " ", count: indent) + inlineString(String(line.dropFirst(indent)))
551 }
552 return "<p class=\"verse\">\n" + rendered.joined(separator: "<br>\n") + "\n</p>\n"
553 case "export":
554 return parameters.lowercased().hasPrefix("html") ? text + "\n" : ""
555 case "comment":
556 return ""
557 default:
558 return "<div class=\"\(Self.escape(type))\">\n\(blocks(text))</div>\n"
559 }
560 }
561
562 private func dedent(_ lines: [String]) -> [String] {
563 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
564 let common = indents.min() ?? 0
565 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
566 }
567
568 // MARK: - Inline
569
570 func inline(_ node: SyntaxNode) -> String {
571 var out = ""
572 for element in node.elements {
573 switch element {
574 case .token(let token):
575 switch token.kind {
576 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority:
577 continue
578 default:
579 out += entities(token.text)
580 }
581 case .node(let child):
582 out += object(child)
583 }
584 }
585 return out
586 }
587
588 /// Text: LaTeX fragments left for MathJax, `\alpha` and friends as characters, `_` and `^`
589 /// scripts as `<sub>` and `<sup>`, as `#+OPTIONS` says.
590 static let textObjects = try! NSRegularExpression(pattern: [
591 #"\\\((.+?)\\\)"#, #"\\\[(.+?)\\\]"#, #"\$\$(.+?)\$\$"#,
592 #"(?<![$\w])\$([^\s$.,;](?:[^$]*?[^\s$.,\\])?)\$(?=[\s.,;:!?'")\]-]|$)"#,
593 #"\\([a-zA-Z]+)(\{\})?"#,
594 #"(?<=\S)([_^])(\{[^{}]*\}|[+-]?[\p{L}\p{N}.,\\]*[\p{L}\p{N}])"#,
595 ].joined(separator: "|"))
596
597 private func entities(_ text: String) -> String {
598 guard text.contains(where: { $0 == "\\" || $0 == "$" || $0 == "_" || $0 == "^" }) else { return Self.escape(text) }
599 let ns = text as NSString
600 var out = ""
601 var at = 0
602 for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
603 out += Self.escape(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
604 at = NSMaxRange(m.range)
605 let whole = ns.substring(with: m.range)
606 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
607 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
608 guard options.tex else { continue }
609 hasMath = true
610 out += Self.escape(whole)
611 } else if let name = group(5) {
612 out += Self.escape(OrgEntities.display[name] ?? whole)
613 } else if let marker = group(7), let body = group(8) {
614 let braced = body.hasPrefix("{")
615 if options.scripts == .off || (options.scripts == .braces && !braced) {
616 out += Self.escape(whole)
617 continue
618 }
619 let inner = braced ? String(body.dropFirst().dropLast()) : body
620 out += marker == "_" ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
621 } else {
622 out += Self.escape(whole)
623 }
624 }
625 return out + Self.escape(ns.substring(from: at))
626 }
627
628 private func object(_ node: SyntaxNode) -> String {
629 switch node.kind {
630 case .bold: return "<strong>\(inline(node))</strong>"
631 case .italic: return "<em>\(inline(node))</em>"
632 case .underline: return "<u>\(inline(node))</u>"
633 case .strikeThrough: return "<del>\(inline(node))</del>"
634 case .verbatim: return "<code class=\"verbatim\">\(inline(node))</code>"
635 case .code: return "<code>\(inline(node))</code>"
636 case .link: return link(node)
637 case .linkDescription: return inline(node)
638 case .timestamp: return timestamp(node.text)
639 case .footnoteReference: return footnote(node.text)
640 case .superscript:
641 let text = node.text
642 let body = text.dropFirst()
643 let braced = body.hasPrefix("{") && body.hasSuffix("}")
644 if options.scripts == .off || (options.scripts == .braces && !braced) { return Self.escape(text) }
645 let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
646 return text.hasPrefix("_") ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
647 case .lineBreak: return "<br>\n"
648 case .target, .macro: return ""
649 case .inlineSourceBlock:
650 if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "<code>\(Self.escape(String(m.1)))</code>" }
651 return Self.escape(node.text)
652 case .latexFragment:
653 // For MathJax, as ox-html leaves them with `tex:t`; `tex:nil` drops them.
654 guard options.tex else { return "" }
655 hasMath = true
656 return Self.escape(node.text)
657 case .statisticsCookie: return Self.escape(node.text)
658 default: return inline(node)
659 }
660 }
661
662 static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "avif"]
663
664 private func link(_ node: SyntaxNode) -> String {
665 let path = node.tokens.first { $0.kind == .linkPath }?.text
666 let description = node.firstChild(.linkDescription)
667 guard let path else {
668 // A plain or angle link.
669 var target = node.text
670 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
671 return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
672 }
673 var href = path
674 var label = path
675 if path.hasPrefix("file:") {
676 href = String(path.dropFirst(5))
677 label = href
678 } else if path.hasPrefix("id:") {
679 href = "#" + path.dropFirst(3)
680 label = String(path.dropFirst(3))
681 } else if path.hasPrefix("*") {
682 href = "#" + slugOnly(String(path.dropFirst()))
683 } else if !path.hasPrefix("#"), !path.contains(":"), !path.contains("/"), !path.contains(".") {
684 href = "#" + slugOnly(path)
685 }
686 let isFile = path.hasPrefix("file:") || (!path.contains(":") && (path.contains("/") || path.contains(".")))
687 if isFile, href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".html" }
688 if isFile, let range = href.range(of: ".org::") { href = String(href[..<range.lowerBound]) + ".html" }
689 let ext = (href.split(separator: "?").first.map(String.init) ?? href).split(separator: ".").last.map { $0.lowercased() } ?? ""
690 if description == nil, Self.imageExtensions.contains(ext) {
691 var attributes = ""
692 if let attrs = affiliated["ATTR_HTML"] {
693 for (key, value) in parseAttributes(attrs) where key != "src" {
694 attributes += " \(key)=\"\(Self.escape(value))\""
695 }
696 }
697 if !attributes.contains(" alt=") { attributes = " alt=\"\(Self.escape((href as NSString).lastPathComponent))\"" + attributes }
698 return "<img src=\"\(Self.escape(href))\"\(attributes)>"
699 }
700 let text = description.map(inline) ?? Self.escape(label)
701 return "<a href=\"\(Self.escape(href))\">\(text)</a>"
702 }
703
704 private func slugOnly(_ text: String) -> String {
705 var slug = ""
706 var dash = false
707 for c in text.lowercased() {
708 if c.isLetter || c.isNumber {
709 if dash, !slug.isEmpty { slug.append("-") }
710 slug.append(c)
711 dash = false
712 } else {
713 dash = true
714 }
715 }
716 return slug
717 }
718
719 /// `:key value :other "quoted value"`.
720 private func parseAttributes(_ text: String) -> [(String, String)] {
721 var pairs: [(String, String)] = []
722 let regex = try! NSRegularExpression(pattern: ":([A-Za-z_-]+)[ \\t]+(\"[^\"]*\"|[^:\\s][^\\s]*)")
723 let ns = text as NSString
724 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
725 var value = ns.substring(with: m.range(at: 2))
726 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
727 pairs.append((ns.substring(with: m.range(at: 1)), value))
728 }
729 return pairs
730 }
731
732 private func timestamp(_ text: String) -> String {
733 guard let stamp = Timestamp.parse(text) else { return Self.escape(text) }
734 func date(_ p: Timestamp.Point) -> String { String(format: "%04d-%02d-%02d", p.year, p.month, p.day) }
735 func time(_ p: Timestamp.Point) -> String? {
736 guard let h = p.hour, let m = p.minute else { return nil }
737 return String(format: "%02d:%02d", h, m)
738 }
739 func element(_ p: Timestamp.Point, full: Bool) -> String {
740 let datetime = date(p) + (time(p).map { "T" + $0 } ?? "")
741 let shown = full ? date(p) + (time(p).map { " " + $0 } ?? "") : (time(p) ?? date(p))
742 return "<time class=\"timestamp\" datetime=\"\(datetime)\">\(shown)</time>"
743 }
744 guard let end = stamp.end else { return element(stamp.start, full: true) }
745 let sameDay = end.year == stamp.start.year && end.month == stamp.start.month && end.day == stamp.start.day
746 return element(stamp.start, full: true) + "–" + element(end, full: !sameDay)
747 }
748
749 private func footnote(_ text: String) -> String {
750 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return Self.escape(text) }
751 var label = String(m.1)
752 let inlineText = m.2.map(String.init)
753 if label.isEmpty {
754 anonymous += 1
755 label = "anonymous-\(anonymous)"
756 }
757 let number: Int
758 if let existing = footnoteNumbers[label] {
759 number = existing
760 } else {
761 let content: FootnoteContent
762 if let inlineText {
763 content = .inline(inlineText)
764 } else if let definition = definitions[label] {
765 content = .definition(definition)
766 } else {
767 return Self.escape(text)
768 }
769 footnoteOrder.append((label, content))
770 number = footnoteOrder.count
771 footnoteNumbers[label] = number
772 }
773 return "<sup class=\"footnote-ref\"><a id=\"fnr-\(number)\" href=\"#fn-\(number)\">\(number)</a></sup>"
774 }
775}