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