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