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