Sources/OrgCore/Export/HTMLExport.swift
1010 lines · 49278 bytes
1import Foundation
2
3/// Document metadata from `#+TITLE`, `#+AUTHOR`, `#+DATE` and `#+LANGUAGE`.
4public struct ExportMetadata: Sendable, Equatable {
5 public var title: String?
6 public var author: String?
7 public var date: String?
8 public var language: String?
9}
10
11/// HTML export. The body follows the shape orgo produces, which the org-conformance corpus
12/// holds as the reference: headings one level down (`*` is `<h2>`), timestamps as `<time>`,
13/// footnotes collected at the end, captioned images as figures.
14public enum HTMLExport {
15 public static func body(_ text: String, settings: OrgSettings = .default) -> String {
16 let renderer = HTMLRenderer(settings: settings, options: .orgo)
17 return renderer.document(text)
18 }
19
20 public static func metadata(_ text: String, settings: OrgSettings = .default) -> ExportMetadata {
21 let tree = OrgParser.parse(text, defaults: settings)
22 var meta = ExportMetadata()
23 // Setup files' keywords come first, as Org reads them where `#+SETUPFILE` is.
24 let setup = settings.setupKeywords.split(separator: "\n").map(String.init)
25 let own = tree.root.children.filter { $0.kind == .zerothSection }.flatMap { $0.children.filter { $0.kind == .keyword } }.map(\.text)
26 for text in setup + own {
27 let line = text.trimmingCharacters(in: .whitespacesAndNewlines)
28 guard let colon = line.firstIndex(of: ":") else { continue }
29 let key = line.dropFirst(2).prefix { $0 != ":" }.uppercased()
30 let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
31 switch key {
32 case "TITLE": meta.title = value
33 case "AUTHOR": meta.author = value
34 case "DATE": meta.date = value
35 case "LANGUAGE": meta.language = value.isEmpty ? nil : value
36 default: break
37 }
38 }
39 return meta
40 }
41
42 /// The tag that loads MathJax on a page with math.
43 public static let mathJaxScript = #"<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>"#
44
45 /// A standalone page: the body under the document's title, with a small stylesheet, as
46 /// `#+OPTIONS` and the export keywords ask. `path` is the file's, for `#+INCLUDE` and
47 /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and
48 /// byline: the table of contents, the document and its footnotes, as Org's body-only export.
49 /// `language` is `org-export-default-language`, for files without `#+LANGUAGE`.
50 public static func page(
51 _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
52 codeStyle: HTMLCodeStyle? = nil, language: String = "en"
53 ) -> String {
54 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
55 let expanded = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
56 let text = ExportPreprocess.attachments(expanded, path: path, settings: settings)
57 let options = ExportOptions.parse(settings.setupKeywords + text)
58 let meta = metadata(text, settings: settings)
59 let title = meta.title ?? fallbackTitle
60 let renderer = HTMLRenderer(settings: settings, options: options)
61 renderer.codeStyle = codeStyle
62 renderer.language = meta.language ?? language
63 // The title isn't part of the document Org processes citations in: they drop out.
64 renderer.inTitle = true
65 let titleHTML = renderer.inlineString(title)
66 renderer.inTitle = false
67 renderer.citations = CiteProcessor(text: text, directory: directory, global: settings.citeGlobalBibliography)
68 var header = options.title ? "<h1 class=\"title\">\(titleHTML)</h1>\n" : ""
69 let byline = [options.author ? meta.author : nil, options.date ? meta.date : nil].compactMap { $0 }.filter { !$0.isEmpty }
70 if !byline.isEmpty { header += "<p class=\"byline\">\(byline.map(HTMLRenderer.escape).joined(separator: " · "))</p>\n" }
71 let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
72 let contents = renderer.tableOfContents()
73 if bodyOnly { return contents + body }
74 header += contents
75 var head = options.htmlHead.map { $0 + "\n" }.joined()
76 if renderer.hasMath {
77 head += """
78 <script>window.MathJax = { tex: { inlineMath: [['\\\\(', '\\\\)']], displayMath: [['\\\\[', '\\\\]'], ['$$', '$$']] } };</script>
79 \(mathJaxScript)
80
81 """
82 }
83 return """
84 <!DOCTYPE html>
85 <html lang="\(HTMLRenderer.escape(renderer.language))">
86 <head>
87 <meta charset="utf-8">
88 <meta name="viewport" content="width=device-width, initial-scale=1">
89 <title>\(HTMLRenderer.escape(title))</title>
90 <style>
91 body { font: 16px/1.55 -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif; max-width: 46em; margin: 2em auto; padding: 0 1em; color: #222; }
92 @media (prefers-color-scheme: dark) { body { background: #1d1d1f; color: #ddd; } a { color: #6cb6ff; } }
93 pre { background: rgba(127, 127, 127, 0.12); padding: 0.75em; overflow-x: auto; }
94 code { font: 0.9em ui-monospace, Menlo, monospace; }
95 table { border-collapse: collapse; } th, td { border: 1px solid rgba(127, 127, 127, 0.4); padding: 0.25em 0.6em; }
96 blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid rgba(127, 127, 127, 0.4); }
97 .tag { font-size: 0.75em; padding: 0 0.3em; border-radius: 3px; background: rgba(127, 127, 127, 0.18); }
98 .todo { color: #c33; } .done { color: #393; } .byline { color: #888; } .center { text-align: center; }
99 figure { margin: 1em 0; } img { max-width: 100%; }
100 #table-of-contents ul { list-style: none; padding-left: 1.2em; } #table-of-contents > div > ul { padding-left: 0; }
101 \(codeStyle?.css ?? "")</style>
102 \(head)</head>
103 <body>
104 \(header)\(body)</body>
105 </html>
106
107 """
108 }
109}
110
111/// The tree being exported, for what its src blocks, calls and inline blocks export.
112final class ExportSource {
113 let tree: OrgTree
114 let text: NSString
115 private lazy var model = DocumentModel(tree: tree)
116 /// Whether the last inline src block or call lets the `{{{results(…)}}}` after it show;
117 /// nil when nothing asks.
118 var inlineResults: Bool?
119 /// Whether the languages' own `:exports` defaults apply.
120 let languages: Bool
121
122 init(tree: OrgTree, text: String, languages: Bool = true) {
123 self.tree = tree
124 self.text = text as NSString
125 self.languages = languages
126 }
127
128 func exports(at offset: Int) -> String? {
129 Babel.exports(at: offset, tree: tree, model: model, text: text, languages: languages)
130 }
131
132 /// `{{{results(…)}}}`, Org's `$1` macro, as the inline block or call before it allows:
133 /// nil for other macros, the text to show (or nil) for this one.
134 func resultsMacro(_ node: SyntaxNode) -> String?? {
135 guard let m = node.text.firstMatch(of: /(?i)^\{\{\{results\((.*)\)\}\}\}$/) else { return .none }
136 defer { inlineResults = nil }
137 return inlineResults ?? true ? ExportPreprocess.arguments(String(m.1)).first : .some(nil)
138 }
139}
140
141final class HTMLRenderer {
142 let settings: OrgSettings
143 let options: ExportOptions
144 /// With select tags in the document: the sections to export, by heading start.
145 private var selected: Set<Int>?
146 private var numbers: [Int] = []
147 private var tocEntries: [(level: Int, id: String, html: String)] = []
148 /// `#+LANGUAGE`, for the words the exporter writes (`org-export-translate`).
149 var language = "en"
150 /// A LaTeX fragment was exported, for MathJax.
151 private(set) var hasMath = false
152 private var footnoteNumbers: [String: Int] = [:]
153 private var footnoteOrder: [(label: String, content: FootnoteContent)] = []
154 private var definitions: [String: String] = [:]
155 private var anonymous = 0
156 private var figures = 0
157 private var ids: Set<String> = []
158 /// Citations and the bibliography, as `oc-basic` exports them.
159 var citations: CiteProcessor?
160 /// Rendering the title, where Org exports citations as nothing.
161 var inTitle = false
162 /// Colors for source blocks; plain without.
163 var codeStyle: HTMLCodeStyle?
164 /// A reveal.js deck being exported: headings become slides, `#+ATTR_REVEAL` fragments.
165 var reveal: RevealSlides?
166
167 enum FootnoteContent {
168 case definition(String)
169 case inline(String)
170 }
171
172 init(settings: OrgSettings, options: ExportOptions = .orgo) {
173 self.settings = settings
174 self.options = options
175 }
176
177 static func escape(_ s: String) -> String {
178 var out = ""
179 for c in s {
180 switch c {
181 case "&": out += "&"
182 case "<": out += "<"
183 case ">": out += ">"
184 case "\"": out += """
185 default: out.append(c)
186 }
187 }
188 return out
189 }
190
191 // MARK: - Document
192
193 /// The document's tree, for code references, and each src and example block's
194 /// `org-export-get-loc`, by the block's text, in order.
195 private var documentTree: OrgTree?
196 private var blockLocs: [String: [Int?]] = [:]
197
198 func document(_ text: String) -> String {
199 let tree = OrgParser.parse(text, defaults: settings)
200 documentTree = tree
201 let codeBlocks = Coderef.blocks(tree)
202 for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
203 blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
204 }
205 collectDefinitions(tree.root)
206 selected = Self.selection(tree, tags: options.selectTags)
207 var out = ""
208 rendering(tree, text) {
209 for child in tree.root.children { out += element(child) }
210 }
211 if let reveal { return out + reveal.close() }
212 out += footnoteSection()
213 return out
214 }
215
216 private var source: ExportSource?
217
218 /// `body` with `tree` as the source of `:exports`.
219 private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
220 let saved = source
221 source = ExportSource(tree: tree, text: text)
222 defer { source = saved }
223 return body()
224 }
225
226 private func collectDefinitions(_ node: SyntaxNode) {
227 for child in node.children {
228 if child.kind == .footnoteDefinition {
229 let text = child.text
230 if let m = text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
231 definitions[String(m.1)] = String(text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
232 }
233 } else {
234 collectDefinitions(child)
235 }
236 }
237 }
238
239 func footnoteSection() -> String {
240 guard !footnoteOrder.isEmpty else { return "" }
241 var out = "<section class=\"footnotes\" aria-label=\"\(ExportDictionary.translate("Footnotes", language: language, encoding: .html))\">\n<hr>\n<ol>\n"
242 for (index, note) in footnoteOrder.enumerated() {
243 let n = index + 1
244 let content: String
245 switch note.content {
246 case .definition(let text): content = blocks(text).trimmingCharacters(in: .newlines)
247 case .inline(let text): content = inlineString(text)
248 }
249 out += "<li id=\"fn-\(n)\">\(content)\n <a class=\"footnote-back\" href=\"#fnr-\(n)\" aria-label=\"Back to reference \(n)\">↩</a></li>\n"
250 }
251 return out + "</ol>\n</section>\n"
252 }
253
254 /// How deep in `blocks` rendering is: the document's own text at 0.
255 private var nested = 0
256
257 /// Org text rendered as elements, for block and footnote contents.
258 func blocks(_ text: String) -> String {
259 nested += 1
260 defer { nested -= 1 }
261 let tree = OrgParser.parse(text, defaults: settings)
262 var out = ""
263 rendering(tree, text) {
264 for child in tree.root.children { out += element(child) }
265 }
266 return out
267 }
268
269 /// One line of org text rendered inline.
270 func inlineString(_ text: String) -> String {
271 let tree = OrgParser.parse(text, defaults: settings)
272 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
273 return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
274 }
275
276 /// A citation's or a bibliography entry's pieces: text escaped, prefixes and suffixes as
277 /// Org markup with their blanks kept.
278 private func render(_ pieces: [CiteProcessor.Piece]) -> String {
279 pieces.map { piece in
280 switch piece {
281 case .text(let s): Self.escape(s)
282 case .italic(let s): "<i>" + Self.escape(s) + "</i>"
283 case .org(let s) where s.allSatisfy(\.isWhitespace): s
284 case .org(let s):
285 String(s.prefix { $0.isWhitespace }) + inlineString(s) + (s.allSatisfy(\.isWhitespace) ? "" : String(s.reversed().prefix { $0.isWhitespace }))
286 }
287 }.joined()
288 }
289
290 // MARK: - Elements
291
292 private var affiliated: [String: String] = [:]
293 /// `:exports` of the last src block or call: its results are exported only for `results`
294 /// and `both`; nothing runs.
295 private var lastExports = "code"
296
297 func element(_ node: SyntaxNode) -> String {
298 defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
299 if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
300 defer { lastExports = "code" }
301 if lastExports != "results", lastExports != "both" { return "" }
302 }
303 if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
304 lastExports = exports
305 if exports == "results" || exports == "none" { return "" }
306 }
307 switch node.kind {
308 case .section:
309 guard let heading = node.firstChild(.heading) else { fallthrough }
310 let export = Self.sectionExport(heading, options: options, selected: selected)
311 if export != .nothing, let slide = reveal?.section(node, heading: heading, all: export == .all, renderer: self) { return slide }
312 switch export {
313 case .nothing: return ""
314 case .heading: return self.heading(heading)
315 case .all: break
316 }
317 var out = ""
318 for child in node.children { out += element(child) }
319 return out
320 case .zerothSection, .document:
321 var out = ""
322 for child in node.children { out += element(child) }
323 if node.kind == .zerothSection, let reveal, nested == 0 { return reveal.preamble(out) }
324 return out
325 case .heading:
326 return heading(node)
327 case .affiliatedKeyword:
328 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
329 if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
330 affiliated[m.1.uppercased()] = String(m.2)
331 }
332 return ""
333 case .paragraph:
334 return fragment(paragraph(node))
335 case .keyword where citations != nil && node.text.range(of: "^[ \\t]*#\\+print_bibliography:", options: [.regularExpression, .caseInsensitive]) != nil:
336 return citations!.bibliography.map { "<p>" + render($0) + "</p>\n" }.joined()
337 case .plainList:
338 return fragment(list(node), list: true)
339 case .table:
340 return fragment(table(node))
341 case .block:
342 return fragment(block(node))
343 case .keyword where reveal != nil:
344 return reveal!.keyword(node.text)
345 case .horizontalRule:
346 return "<hr>\n"
347 case .inlineTask:
348 // As ox-html: the title in bold, then the contents.
349 var out = "<div class=\"inlinetask\">\n"
350 for child in node.children {
351 if child.kind == .heading {
352 guard child.range.lowerBound == node.range.lowerBound else { continue }
353 let title = child.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
354 let todo = options.todo ? child.tokens.first { $0.kind == .todoKeyword }.map { "<span class=\"todo \(Self.escape($0.text))\">\(Self.escape($0.text))</span> " } ?? "" : ""
355 out += "<b>\(todo)\(title)</b><br>\n"
356 } else {
357 out += element(child)
358 }
359 }
360 return out + "</div>\n"
361 case .latexEnvironment:
362 // For MathJax, as ox-html leaves it with `tex:t`.
363 guard options.tex else { return "" }
364 hasMath = true
365 return Self.escape(node.text.trimmingCharacters(in: .newlines)) + "\n"
366 case .fixedWidth:
367 let lines = node.text.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
368 let trimmed = line.drop { $0 == " " || $0 == "\t" }
369 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
370 }
371 return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
372 case .tableEl:
373 let lines = node.text.components(separatedBy: "\n").filter { !$0.lowercased().contains("#+tblfm") }
374 // As `org-html-table--table.el-table`: cells with their spans, lines kept apart.
375 if let cells = TableEl.cells(lines.joined(separator: "\n")) {
376 var out = "<table class=\"table-el\">\n"
377 for row in Dictionary(grouping: cells, by: \.row).keys.sorted() {
378 out += "<tr>"
379 for cell in cells where cell.row == row {
380 let spans = (cell.colspan > 1 ? " colspan=\"\(cell.colspan)\"" : "") + (cell.rowspan > 1 ? " rowspan=\"\(cell.rowspan)\"" : "")
381 let content = cell.lines.reversed().drop { $0.isEmpty }.reversed().map(Self.escape).joined(separator: "<br>")
382 out += "<td\(spans)>\(content)</td>"
383 }
384 out += "</tr>\n"
385 }
386 return out + "</table>\n"
387 }
388 return "<pre class=\"example\">" + Self.escape(lines.joined(separator: "\n").trimmingCharacters(in: .newlines)) + "</pre>\n"
389 case .dynamicBlock:
390 let lines = node.text.components(separatedBy: "\n")
391 return blocks(lines.dropFirst().dropLast(2).joined(separator: "\n"))
392 default:
393 // Keywords, comments, drawers, planning, clocks, footnote definitions, formulas.
394 return ""
395 }
396 }
397
398 private func slug(_ text: String) -> String {
399 var slug = ""
400 var dash = false
401 for c in text.lowercased() {
402 if c.isLetter || c.isNumber {
403 if dash, !slug.isEmpty { slug.append("-") }
404 slug.append(c)
405 dash = false
406 } else {
407 dash = true
408 }
409 }
410 if slug.isEmpty { slug = "section" }
411 var candidate = slug
412 var n = 1
413 while ids.contains(candidate) {
414 candidate = "\(slug)-\(n)"
415 n += 1
416 }
417 ids.insert(candidate)
418 return candidate
419 }
420
421 /// `org-export--selected-trees`: headings with a select tag, everything below them and
422 /// their ancestors; nil when no heading has one.
423 enum SectionExport {
424 case all, heading, nothing
425 }
426
427 /// `org-export--skip-p` for the section under `heading`: excluded tags, COMMENT and
428 /// unselected trees export nothing, archived trees their heading only.
429 static func sectionExport(_ heading: SyntaxNode, options: ExportOptions, selected: Set<Int>?) -> SectionExport {
430 let tags = heading.tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? []
431 let title = heading.firstChild(.title)?.text.trimmingCharacters(in: .whitespaces) ?? ""
432 if tags.contains(where: options.excludeTags.contains) || title == "COMMENT" || title.hasPrefix("COMMENT ") { return .nothing }
433 if let selected, !selected.contains(heading.range.lowerBound) { return .nothing }
434 return tags.contains("ARCHIVE") ? .heading : .all
435 }
436
437 static func selection(_ tree: OrgTree, tags: [String]) -> Set<Int>? {
438 let model = DocumentModel(tree: tree)
439 let picked = model.headings.indices.filter { model.headings[$0].localTags.contains(where: tags.contains) }
440 guard !picked.isEmpty else { return nil }
441 var set: Set<Int> = []
442 for index in picked {
443 set.insert(model.headings[index].headingRange.lowerBound)
444 for a in model.ancestors(of: index) { set.insert(model.headings[a].headingRange.lowerBound) }
445 let level = model.headings[index].level
446 for d in model.headings[(index + 1)...].prefix(while: { $0.level > level }) { set.insert(d.headingRange.lowerBound) }
447 }
448 return set
449 }
450
451 /// The table of contents, as ox-html writes it, or nothing.
452 func tableOfContents() -> String {
453 guard options.toc != nil, !tocEntries.isEmpty else { return "" }
454 var out = "<div id=\"table-of-contents\" role=\"doc-toc\">\n<h2>\(ExportDictionary.translate("Table of Contents", language: language, encoding: .html))</h2>\n<div id=\"text-table-of-contents\" role=\"doc-toc\">\n"
455 var depth = 0
456 var open: [Bool] = []
457 let base = tocEntries.map(\.level).min() ?? 1
458 for entry in tocEntries {
459 let level = entry.level - base + 1
460 if level > depth {
461 while depth < level {
462 out += "\n<ul>\n"
463 depth += 1
464 open.append(false)
465 }
466 } else {
467 out += "</li>\n"
468 while depth > level {
469 out += "</ul>\n</li>\n"
470 depth -= 1
471 open.removeLast()
472 }
473 }
474 out += "<li><a href=\"#\(Self.escape(entry.id))\">\(entry.html)</a>"
475 }
476 out += "</li>\n"
477 while depth > 1 {
478 out += "</ul>\n</li>\n"
479 depth -= 1
480 }
481 return out + "</ul>\n</div>\n</div>\n"
482 }
483
484 /// `html` as a reveal.js fragment when `#+ATTR_REVEAL` asks.
485 private func fragment(_ html: String, list: Bool = false) -> String {
486 guard let reveal, let attributes = affiliated["ATTR_REVEAL"] else { return html }
487 return reveal.fragment(html, attributes: attributes, list: list)
488 }
489
490 func heading(_ node: SyntaxNode) -> String {
491 let tokens = node.tokens
492 let level = tokens.first { $0.kind == .stars }?.text.count ?? 1
493 let title = node.firstChild(.title)
494 let titleText = title?.text.trimmingCharacters(in: .whitespaces) ?? ""
495 // `CUSTOM_ID` from the property drawer that follows.
496 var customID: String?
497 if let section = node.parent, let drawer = section.firstChild(.propertyDrawer) {
498 for property in drawer.children where property.kind == .nodeProperty {
499 if let m = property.text.firstMatch(of: /^[ \t]*:CUSTOM_ID:[ \t]*(\S+)/) { customID = String(m.1) }
500 }
501 }
502 let id = customID ?? slug(titleText)
503 if customID != nil { ids.insert(id) }
504 var parts: [String] = []
505 let h = min(level + 1, 6)
506 if let num = options.num, level <= num {
507 if numbers.count < level { numbers += Array(repeating: 0, count: level - numbers.count) }
508 numbers = Array(numbers.prefix(level))
509 numbers[level - 1] += 1
510 parts.append("<span class=\"section-number-\(h)\">\(numbers.map(String.init).joined(separator: ".")).</span>")
511 }
512 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
513 parts.append("<span class=\"todo \(settings.isDone(todo) ? "done " : "")\(Self.escape(todo))\">\(Self.escape(todo))</span>")
514 }
515 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text {
516 parts.append("<span class=\"priority\">\(Self.escape(priority))</span>")
517 }
518 if let title, !titleText.isEmpty { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
519 var tagParts: [String] = []
520 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
521 tagParts = tags.split(separator: ":").map { "<span class=\"tag\">\(Self.escape(String($0)))</span>" }
522 }
523 if let toc = options.toc, level <= toc {
524 tocEntries.append((level, id, (parts + (options.tagsInTOC ? tagParts : [])).joined(separator: " ")))
525 }
526 parts += tagParts
527 return "<h\(h) id=\"\(Self.escape(id))\">\(parts.joined(separator: " "))</h\(h)>\n"
528 }
529
530 private func paragraph(_ node: SyntaxNode) -> String {
531 let body = inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
532 if let image = soleImage(node), affiliated["CAPTION"] != nil || affiliated["ATTR_HTML"] != nil {
533 var out = "<figure>\n" + image + "\n"
534 if let caption = affiliated["CAPTION"] {
535 figures += 1
536 let label = ExportDictionary.translate("Figure %d:", language: language, encoding: .html).replacingOccurrences(of: "%d", with: String(figures))
537 out += "<figcaption>\(label) \(inlineString(caption))</figcaption>\n"
538 }
539 return out + "</figure>\n"
540 }
541 return "<p>\(body)</p>\n"
542 }
543
544 /// The `<img>` of a paragraph that is only an image link.
545 private func soleImage(_ node: SyntaxNode) -> String? {
546 let links = node.children.filter { $0.kind == .link }
547 guard links.count == 1, node.children.count == 1,
548 node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else { return nil }
549 let html = link(links[0])
550 return html.hasPrefix("<img") ? html : nil
551 }
552
553 // MARK: - Lists
554
555 private func isOrdered(_ item: SyntaxNode) -> Bool {
556 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
557 return bullet.first.map { $0.isNumber || $0.isLetter } ?? false
558 }
559
560 /// As orgo does, a change between ordered and unordered bullets starts another list.
561 private func list(_ node: SyntaxNode) -> String {
562 var runs: [[SyntaxNode]] = []
563 for item in node.children where item.kind == .item {
564 if let last = runs.last?.last, isOrdered(last) == isOrdered(item) {
565 runs[runs.count - 1].append(item)
566 } else {
567 runs.append([item])
568 }
569 }
570 return runs.map(list).joined()
571 }
572
573 private func list(_ items: [SyntaxNode]) -> String {
574 guard let first = items.first else { return "" }
575 let ordered = isOrdered(first)
576 // `org-list-get-list-type`: descriptive when the first item has a tag.
577 let description = !ordered && first.firstChild(.itemTag) != nil
578 if description {
579 var out = "<dl>\n"
580 for item in items {
581 let (term, rest) = descriptionParts(item)
582 out += "<dt>\(term)</dt>\n<dd>\(rest)</dd>\n"
583 }
584 return out + "</dl>\n"
585 }
586 let tag = ordered ? "ol" : "ul"
587 var out = "<\(tag)>\n"
588 for item in items { out += listItem(item) }
589 return out + "</\(tag)>\n"
590 }
591
592 /// A description item's term, `(no term)` without one, and the rest of the item.
593 private func descriptionParts(_ item: SyntaxNode) -> (String, String) {
594 var term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
595 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
596 term = "<code>\(box == "[ ]" ? "[ ]" : box.uppercased())</code> " + term
597 }
598 var rest = ""
599 for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
600 rest += index == 0 && child.kind == .paragraph ? inline(child).trimmingCharacters(in: .whitespacesAndNewlines) : element(child)
601 }
602 return (term, rest.trimmingCharacters(in: .whitespacesAndNewlines))
603 }
604
605 private func listItem(_ item: SyntaxNode) -> String {
606 // ox-html gives an ordered item's counter as its value.
607 var open = "<li>"
608 if isOrdered(item), let counter = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+|[A-Za-z])\]/) {
609 open = "<li value=\"\(counter.1)\">"
610 }
611 var prefix = ""
612 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
613 switch box {
614 case "[X]", "[x]":
615 open = "<li class=\"on\">"
616 prefix = "<code>[X]</code> "
617 case "[-]":
618 open = "<li class=\"trans\">"
619 prefix = "<code>[-]</code> "
620 default:
621 open = "<li class=\"off\">"
622 prefix = "<code>[ ]</code> "
623 }
624 }
625 let paragraphs = item.children.filter { $0.kind == .paragraph }.count
626 var body = ""
627 for child in item.children {
628 if child.kind == .paragraph {
629 let content = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
630 body += paragraphs >= 2 ? "<p>\(content)</p>\n" : content
631 } else {
632 body += element(child)
633 }
634 }
635 if paragraphs >= 2 {
636 body = prefix + body
637 } else {
638 body = prefix + body
639 }
640 return open + body + (body.hasSuffix("\n") ? "" : "") + "</li>\n"
641 }
642
643 // MARK: - Tables
644
645 private func table(_ node: SyntaxNode) -> String {
646 let rows = node.children.filter { $0.kind == .tableRow }
647 var groups: [[SyntaxNode]] = [[]]
648 for row in rows {
649 if row.children.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
650 if !groups[groups.count - 1].isEmpty { groups.append([]) }
651 } else {
652 groups[groups.count - 1].append(row)
653 }
654 }
655 groups.removeAll { $0.isEmpty }
656 var out = "<table>\n"
657 if let caption = affiliated["CAPTION"] { out += "<caption>\(inlineString(caption))</caption>\n" }
658 let hasHeader = groups.count > 1
659 for (index, group) in groups.enumerated() {
660 let header = hasHeader && index == 0
661 if header { out += "<thead>\n" } else if index == (hasHeader ? 1 : 0) { out += "<tbody>\n" }
662 for row in group {
663 out += "<tr>" + row.children.filter { $0.kind == .tableCell }.map { cell in
664 let content = inline(cell).trimmingCharacters(in: .whitespaces)
665 return header ? "<th>\(content)</th>" : "<td>\(content)</td>"
666 }.joined() + "</tr>\n"
667 }
668 if header { out += "</thead>\n" }
669 }
670 if !groups.isEmpty, !(hasHeader && groups.count == 1) { out += "</tbody>\n" }
671 return out + "</table>\n"
672 }
673
674 // MARK: - Blocks
675
676 private func block(_ node: SyntaxNode) -> String {
677 var lines = node.text.components(separatedBy: "\n")
678 if lines.last == "" { lines.removeLast() }
679 guard let first = lines.first,
680 let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
681 let type = m.1.lowercased()
682 let parameters = String(m.2)
683 let body = Array(lines.dropFirst().dropLast())
684 // Commas protect `*` and `#+` lines inside blocks.
685 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
686 let text = unescaped.joined(separator: "\n")
687 switch type {
688 case "src":
689 let language = parameters.split(separator: " ").first.map(String.init)
690 let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
691 let source = lines.joined(separator: "\n")
692 let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source)
693 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
694 return "<pre><code\(cls)>\(numbered(code, loc: loc, refs: refs, retain: switches.retainLabels))</code></pre>\n"
695 case "example":
696 let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
697 return "<pre>\(numbered(Self.escape(lines.joined(separator: "\n")), loc: loc, refs: refs, retain: switches.retainLabels))</pre>\n"
698 case "quote":
699 return "<blockquote>\n\(blocks(text))</blockquote>\n"
700 case "center":
701 return "<div class=\"center\">\n\(blocks(text))</div>\n"
702 case "verse":
703 let rendered = unescaped.map { line -> String in
704 let indent = line.prefix { $0 == " " }.count
705 return String(repeating: " ", count: indent) + inlineString(String(line.dropFirst(indent)))
706 }
707 return "<p class=\"verse\">\n" + rendered.joined(separator: "<br>\n") + "\n</p>\n"
708 case "export":
709 let backend = parameters.lowercased()
710 return backend.hasPrefix("html") || (reveal != nil && backend.split(separator: " ").first == "reveal") ? text + "\n" : ""
711 case "comment":
712 return ""
713 case "notes" where reveal != nil:
714 return "<aside class=\"notes\">\n\(blocks(text))</aside>\n"
715 default:
716 return "<div class=\"\(Self.escape(type))\">\n\(blocks(text))</div>\n"
717 }
718 }
719
720 /// A src or example block's code without its labels (`org-export-unravel-code`), the lines
721 /// numbered before it, its switches, and its labels by line.
722 private func code(_ block: [String], _ body: [String]) -> (lines: [String], loc: Int?, switches: Coderef.Switches, refs: [Int: String]) {
723 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
724 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
725 let key = block.joined(separator: "\n")
726 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
727 return (lines, switches.numberLines == nil ? nil : loc, switches, refs)
728 }
729
730 /// `org-html-do-format-code`: lines numbered from `loc`, and lines with a label marked as
731 /// its `coderef-` anchor, the label kept after them with `retain`.
732 private func numbered(_ html: String, loc: Int?, refs: [Int: String], retain: Bool) -> String {
733 guard loc != nil || !refs.isEmpty else { return html }
734 let lines = Self.splitLines(html)
735 let width = loc.map { String($0 + lines.count).count } ?? 0
736 return lines.enumerated().map { index, line in
737 var out = loc.map { "<span class=\"linenr\">" + String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1): </span>" } ?? ""
738 out += line
739 guard let ref = refs[index + 1] else { return out }
740 if retain { out += " (\(Self.escape(ref)))" }
741 return "<span id=\"coderef-\(Self.escape(ref))\" class=\"coderef-off\">\(out)</span>"
742 }.joined(separator: "\n")
743 }
744
745 /// Highlighted code split into lines, spans open at a line's end closed there and opened
746 /// again on the next.
747 static func splitLines(_ html: String) -> [String] {
748 var open: [String] = []
749 return html.components(separatedBy: "\n").map { line in
750 var out = open.joined() + line
751 for m in line.matches(of: /<span[^>]*>|<\/span>/) {
752 if m.output.hasPrefix("</") { if !open.isEmpty { open.removeLast() } } else { open.append(String(m.output)) }
753 }
754 out += String(repeating: "</span>", count: open.count)
755 return out
756 }
757 }
758
759 private func dedent(_ lines: [String]) -> [String] {
760 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
761 let common = indents.min() ?? 0
762 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
763 }
764
765 // MARK: - Inline
766
767 func inline(_ node: SyntaxNode) -> String {
768 var out = ""
769 for element in node.elements {
770 switch element {
771 case .token(let token):
772 switch token.kind {
773 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority:
774 continue
775 default:
776 out += entities(token.text)
777 }
778 case .node(let child):
779 out += object(child)
780 }
781 }
782 return out
783 }
784
785 /// Text: LaTeX fragments left for MathJax, `\alpha` and friends as characters, `_` and `^`
786 /// scripts as `<sub>` and `<sup>`, as `#+OPTIONS` says.
787 static let textObjects = try! NSRegularExpression(pattern: [
788 #"\\\((.+?)\\\)"#, #"\\\[(.+?)\\\]"#, #"\$\$(.+?)\$\$"#,
789 #"(?<![$\w])\$([^\s$.,;](?:[^$]*?[^\s$.,\\])?)\$(?=[\s.,;:!?'")\]-]|$)"#,
790 #"\\([a-zA-Z]+)(\{\})?"#,
791 #"(?<=\S)([_^])(\{[^{}]*\}|[+-]?[\p{L}\p{N}.,\\]*[\p{L}\p{N}])"#,
792 ].joined(separator: "|"))
793
794 private func entities(_ text: String) -> String {
795 guard text.contains(where: { $0 == "\\" || $0 == "$" || $0 == "_" || $0 == "^" }) else { return Self.escape(text) }
796 let ns = text as NSString
797 var out = ""
798 var at = 0
799 for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
800 out += Self.escape(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
801 at = NSMaxRange(m.range)
802 let whole = ns.substring(with: m.range)
803 func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
804 if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
805 guard options.tex else { continue }
806 hasMath = true
807 out += Self.escape(whole)
808 } else if let name = group(5) {
809 out += Self.escape(OrgEntities.display[name] ?? whole)
810 } else if let marker = group(7), let body = group(8) {
811 let braced = body.hasPrefix("{")
812 if options.scripts == .off || (options.scripts == .braces && !braced) {
813 out += Self.escape(whole)
814 continue
815 }
816 let inner = braced ? String(body.dropFirst().dropLast()) : body
817 out += marker == "_" ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
818 } else {
819 out += Self.escape(whole)
820 }
821 }
822 return out + Self.escape(ns.substring(from: at))
823 }
824
825 private func object(_ node: SyntaxNode) -> String {
826 switch node.kind {
827 case .bold: return "<strong>\(inline(node))</strong>"
828 case .italic: return "<em>\(inline(node))</em>"
829 case .underline: return "<u>\(inline(node))</u>"
830 case .strikeThrough: return "<del>\(inline(node))</del>"
831 case .verbatim: return "<code class=\"verbatim\">\(inline(node))</code>"
832 case .code: return "<code>\(inline(node))</code>"
833 case .link: return link(node)
834 case .linkDescription: return inline(node)
835 case .timestamp: return timestamp(node.text)
836 case .footnoteReference: return footnote(node.text)
837 case .entity:
838 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
839 return Self.escape(OrgEntities.display[name] ?? node.text)
840 case .radioTarget:
841 let inner = String(node.text.dropFirst(3).dropLast(3))
842 return "<a id=\"\(Self.escape(slugOnly(inner)))\">\(Self.escape(inner))</a>"
843 case .superscript, .subscript:
844 let text = node.text
845 let body = text.dropFirst()
846 let braced = body.hasPrefix("{") && body.hasSuffix("}")
847 if options.scripts == .off || (options.scripts == .braces && !braced) { return Self.escape(text) }
848 let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
849 return text.hasPrefix("_") ? "<sub>\(Self.escape(inner))</sub>" : "<sup>\(Self.escape(inner))</sup>"
850 case .lineBreak: return "<br>\n"
851 case .macro:
852 guard case .some(let value) = source?.resultsMacro(node) else { return "" }
853 return value.map(inlineString) ?? ""
854 case .target: return ""
855 case .inlineSourceBlock:
856 let exports = source?.exports(at: node.range.lowerBound) ?? "results"
857 source?.inlineResults = exports == "results" || exports == "both"
858 guard exports == "code" || exports == "both" else { return "" }
859 if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "<code>\(Self.escape(String(m.1)))</code>" }
860 return Self.escape(node.text)
861 case .latexFragment:
862 // For MathJax, as ox-html leaves them with `tex:t`; `tex:nil` drops them.
863 guard options.tex else { return "" }
864 hasMath = true
865 return Self.escape(node.text)
866 case .statisticsCookie: return Self.escape(node.text)
867 // `org-html-export-snippet`: only HTML snippets.
868 case .exportSnippet:
869 guard node.tokens.first?.text == "@@html:" || (reveal != nil && node.tokens.first?.text == "@@reveal:") else { return "" }
870 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
871 case .citation:
872 if inTitle { return "" }
873 guard let pieces = citations?.next(node.text) else { return Self.escape(node.text) }
874 return render(pieces)
875 case .inlineBabelCall:
876 source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
877 return ""
878 default: return inline(node)
879 }
880 }
881
882 static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "bmp", "tif", "tiff", "avif"]
883
884 private func link(_ node: SyntaxNode) -> String {
885 let path = node.linkPath
886 let description = node.firstChild(.linkDescription)
887 guard let path else {
888 // A radio link goes to its target.
889 if !node.text.hasPrefix("<"), !node.text.contains(":") {
890 return "<a href=\"#\(Self.escape(slugOnly(node.text)))\">\(Self.escape(node.text))</a>"
891 }
892 // A plain or angle link.
893 var target = node.text
894 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
895 return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
896 }
897 // A code reference: the label, or its line's number.
898 if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
899 let name = String(path.dropFirst().dropLast())
900 let resolved = documentTree.flatMap { Coderef.resolve(name, in: $0) } ?? name
901 let text = Coderef.linkText(resolved, description: description.map { $0.text })
902 return "<a href=\"#coderef-\(Self.escape(name))\" class=\"coderef\">\(Self.escape(text))</a>"
903 }
904 // A regexp search has nowhere to go in the export.
905 if path.count >= 2, path.hasPrefix("/"), path.hasSuffix("/") {
906 return description.map(inline) ?? Self.escape(path)
907 }
908 var href = path
909 var label = path
910 if path.hasPrefix("file:") {
911 href = String(path.dropFirst(5))
912 label = href
913 } else if path.hasPrefix("id:") {
914 href = "#" + path.dropFirst(3)
915 label = String(path.dropFirst(3))
916 } else if path.hasPrefix("*") {
917 href = "#" + slugOnly(String(path.dropFirst()))
918 } else if !path.hasPrefix("#"), !path.contains(":"), !path.contains("/"), !path.contains(".") {
919 href = "#" + slugOnly(path)
920 }
921 let isFile = path.hasPrefix("file:") || (!path.contains(":") && (path.contains("/") || path.contains(".")))
922 if isFile, href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".html" }
923 if isFile, let range = href.range(of: ".org::") { href = String(href[..<range.lowerBound]) + ".html" }
924 let ext = (href.split(separator: "?").first.map(String.init) ?? href).split(separator: ".").last.map { $0.lowercased() } ?? ""
925 if description == nil, Self.imageExtensions.contains(ext) {
926 var attributes = ""
927 if let attrs = affiliated["ATTR_HTML"] {
928 for (key, value) in parseAttributes(attrs) where key != "src" {
929 attributes += " \(key)=\"\(Self.escape(value))\""
930 }
931 }
932 if !attributes.contains(" alt=") { attributes = " alt=\"\(Self.escape((href as NSString).lastPathComponent))\"" + attributes }
933 return "<img src=\"\(Self.escape(href))\"\(attributes)>"
934 }
935 let text = description.map(inline) ?? Self.escape(label)
936 return "<a href=\"\(Self.escape(href))\">\(text)</a>"
937 }
938
939 private func slugOnly(_ text: String) -> String {
940 var slug = ""
941 var dash = false
942 for c in text.lowercased() {
943 if c.isLetter || c.isNumber {
944 if dash, !slug.isEmpty { slug.append("-") }
945 slug.append(c)
946 dash = false
947 } else {
948 dash = true
949 }
950 }
951 return slug
952 }
953
954 /// `:key value :other "quoted value"`.
955 private func parseAttributes(_ text: String) -> [(String, String)] {
956 var pairs: [(String, String)] = []
957 let regex = try! NSRegularExpression(pattern: ":([A-Za-z_-]+)[ \\t]+(\"[^\"]*\"|[^:\\s][^\\s]*)")
958 let ns = text as NSString
959 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
960 var value = ns.substring(with: m.range(at: 2))
961 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
962 pairs.append((ns.substring(with: m.range(at: 1)), value))
963 }
964 return pairs
965 }
966
967 private func timestamp(_ text: String) -> String {
968 guard let stamp = Timestamp.parse(text) else { return Self.escape(text) }
969 func date(_ p: Timestamp.Point) -> String { String(format: "%04d-%02d-%02d", p.year, p.month, p.day) }
970 func time(_ p: Timestamp.Point) -> String? {
971 guard let h = p.hour, let m = p.minute else { return nil }
972 return String(format: "%02d:%02d", h, m)
973 }
974 func element(_ p: Timestamp.Point, full: Bool) -> String {
975 let datetime = date(p) + (time(p).map { "T" + $0 } ?? "")
976 let shown = full ? date(p) + (time(p).map { " " + $0 } ?? "") : (time(p) ?? date(p))
977 return "<time class=\"timestamp\" datetime=\"\(datetime)\">\(shown)</time>"
978 }
979 guard let end = stamp.end else { return element(stamp.start, full: true) }
980 let sameDay = end.year == stamp.start.year && end.month == stamp.start.month && end.day == stamp.start.day
981 return element(stamp.start, full: true) + "–" + element(end, full: !sameDay)
982 }
983
984 private func footnote(_ text: String) -> String {
985 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return Self.escape(text) }
986 var label = String(m.1)
987 let inlineText = m.2.map(String.init)
988 if label.isEmpty {
989 anonymous += 1
990 label = "anonymous-\(anonymous)"
991 }
992 let number: Int
993 if let existing = footnoteNumbers[label] {
994 number = existing
995 } else {
996 let content: FootnoteContent
997 if let inlineText {
998 content = .inline(inlineText)
999 } else if let definition = definitions[label] {
1000 content = .definition(definition)
1001 } else {
1002 return Self.escape(text)
1003 }
1004 footnoteOrder.append((label, content))
1005 number = footnoteOrder.count
1006 footnoteNumbers[label] = number
1007 }
1008 return "<sup class=\"footnote-ref\"><a id=\"fnr-\(number)\" href=\"#fn-\(number)\">\(number)</a></sup>"
1009 }
1010}