Sources/OrgCore/Export/LaTeXExport.swift
1930 lines · 102808 bytes
89 symbols in this file
LaTeXExportUnsupporteddocumentexpandedLaTeXRendererUnsupporteddepthtemplateparsedpreamblecapitalizenormalizetrimprotecttextttremoveIndentationreferencebodyblankLinesAffiliatedattributevaluevaluehaselementspruneddrawerNamecleanLineBreakssectionheadlineexportedSiblingsblockTypeelementwrapLabelblocksblockContentshasContentskeywordparagraphremoveBlankLinesisOrderedBulletlistitemstartsWithLaTeXSnippettablehasSpecialRowsdecoratecaptionLabelblockformatCodeisResultsblockLocverseInlineinlineItemsmergenormalizeIndentationscanstripwidthdedentinlineStringinlinetranscodemathValueobjectplainTexttexLogosisWordtimestampdatelinkTargetisImagesoleImagelinkfileURIrefusePlainLinksIntoObjectsplainTextAndLinkswordstargetnamedElementresolveHeadinginlineImageFloatcountFootnotesexcludedfootnotefootnoteBodypreviousSibling
1import Foundation
2
3/// LaTeX export as ox-latex (Org 9.8.7) writes it under `emacs -Q`: the default packages,
4/// `article`, `report` or `book` sectioning, `verbatim` source blocks, `tabular` tables. What it
5/// can't write as Emacs would throws `Unsupported`, naming the construct, instead of writing
6/// something else. Labels are made from the document, where Emacs picks them at random.
7public enum LaTeXExport {
8 public struct Unsupported: Error, LocalizedError, Equatable, CustomStringConvertible {
9 public let reason: String
10 public init(reason: String) { self.reason = reason }
11 public var errorDescription: String? { reason }
12 public var description: String { reason }
13 }
14
15 /// `org-latex-classes`: each class's header and its sectioning, numbered and not.
16 static let classes: [String: (header: String, sections: [(String, String)])] = {
17 let part = ("\\part{%s}", "\\part*{%s}")
18 let chapter = ("\\chapter{%s}", "\\chapter*{%s}")
19 let section = ("\\section{%s}", "\\section*{%s}")
20 let subsection = ("\\subsection{%s}", "\\subsection*{%s}")
21 let subsubsection = ("\\subsubsection{%s}", "\\subsubsection*{%s}")
22 return [
23 "article": ("\\documentclass[11pt]{article}", [section, subsection, subsubsection, ("\\paragraph{%s}", "\\paragraph*{%s}"), ("\\subparagraph{%s}", "\\subparagraph*{%s}")]),
24 "report": ("\\documentclass[11pt]{report}", [part, chapter, section, subsection, subsubsection]),
25 "book": ("\\documentclass[11pt]{book}", [part, chapter, section, subsection, subsubsection]),
26 ]
27 }()
28
29 /// `org-latex-default-packages-alist`: options, package and the compilers it is for.
30 static let packages: [(String, String, [String])] = [
31 ("", "amsmath", ["lualatex", "xelatex"]), ("", "fontspec", ["lualatex", "xelatex"]),
32 ("utf8", "inputenc", ["pdflatex"]), ("T1", "fontenc", ["pdflatex"]),
33 ("", "graphicx", []), ("", "longtable", []), ("", "wrapfig", []), ("", "rotating", []), ("normalem", "ulem", []),
34 ("", "amsmath", ["pdflatex"]), ("", "amssymb", ["pdflatex"]), ("", "capt-of", []), ("", "hyperref", []),
35 ]
36
37 static let compilers = ["pdflatex", "xelatex", "lualatex"]
38
39 /// A `.tex` document, or with `bodyOnly` what goes between `\begin{document}` and
40 /// `\end{document}` without the title and contents. `author` stands for `user-full-name`,
41 /// `language` for `org-export-default-language`, `now` for the `% Created` line. `file` adds
42 /// the final newline `org-export-to-file` writes.
43 public static func document(
44 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
45 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false
46 ) throws -> String {
47 let text = try expanded(ExportPreprocess.decodedLineEnds(text), settings: settings, path: path, now: now)
48 let tree = OrgParser.parse(text, defaults: settings)
49 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
50 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
51 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
52 let body = try renderer.body()
53 let output = bodyOnly ? body : try renderer.template(body, author: author, now: now, timeZone: timeZone)
54 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
55 }
56
57 /// `text` with `#+INCLUDE`s and macros expanded, as `org-export-as` does before parsing.
58 static func expanded(_ text: String, settings: OrgSettings, path: String?, now: Date) throws -> String {
59 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
60 let included = ExportPreprocess.includes(text, directory: directory)
61 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
62 let marker = "\u{E000}"
63 var literal = included
64 if included.contains("{{{") {
65 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
66 let ns = included as NSString
67 let nodes = OrgParser.parse(included, defaults: settings).root.descendants()
68 // A macro a plain link runs on into is part of the link in Org, not expanded.
69 let links = ASCIIRenderer.plainLink.matches(in: included, range: NSRange(location: 0, length: ns.length)).map(\.range)
70 for macro in nodes where macro.kind == .macro {
71 if links.contains(where: { $0.location < macro.range.lowerBound && NSMaxRange($0) > macro.range.lowerBound }) {
72 throw LaTeXExport.Unsupported(reason: "Plain links running into other objects")
73 }
74 }
75 let kept = nodes
76 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
77 var out = ""
78 var at = 0
79 for range in kept.sorted(by: { $0.lowerBound < $1.lowerBound }) where range.lowerBound >= at {
80 out += ns.substring(with: NSRange(location: at, length: range.lowerBound - at))
81 out += ns.substring(with: NSRange(location: range.lowerBound, length: range.count)).replacingOccurrences(of: "{{{", with: marker + "{{")
82 at = range.upperBound
83 }
84 literal = out + ns.substring(from: at)
85 }
86 return ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{")
87 }
88}
89
90final class LaTeXRenderer {
91 typealias Unsupported = LaTeXExport.Unsupported
92
93 let tree: OrgTree
94 let source: NSString
95 let settings: OrgSettings
96 let options: ExportOptions
97 /// Keyword values by name, in order.
98 let keywords: [String: [String]]
99 let language: String
100 let className: String
101 /// `num` and `toc` as written: nil for t.
102 let num: Int?
103 let numbered: Bool
104 let toc: Int?
105 let withTOC: Bool
106 let timeStampFile: Bool
107 private var selected: Set<Int>?
108 /// Added to heading levels.
109 private var levelOffset = 0
110 private var exportSource: ExportSource
111 private let model: DocumentModel
112
113 init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String) throws {
114 self.tree = tree
115 source = text as NSString
116 self.settings = settings
117 exportSource = ExportSource(tree: tree, text: text)
118 model = DocumentModel(tree: tree)
119 var keywords: [String: [String]] = [:]
120 for line in lines {
121 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
122 keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
123 }
124 self.keywords = keywords
125 options = ExportOptions.parse(lines.joined(separator: "\n"))
126 self.language = keywords["LANGUAGE"]?.last ?? language
127 className = options.latexClass ?? "article"
128 guard LaTeXExport.classes[className] != nil else { throw Unsupported(reason: "Unknown LaTeX class `\(className)'") }
129
130 // `#+OPTIONS` this export follows; any other item only at its default.
131 let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
132 "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
133 "broken-links": "nil", "'": "nil", "<": "t", "d": "(not \"LOGBOOK\")", "latex-use-sans": "nil", "expand-links": "t"]
134 for (key, value) in options.items {
135 if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
136 }
137 let items = options.items
138 func depth(_ key: String) throws -> (Bool, Int?) {
139 guard let v = items[key] else { return (true, nil) }
140 if v == "nil" { return (false, nil) }
141 if v == "t" { return (true, nil) }
142 guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
143 return (true, n)
144 }
145 (numbered, num) = try depth("num")
146 (withTOC, toc) = try depth("toc")
147 timeStampFile = items["timestamp"] != "nil"
148 if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
149 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "LATEX_CLASS_PRE", "LATEX_FOOTNOTE_COMMAND", "CALL", "EXPORT_LATEX_CLASS"] where keywords[key] != nil {
150 throw Unsupported(reason: "#+\(key)")
151 }
152 for line in options.latexHeader + options.latexHeaderExtra + (options.latexClassOptions.map { [$0] } ?? [])
153 where line.contains("{babel}") || line.contains("{polyglossia}") || line.contains("\\babelprovide") || line.contains("[AUTO]") {
154 throw Unsupported(reason: "Babel or Polyglossia in the LaTeX header")
155 }
156 // Radio links: links that are only words.
157 if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
158 throw Unsupported(reason: "Radio targets")
159 }
160 let kinds = Set(tree.root.descendants().map(\.kind))
161 for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
162 (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
163 (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
164 throw Unsupported(reason: name)
165 }
166 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
167 // `:headline-offset`: the shallowest exported heading is level 1.
168 let options = options
169 let selected = selected
170 let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
171 .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
172 levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
173 try countFootnotes()
174 }
175
176 // MARK: - Template
177
178 /// `org-latex-template`.
179 func template(_ body: String, author: String, now: Date, timeZone: TimeZone) throws -> String {
180 var out = ""
181 if timeStampFile {
182 let formatter = DateFormatter()
183 formatter.locale = Locale(identifier: "en_US_POSIX")
184 formatter.timeZone = timeZone
185 formatter.dateFormat = "yyyy-MM-dd EEE HH:mm"
186 out += "% Created \(formatter.string(from: now))\n"
187 }
188 let compiler = options.latexCompiler ?? "pdflatex"
189 if LaTeXExport.compilers.contains(compiler) { out += "% Intended LaTeX compiler: \(compiler)\n" }
190 out += preamble(compiler: compiler)
191 if numbered, let num { out += "\\setcounter{secnumdepth}{\(num)}\n" }
192 var authorText: String? = try keywords["AUTHOR"].map { try parsed($0) } ?? (author.isEmpty ? nil : try inlineString(author))
193 if authorText?.isEmpty == true { authorText = nil }
194 if options.author, let authorText { out += "\\author{\(authorText)}\n" }
195 // The default, `\today`, is a LaTeX fragment, which `tex:nil` takes out.
196 let date = try keywords["DATE"].map { try parsed($0) } ?? (options.tex ? "\\today" : "")
197 out += "\\date{\(options.date ? date : "")}\n"
198 let title = try keywords["TITLE"].map { try parsed($0) } ?? ""
199 // An empty `#+SUBTITLE` parses to nil, which ox-latex leaves out.
200 let subtitle = try keywords["SUBTITLE"].flatMap({ $0 == [""] ? nil : $0 }).map { "\\\\\\medskip\n\\large " + (try parsed($0)) } ?? ""
201 out += "\\title{\(title)\(subtitle)}\n"
202 let lang = Self.languageNames[self.language] ?? self.language
203 out += "\\hypersetup{\n pdfauthor={\(options.author ? authorText ?? "" : "")},\n pdftitle={\(options.title ? title : "")},\n"
204 out += " pdfkeywords={\(try keywords["KEYWORDS"].map { try parsed($0) } ?? "")},\n"
205 out += " pdfsubject={\(try keywords["DESCRIPTION"].map { try parsed($0) } ?? "")},\n pdfcreator={},\n pdflang={\(Self.capitalize(lang))}}\n"
206 out += "\\begin{document}\n\n"
207 if options.title, !title.isEmpty { out += "\\maketitle\n" }
208 if withTOC {
209 if let toc { out += "\\setcounter{tocdepth}{\(toc)}\n" }
210 out += "\\tableofcontents\n\n"
211 }
212 return out + body + "\\end{document}"
213 }
214
215 /// A keyword parsed as Org text, its lines joined with spaces.
216 private func parsed(_ values: [String]) throws -> String {
217 if values.count > 1, values.contains("") { throw Unsupported(reason: "Repeated keywords with an empty value") }
218 return try inlineString(values.joined(separator: " "))
219 }
220
221 /// `org-latex-make-preamble` with the class, its options and the header lines.
222 private func preamble(compiler: String) -> String {
223 var header = LaTeXExport.classes[className]!.header
224 if let classOptions = options.latexClassOptions {
225 header = header.replacingOccurrences(of: "[11pt]", with: classOptions)
226 }
227 let known = LaTeXExport.compilers.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame }
228 let packages = LaTeXExport.packages.filter { !known || $0.2.isEmpty || $0.2.contains { $0.caseInsensitiveCompare(compiler) == .orderedSame } }
229 .map { $0.0.isEmpty ? "\\usepackage{\($0.1)}" : "\\usepackage[\($0.0)]{\($0.1)}" }
230 var out = header + "\n\n" + packages.joined(separator: "\n")
231 let extra = [options.latexHeader, options.latexHeaderExtra].filter { !$0.isEmpty }.map { Self.normalize($0.joined(separator: "\n")) }.joined()
232 if extra.contains(where: { !$0.isWhitespace }) { out += "\n" + extra }
233 return Self.normalize(out)
234 }
235
236 /// `:lang-name` in `org-latex-language-alist`.
237 static let languageNames: [String: String] = [
238 "af": "Afrikaans", "am": "Amharic", "ar": "Arabic", "ast": "Asturian", "bg": "Bulgarian", "bn": "Bengali", "bo": "Tibetan",
239 "br": "Breton", "ca": "Catalan", "cop": "Coptic", "cs": "Czech", "cy": "Welsh", "da": "Danish", "de": "German", "de-de": "German",
240 "de-at": "German", "dsb": "Lower Sorbian", "dv": "Dhivehi", "el": "Greek", "el-polyton": "Polytonic Greek", "grc": "Ancient Greek",
241 "en": "English", "en-au": "English", "en-ca": "English", "en-gb": "English", "en-nz": "English", "en-us": "English",
242 "eo": "Esperanto", "es": "Spanish", "es-mx": "Spanish", "et": "Estonian", "eu": "Basque", "fa": "Persian", "fi": "Finnish",
243 "fr": "French", "fr-ca": "French", "fur": "Friulian", "ga": "Irish Gaelic", "gd": "Scottish Gaelic", "gl": "Galician",
244 "he": "Hebrew", "hi": "Hindi", "hr": "Croatian", "hsb": "Upper Sorbian", "hu": "Magyar", "hy": "Armenian", "ia": "Interlingua",
245 "id": "Indonesian", "is": "Icelandic", "it": "Italian", "kn": "Kannada", "la": "Latin", "la-classic": "Classic Latin",
246 "la-medieval": "Medieval Latin", "la-ecclesiastic": "Ecclesiastic Latin", "lo": "Lao", "lt": "Lithuanian", "lv": "Latvian",
247 "ml": "Malayalam", "mr": "Marathi", "ms": "Malay", "nb": "Norwegian Bokmål", "nl": "Dutch", "nn": "Norwegian Nynorsk",
248 "no": "Norwegian", "oc": "Occitan", "pl": "Polish", "pms": "Piedmontese", "pt": "Portuges", "pt-br": "Portuges", "rm": "Romansh",
249 "ro": "Romanian", "ru": "Russian", "sa": "Sanskrit", "sk": "Slovak", "sl": "Slovene", "sq": "Albanian", "sr": "Serbian",
250 "sr-cyrl": "Serbian", "sr-latn": "Serbian", "sv": "Swedish", "syr": "Syriac", "ta": "Tamil", "te": "Telugu", "th": "Thai",
251 "tk": "Turkmen", "tr": "Turkish", "uk": "Ukrainian", "ur": "Urdu", "vi": "Vietnamese", "zh": "Chinese Simplified",
252 "zh-cn": "Chinese Simplified", "zh-tw": "Chinese Traditional",
253 ]
254
255 /// Emacs's `capitalize`: each word's first letter up, the rest down.
256 static func capitalize(_ s: String) -> String {
257 var out = ""
258 var inWord = false
259 for c in s {
260 let word = c.isLetter || c.isNumber
261 out += word ? (inWord ? c.lowercased() : c.uppercased()) : String(c)
262 inWord = word
263 }
264 return out
265 }
266
267 // MARK: - Strings
268
269 /// `org-element-normalize-string`: one final newline, none for the empty string.
270 static func normalize(_ s: String) -> String {
271 guard !s.isEmpty else { return "" }
272 // By scalar: a CR the file kept stays, as in Emacs, where "\r\n" isn't one character.
273 let scalars = s.unicodeScalars
274 var end = scalars.endIndex
275 var cut = scalars.endIndex
276 while end > scalars.startIndex {
277 let before = scalars.index(before: end)
278 if scalars[before] == " " || scalars[before] == "\t" {
279 end = before
280 } else if scalars[before] == "\n" {
281 end = before
282 cut = before
283 } else {
284 break
285 }
286 }
287 return String(scalars[..<cut]) + "\n"
288 }
289
290 /// `org-trim`.
291 static func trim(_ s: String) -> String { s.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\r\u{0C}\u{0B}")) }
292
293 /// `org-latex--protect-text`.
294 static func protect(_ s: String) -> String {
295 var out = ""
296 for c in s {
297 if "\\{}$%&_#~^".contains(c) { out += "\\" }
298 out.append(c)
299 }
300 return out
301 }
302
303 /// `org-latex--protect-texttt`.
304 static func texttt(_ s: String) -> String {
305 var out = ""
306 var i = s.startIndex
307 while i < s.endIndex {
308 let rest = s[i...]
309 if rest.hasPrefix("--") || rest.hasPrefix("<<") || rest.hasPrefix(">>") {
310 out += "\(s[i]){}\(s[i]){}"
311 i = s.index(i, offsetBy: 2)
312 continue
313 }
314 switch s[i] {
315 case "\\": out += "\\textbackslash{}"
316 case "~": out += "\\textasciitilde{}"
317 case "^": out += "\\textasciicircum{}"
318 case "{", "}", "$", "%", "&", "_", "#": out += "\\\(s[i])"
319 default: out.append(s[i])
320 }
321 i = s.index(after: i)
322 }
323 return "\\texttt{\(out)}"
324 }
325
326 /// `org-remove-indentation`: the common indentation of the non-blank lines removed.
327 static func removeIndentation(_ s: String) throws -> String {
328 let lines = s.components(separatedBy: "\n")
329 let indents = lines.filter { $0.contains { $0 != " " && $0 != "\t" } }.map { $0.prefix { $0 == " " || $0 == "\t" } }
330 guard let common = indents.map(\.count).min(), common > 0 else { return s }
331 if indents.contains(where: { $0.contains("\t") }) { throw Unsupported(reason: "Tabs in indented code") }
332 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n")
333 }
334
335 // MARK: - Labels
336
337 private var references: [String: String] = [:]
338 private var usedReferences: Set<String> = []
339
340 /// `org-export-get-reference`: a label for `key`, made from it so it stays the same between
341 /// exports of the same document.
342 func reference(_ key: String) -> String {
343 if let existing = references[key] { return existing }
344 var hash: UInt32 = 2_166_136_261
345 for byte in key.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 }
346 var value = hash & 0xFFFFFFF
347 var label = String(format: "org%07x", value)
348 while usedReferences.contains(label) {
349 value = (value &+ 1) & 0xFFFFFFF
350 label = String(format: "org%07x", value)
351 }
352 usedReferences.insert(label)
353 references[key] = label
354 return label
355 }
356
357 // MARK: - Document
358
359 /// The transcoded document, `org-element-normalize-string`'d.
360 func body() throws -> String {
361 var nodes = tree.root.children
362 // With a select tag, the text before the first heading isn't exported.
363 if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
364 var out = ""
365 for node in nodes {
366 if node.kind == .zerothSection {
367 out += Self.normalize(try elements(node.children, end: node.range.upperBound))
368 } else if node.kind == .section {
369 out += try section(node) ?? ""
370 }
371 }
372 return Self.normalize(out)
373 }
374
375 /// Blank lines at the end of `source[from..<to]`.
376 func blankLines(from: Int, to: Int) -> Int {
377 guard to > from else { return 0 }
378 let source = currentSource ?? self.source
379 let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
380 return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
381 }
382
383 /// Affiliated keywords of the element being transcoded.
384 struct Affiliated {
385 var caption: [String] = []
386 var name: String?
387 var attr: [String] = []
388 /// `#+RESULTS`' value, when it has the keyword.
389 var results: String?
390
391 /// `org-export-read-attribute :attr_latex`: values by key, nil for `nil` or nothing.
392 func attribute(_ key: String) -> String?? {
393 guard !attr.isEmpty else { return .none }
394 var s = attr.joined(separator: " ")
395 var pairs: [(String, String?)] = []
396 var pending: String?
397 let re = #/(?:^|[ \t]+)(:[-a-zA-Z0-9_]+)(?:[ \t]+|$)/#
398 while let m = s.firstMatch(of: re) {
399 if let pending { pairs.append((pending, Self.value(String(s[..<m.range.lowerBound])))) }
400 pending = String(m.1)
401 s = String(s[m.range.upperBound...])
402 }
403 if let pending { pairs.append((pending, Self.value(s))) }
404 guard let pair = pairs.first(where: { $0.0 == ":" + key }) else { return .none }
405 return .some(pair.1)
406 }
407
408 static func value(_ s: String) -> String? {
409 if s.isEmpty || s == "nil" { return nil }
410 if let m = s.wholeMatch(of: /"("+)?"/) { return m.1.map(String.init) ?? "" }
411 return s
412 }
413
414 /// The attribute's value, nil when absent or nil.
415 func value(_ key: String) -> String? { attribute(key) ?? nil }
416 func has(_ key: String) -> Bool { attribute(key) != nil }
417 }
418
419 /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
420 /// `org-export-data` joins a greater element's contents.
421 func elements(_ nodes: [SyntaxNode], end: Int) throws -> String {
422 var out = ""
423 var affiliated = Affiliated()
424 // The element before and its blank lines, which a comment after it may add to; they
425 // show only when it wrote something.
426 var pendingBlank = 0
427 var previous: SyntaxNode?
428 var previousWrote = false
429 var afterSrc = false
430 for (index, node) in nodes.enumerated() {
431 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
432 if node.kind == .affiliatedKeyword {
433 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
434 guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
435 let key = m.1.uppercased()
436 if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
437 switch key {
438 case "CAPTION":
439 if m.2 != nil { throw Unsupported(reason: "Short captions") }
440 affiliated.caption.append(String(m.3))
441 case "NAME": affiliated.name = String(m.3)
442 case "ATTR_LATEX": affiliated.attr.append(String(m.3))
443 case "RESULTS": affiliated.results = String(m.3)
444 default: break
445 }
446 continue
447 }
448 defer { affiliated = Affiliated() }
449 // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
450 // the block too, as if they had never been there.
451 if node.kind == .block, blockType(node) == "src" {
452 let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
453 if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
454 afterSrc = true
455 if exports == "none" { continue }
456 } else if let results = affiliated.results {
457 if afterSrc {
458 afterSrc = false
459 continue
460 }
461 if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
462 if affiliated.name == nil { affiliated.name = results }
463 } else {
464 afterSrc = false
465 }
466 if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
467 // `org-export--skip-p`: the element before keeps at least one blank line.
468 if previous != nil {
469 let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
470 if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
471 pendingBlank = blank
472 }
473 continue
474 }
475 guard let result = try element(node, affiliated: affiliated, previous: previous, previousBlank: pendingBlank) else {
476 if !pruned(node) {
477 previous = node
478 previousWrote = false
479 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
480 }
481 continue
482 }
483 previous = node
484 previousWrote = true
485 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
486 var text = Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
487 if node.kind == .paragraph { text = Self.cleanLineBreaks(text) }
488 out += text
489 }
490 return out
491 }
492
493 /// Elements `org-export--prune-tree` takes out of the tree.
494 private func pruned(_ node: SyntaxNode) -> Bool {
495 switch node.kind {
496 case .planning, .propertyDrawer, .clock, .footnoteDefinition: return true
497 case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
498 case .latexEnvironment: return !options.tex
499 default: return false
500 }
501 }
502
503 private func drawerName(_ node: SyntaxNode) -> String {
504 node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
505 }
506
507 /// `org-latex-clean-invalid-line-breaks`.
508 static func cleanLineBreaks(_ s: String) -> String {
509 s.replacing(#/(?m)(\\end\{[A-Za-z0-9*]+\}|^)[ \t]*\\\\[ \t]*$/#) { String($0.1) }
510 }
511
512 // MARK: - Headlines
513
514 /// A section's heading and contents, nil when not exported.
515 private func section(_ node: SyntaxNode) throws -> String? {
516 guard let heading = node.firstChild(.heading) else { return nil }
517 // `org-footnote-section`'s heading isn't exported.
518 if heading.firstChild(.title)?.text == "Footnotes" { return nil }
519 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
520 if export == .nothing { return nil }
521 let children = node.children.filter { $0.kind != .heading }
522 let body = children.filter { $0.kind != .section }
523 let subsections = children.filter { $0.kind == .section }
524 var contents: String?
525 if export == .all {
526 let out = Self.normalize(try elements(body, end: subsections.first?.range.lowerBound ?? node.range.upperBound))
527 contents = Self.normalize(out + (try subsections.compactMap { try section($0) }.joined()))
528 }
529 let first = children.first?.range.lowerBound ?? node.range.upperBound
530 let preBlank = children.isEmpty ? 0 : blankLines(from: heading.range.lowerBound, to: first)
531 return Self.normalize(try headline(heading, section: node, contents: contents, preBlank: preBlank))
532 }
533
534 /// `org-latex-headline`.
535 private func headline(_ heading: SyntaxNode, section: SyntaxNode, contents: String?, preBlank: Int) throws -> String {
536 let tokens = heading.tokens
537 let level = (tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
538 if let index = model.headings.firstIndex(where: { $0.headingRange.lowerBound == heading.range.lowerBound }) {
539 let keys = model.headings[index].properties.map { $0.key.uppercased() }
540 if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
541 }
542 let isNumbered = numbered && (num.map { level <= $0 } ?? true)
543 let titleNode = heading.firstChild(.title)
544 if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
545 let text = try titleNode.map { try Self.trim(inline($0, sectionTitle: true)) } ?? ""
546 var full = ""
547 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text {
548 full += "{\\bfseries\\sffamily \(plainText(todo))} "
549 }
550 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text,
551 let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
552 full += "\\framebox{\\#\(letter)} "
553 }
554 full += text
555 // The title for the table of contents, without the tags unless `tags` is t.
556 let tocTitle = (options.items["tags"] ?? "t") == "t" ? nil : full
557 if options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
558 let shown = tags.split(separator: ":").map(String.init)
559 if !shown.isEmpty { full += "\\hfill{}\\textsc{\(shown.map(Self.protect).joined(separator: ":"))}" }
560 }
561 let label = "\\label{sec:\(reference("heading@\(heading.range.lowerBound)"))}\n"
562 let pre = String(repeating: "\n", count: preBlank)
563 let sections = LaTeXExport.classes[className]!.sections
564 if level > options.headlineLevels || level > sections.count {
565 let siblings = exportedSiblings(section)
566 let first = siblings.first == section.range.lowerBound
567 let last = siblings.last == section.range.lowerBound
568 let list = isNumbered ? "enumerate" : "itemize"
569 var out = first ? "\\begin{\(list)}\n" : ""
570 out += "\\item" + (full.firstMatch(of: /^[ \t]*\[/) != nil ? "\\relax" : "") + " " + full + "\n" + label + pre + (contents ?? "")
571 if last {
572 while let c = out.last, c == " " || c == "\t" || c == "\n" { out.removeLast() }
573 out += "\n\\end{\(list)}"
574 }
575 return out
576 }
577 var format = isNumbered ? sections[level - 1].0 : sections[level - 1].1
578 // A numbered section's title in the table of contents, when it differs.
579 if isNumbered, let tocTitle, tocTitle != full, let brace = format.firstIndex(of: "{") {
580 // Emacs puts it in a `format` string, where `%` is a directive.
581 if tocTitle.contains("%") { throw Unsupported(reason: "% in a heading with tags not in the table of contents") }
582 let optional = tocTitle.replacingOccurrences(of: "[", with: "(").replacingOccurrences(of: "]", with: ")")
583 format.insert(contentsOf: "[\(optional)]", at: brace)
584 }
585 return format.replacingOccurrences(of: "%s", with: full) + "\n" + label + pre + (contents ?? "")
586 }
587
588 /// The headline sections exported beside `section` at its level, by start: a low-level
589 /// headline opens its list when it is the first and closes it when it is the last.
590 private func exportedSiblings(_ section: SyntaxNode) -> [Int] {
591 guard let parent = section.parent else { return [section.range.lowerBound] }
592 return parent.children.filter { child in
593 guard child.kind == .section, let heading = child.firstChild(.heading) else { return false }
594 return HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .nothing
595 }.map(\.range.lowerBound)
596 }
597
598 // MARK: - Elements
599
600 private func blockType(_ node: SyntaxNode) -> String {
601 node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
602 }
603
604 /// One element's transcoding, nil for none.
605 private func element(_ node: SyntaxNode, affiliated: Affiliated, previous: SyntaxNode?, previousBlank: Int) throws -> String? {
606 switch node.kind {
607 case .paragraph:
608 return try paragraph(node, affiliated: affiliated)
609 case .plainList:
610 return try list(node, affiliated: affiliated)
611 case .table:
612 return try table(node, affiliated: affiliated)
613 case .block:
614 return try block(node, affiliated: affiliated)
615 case .horizontalRule:
616 var out = previous != nil && previousBlank == 0 ? "\n" : ""
617 out += try wrapLabel(affiliated, "\\noindent\\rule{\(affiliated.value("width") ?? "\\textwidth")}{\(affiliated.value("thickness") ?? "0.5pt")}")
618 return out
619 case .fixedWidth:
620 let value = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }
621 .map { $0.replacingOccurrences(of: "^[ \\t]*: ?", with: "", options: .regularExpression) }.joined(separator: "\n")
622 return try wrapLabel(affiliated, "\\begin{verbatim}\n\(try Self.removeIndentation(value))\n\\end{verbatim}")
623 case .latexEnvironment:
624 guard options.tex else { return nil }
625 if affiliated.name != nil || !affiliated.caption.isEmpty { throw Unsupported(reason: "Named or captioned LaTeX environments") }
626 var value = node.text
627 while value.hasSuffix("\n") { value.removeLast() }
628 return try Self.removeIndentation(value) + "\n"
629 case .keyword:
630 return try keyword(node)
631 case .drawer:
632 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
633 // `org-latex-format-drawer-default-function` gives nil for no contents.
634 guard hasContents(node.children) else { return nil }
635 return try wrapLabel(affiliated, Self.normalize(try elements(node.children, end: node.range.upperBound)))
636 case .dynamicBlock:
637 let lines = node.text.components(separatedBy: "\n")
638 guard let contents = try blockContents(lines.dropFirst().dropLast(2).joined(separator: "\n")) else { return nil }
639 return try wrapLabel(affiliated, Self.normalize(contents))
640 case .planning, .propertyDrawer, .clock, .footnoteDefinition, .nodeProperty:
641 return nil
642 default:
643 throw Unsupported(reason: "\(node.kind)")
644 }
645 }
646
647 /// `org-latex--wrap-label`.
648 private func wrapLabel(_ affiliated: Affiliated, _ output: String) throws -> String {
649 guard let name = affiliated.name, output.contains(where: { !$0.isWhitespace }) else { return output }
650 return "\\phantomsection\n\\label{\(reference("name:" + name))}\n" + output
651 }
652
653 /// Org text parsed and transcoded as elements.
654 func blocks(_ text: String) throws -> String {
655 let tree = OrgParser.parse(text, defaults: settings)
656 let saved = exportSource
657 exportSource = ExportSource(tree: tree, text: text)
658 defer { exportSource = saved }
659 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
660 if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
661 let saveSource = currentSource
662 currentSource = text as NSString
663 defer { currentSource = saveSource }
664 return try elements(nodes, end: (text as NSString).length)
665 }
666
667 /// `blocks`, or nil when `text` has no element the export keeps, where Emacs passes nil
668 /// contents.
669 func blockContents(_ text: String) throws -> String? {
670 let tree = OrgParser.parse(text, defaults: settings)
671 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
672 let saved = exportSource
673 exportSource = ExportSource(tree: tree, text: text)
674 defer { exportSource = saved }
675 guard hasContents(nodes) else { return nil }
676 return try blocks(text)
677 }
678
679 /// Whether `nodes` hold an element the export keeps.
680 private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
681 nodes.indices.contains { index in
682 let node = nodes[index]
683 switch node.kind {
684 case .comment: return false
685 case .affiliatedKeyword:
686 // Org parses affiliated keywords with no element right after them as keywords.
687 var last = index
688 while last + 1 < nodes.count, nodes[last + 1].kind == .affiliatedKeyword,
689 nodes[last].range.upperBound == nodes[last + 1].range.lowerBound { last += 1 }
690 return last + 1 == nodes.count || nodes[last].range.upperBound != nodes[last + 1].range.lowerBound
691 case .block:
692 let type = blockType(node)
693 if type == "comment" { return false }
694 if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
695 return !isResults(node)
696 default: return !pruned(node)
697 }
698 }
699 }
700
701 /// The text blank lines are counted in, when it isn't the document's.
702 private var currentSource: NSString?
703
704 private func keyword(_ node: SyntaxNode) throws -> String? {
705 let line = node.text.trimmingCharacters(in: .newlines)
706 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { return nil }
707 let value = m.2.map(String.init) ?? ""
708 switch m.1.uppercased() {
709 case "LATEX": return value
710 case "INDEX": return "\\index{\(value)}"
711 case "TOC":
712 if value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: local") }
713 if value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil {
714 let depth = value.firstMatch(of: /\b([0-9]+)\b/).map { "\\setcounter{tocdepth}{\($0.1)}\n" } ?? ""
715 return depth + "\\tableofcontents"
716 }
717 if value.range(of: "\\btables\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\listoftables" }
718 if value.range(of: "\\blistings\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "\\lstlistoflistings" }
719 return nil
720 default: return nil
721 }
722 }
723
724 // MARK: Paragraphs
725
726 private func paragraph(_ node: SyntaxNode, affiliated: Affiliated, ignoreFirst: Bool = false) throws -> String {
727 var items = Self.normalizeIndentation(try inlineItems(node), ignoreFirst: ignoreFirst)
728 if let image = soleImage(items) {
729 items = []
730 return try inlineImage(image, affiliated: affiliated, alone: true)
731 }
732 if items.contains(where: { if case .object(let n, _) = $0, n.kind == .link, isImage(n) { return true } else { return false } }) {
733 currentAffiliated = affiliated
734 defer { currentAffiliated = nil }
735 return Self.removeBlankLines(try transcode(items))
736 }
737 if !affiliated.caption.isEmpty { throw Unsupported(reason: "Captioned paragraphs") }
738 return Self.removeBlankLines(try transcode(items))
739 }
740
741 private var currentAffiliated: Affiliated?
742
743 /// `org-remove-blank-lines`.
744 static func removeBlankLines(_ s: String) -> String {
745 s.replacing(#/\n(?:[ \t]*\n)+/#, with: "\n")
746 }
747
748 // MARK: Lists
749
750 private func isOrderedBullet(_ item: SyntaxNode) -> Bool {
751 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
752 return bullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
753 }
754
755 /// `org-latex-plain-list`, its type from the first item.
756 private func list(_ node: SyntaxNode, affiliated: Affiliated, orderedDepth: Int = 0) throws -> String {
757 let items = node.children.filter { $0.kind == .item }
758 guard let first = items.first else { return "" }
759 let ordered = isOrderedBullet(first)
760 let description = !ordered && first.firstChild(.itemTag) != nil
761 let type = affiliated.value("environment") ?? (ordered ? "enumerate" : description ? "description" : "itemize")
762 let depth = orderedDepth + (ordered ? 1 : 0)
763 var contents = ""
764 for (index, item) in items.enumerated() {
765 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
766 let text = try self.item(item, ordered: ordered, depth: depth)
767 contents += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
768 }
769 return try wrapLabel(affiliated, "\\begin{\(type)}\(affiliated.value("options") ?? "")\n\(Self.normalize(contents))\\end{\(type)}")
770 }
771
772 /// `org-latex-item`.
773 private func item(_ item: SyntaxNode, ordered: Bool, depth: Int) throws -> String {
774 var counter = ""
775 if let value = item.tokens.first(where: { $0.kind == .counter })?.text.firstMatch(of: /([0-9]+)/) {
776 guard ordered, depth < 5, let n = Int(value.1) else { throw Unsupported(reason: "Counters outside ordered lists") }
777 counter = "\\setcounter{enum\(["i", "ii", "iii", "iv"][depth - 1])}{\(n - 1)}\n"
778 } else if item.tokens.contains(where: { $0.kind == .counter }) {
779 throw Unsupported(reason: "Alphabetical counters")
780 }
781 let checkbox: String? = item.tokens.first { $0.kind == .checkbox }.map {
782 switch $0.text.uppercased() {
783 case "[X]": "$\\boxtimes$"
784 case "[-]": "$\\boxminus$"
785 default: "$\\square$"
786 }
787 }
788 var tag: String?
789 if let tagNode = item.firstChild(.itemTag) {
790 if tagNode.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in item tags") }
791 tag = try transcode(Self.merge(try inlineItems(tagNode)))
792 }
793 let children = item.children.filter { $0.kind != .itemTag }
794 var contents = ""
795 var previous: SyntaxNode?
796 for (index, child) in children.enumerated() {
797 let next = index + 1 < children.count ? children[index + 1].range.lowerBound : item.range.upperBound
798 var result: String?
799 if child.kind == .paragraph, previous == nil, index == 0 {
800 // The first paragraph's first line follows the bullet: its indentation doesn't count.
801 let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
802 let ignore = child.range.lowerBound < NSMaxRange(bulletLine)
803 result = try paragraph(child, affiliated: Affiliated(), ignoreFirst: ignore)
804 } else if child.kind == .plainList {
805 result = try list(child, affiliated: Affiliated(), orderedDepth: depth)
806 } else {
807 // Elements with affiliated keywords go through `elements`.
808 result = try elements([child], end: next)
809 if result == "" { result = nil }
810 if let r = result {
811 contents += r
812 previous = child
813 continue
814 }
815 }
816 guard let result else { continue }
817 previous = child
818 var text = Self.normalize(result) + String(repeating: "\n", count: blankLines(from: child.range.lowerBound, to: next))
819 if child.kind == .paragraph { text = Self.cleanLineBreaks(text) }
820 contents += text
821 }
822 if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") }
823 contents = Self.normalize(contents)
824 var out = counter + "\\item"
825 if let checkbox, let tag {
826 out += ordered ? "{\(checkbox) \(tag)} " : "[{\(checkbox) \(tag)}] "
827 } else if let label = checkbox ?? tag {
828 out += ordered ? "{\(label)} " : "[{\(label)}] "
829 } else if contents.firstMatch(of: /^[ \t]*\[/) != nil, !Self.startsWithLaTeXSnippet(children.first) {
830 out += "\\relax "
831 } else {
832 out += " "
833 }
834 return out + Self.trim(contents)
835 }
836
837 /// Whether `node` is a paragraph whose first object is a `@@latex:…@@` snippet.
838 static func startsWithLaTeXSnippet(_ node: SyntaxNode?) -> Bool {
839 guard let node, node.kind == .paragraph else { return false }
840 for element in node.elements {
841 switch element {
842 case .token(let token):
843 if token.text.contains(where: { !$0.isWhitespace }) { return false }
844 case .node(let n):
845 return n.kind == .exportSnippet && n.text.hasPrefix("@@latex:")
846 }
847 }
848 return false
849 }
850
851 // MARK: Tables
852
853 /// `org-table-number-regexp`.
854 static let numberPattern = try! NSRegularExpression(pattern: "^(?:[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .caseInsensitive)
855
856 private func table(_ node: SyntaxNode, affiliated: Affiliated) throws -> String {
857 let rows = node.children.filter { $0.kind == .tableRow }
858 if node.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in tables") }
859 let mode = affiliated.value("mode") ?? "table"
860 guard mode == "table" else { throw Unsupported(reason: "#+ATTR_LATEX: :mode \(mode)") }
861 let environment = affiliated.value("environment") ?? "tabular"
862 if ["longtable", "longtabu", "tabbing"].contains(environment) { throw Unsupported(reason: "#+ATTR_LATEX: :environment \(environment)") }
863 let booktabs = affiliated.has("booktabs") ? affiliated.value("booktabs") != nil : false
864 if booktabs { throw Unsupported(reason: "Booktabs tables") }
865 // Cells as transcoded, rules as nil.
866 var cells: [[String]?] = []
867 for row in rows {
868 let rowCells = row.children.filter { $0.kind == .tableCell }
869 if rowCells.isEmpty, row.text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") {
870 cells.append(nil)
871 continue
872 }
873 if rowCells.isEmpty { continue }
874 cells.append(try rowCells.map { try transcode(Self.merge(try inlineItems($0, trimmed: true))) })
875 }
876 let data = cells.compactMap { $0 }
877 if Self.hasSpecialRows(data.map { $0 }, raw: rows) { throw Unsupported(reason: "Tables with alignment cookies or special columns") }
878 let columns = data.first?.count ?? 0
879 var align = ""
880 for c in 0..<columns {
881 var numbers = 0, total = 0
882 var previousNumber = false
883 for row in data {
884 let value = c < row.count ? row[c] : ""
885 total += 1
886 let isNumber = Self.numberPattern.firstMatch(in: value, range: NSRange(location: 0, length: (value as NSString).length)) != nil
887 if isNumber || (value.isEmpty && previousNumber) {
888 previousNumber = true
889 numbers += 1
890 } else {
891 previousNumber = false
892 }
893 }
894 align += total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
895 }
896 let alignment = affiliated.value("align") ?? align
897 var contents = ""
898 for row in cells {
899 guard let row else {
900 contents += "\\hline\n"
901 continue
902 }
903 contents += Self.normalize(row.joined(separator: " & ") + "\\\\\n")
904 }
905 contents = Self.normalize(contents)
906 var width = ""
907 if let w = affiliated.value("width"), !["tabular", "longtable"].contains(environment) {
908 if ["tabu", "longtabu"].contains(environment) { throw Unsupported(reason: "tabu tables") }
909 width = "{\(w)}"
910 }
911 let opt = affiliated.value("options").map { "[\($0)]" } ?? ""
912 let table = "\\begin{\(environment)}\(opt)\(width){\(alignment)}\n\(contents)\\end{\(environment)}"
913 let caption = try captionLabel(affiliated, type: "table", prefix: "tab:")
914 return decorate(table, affiliated: affiliated, caption: caption, above: true)
915 }
916
917 /// Whether a table has rows of alignment cookies or a column of row marks.
918 static func hasSpecialRows(_ data: [[String]], raw: [SyntaxNode]) -> Bool {
919 let cookie = /^<[lrc]?[0-9]*>$/
920 for row in raw {
921 let cells = row.children.filter { $0.kind == .tableCell }.map { $0.text.trimmingCharacters(in: .whitespaces) }
922 guard !cells.isEmpty else { continue }
923 if cells.allSatisfy({ $0.isEmpty || $0.wholeMatch(of: cookie) != nil }), cells.contains(where: { !$0.isEmpty }) { return true }
924 }
925 let marks: Set<String> = ["", "#", "!", "$", "*", "^", "_", "/"]
926 let first = raw.compactMap { $0.children.first { $0.kind == .tableCell }?.text.trimmingCharacters(in: .whitespaces) }
927 return !first.isEmpty && first.allSatisfy(marks.contains) && first.contains { !$0.isEmpty }
928 }
929
930 /// `org-latex--decorate-table`.
931 private func decorate(_ table: String, affiliated: Affiliated, caption: String, above: Bool) -> String {
932 let floatEnvironment: String?
933 let float = affiliated.attribute("float")
934 switch float {
935 case .some(nil): floatEnvironment = nil
936 case .some(.some(let f)) where f == "sidewaystable" || f == "sideways": floatEnvironment = "sidewaystable"
937 case .some(.some("multicolumn")): floatEnvironment = "table*"
938 case .some(.some("t")): floatEnvironment = "table"
939 case .some(.some(let f)): floatEnvironment = f
940 case .none: floatEnvironment = caption.contains(where: { !$0.isWhitespace }) ? "table" : nil
941 }
942 let placement = affiliated.value("placement") ?? "[htbp]"
943 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
944 let font = affiliated.value("font").map { $0 + "\n" }
945 let captionText: String? = caption.isEmpty ? nil : caption
946 var out = ""
947 if let floatEnvironment {
948 out = "\\begin{\(floatEnvironment)}\(placement)\n" + (above ? caption : "") + (center ? "\\centering\n" : "") + (font ?? "")
949 } else if captionText != nil {
950 out = (center ? "\\begin{center}\n" : "") + (above ? caption : "") + (font.map { center ? $0 : "{" + $0 } ?? "")
951 } else if center {
952 out = "\\begin{center}\n" + (font ?? "")
953 } else if let font {
954 out = "{" + font
955 }
956 out += table
957 if let floatEnvironment {
958 out += (above ? "" : "\n" + caption) + "\n\\end{\(floatEnvironment)}"
959 } else if captionText != nil {
960 out += (above ? "" : "\n" + caption) + (center ? "\n\\end{center}" : "") + (font != nil && !center ? "}" : "")
961 } else if center {
962 out += "\n\\end{center}"
963 } else if font != nil {
964 out += "}"
965 }
966 return out
967 }
968
969 /// `org-latex--caption/label-string` for a float.
970 private func captionLabel(_ affiliated: Affiliated, type: String, prefix: String, srcBlock: Bool = false) throws -> String {
971 let nonfloat = (affiliated.attribute("float") == .some(nil) && !affiliated.caption.isEmpty) || (srcBlock && affiliated.value("float") == nil)
972 let label = affiliated.name.map { "\\label{\(prefix)\(reference("name:" + $0))}\n" } ?? ""
973 if let fromAttr = affiliated.value("caption"), fromAttr.contains(where: { !$0.isWhitespace }) { return fromAttr + "\n" }
974 guard !affiliated.caption.isEmpty else { return label }
975 let main = try inlineString(affiliated.caption.joined(separator: " "))
976 let trimmedLabel = Self.trim(label)
977 return nonfloat ? "\\captionof{\(type)}{\(trimmedLabel)\(main)}\n" : "\\caption{\(trimmedLabel)\(main)}\n"
978 }
979
980 // MARK: Blocks
981
982 private func block(_ node: SyntaxNode, affiliated: Affiliated) throws -> String? {
983 var lines = node.text.components(separatedBy: "\n")
984 if lines.last == "" { lines.removeLast() }
985 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
986 let type = m.1.lowercased()
987 let parameters = String(m.2)
988 let body = Array(lines.dropFirst().dropLast())
989 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
990 let text = unescaped.joined(separator: "\n")
991 switch type {
992 case "src":
993 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
994 if affiliated.has("float") { throw Unsupported(reason: "Floating source blocks") }
995 let code = try formatCode(lines)
996 let verbatim = "\\begin{verbatim}\n\(code)\\end{verbatim}"
997 guard !affiliated.caption.isEmpty else { return verbatim }
998 return verbatim + "\n" + (try captionLabel(affiliated, type: "figure", prefix: "lst:", srcBlock: true))
999 case "example":
1000 guard text.contains(where: { !$0.isWhitespace }) else { return nil }
1001 let environment = affiliated.value("environment") ?? "verbatim"
1002 return try wrapLabel(affiliated, "\\begin{\(environment)}\n\(try formatCode(lines))\\end{\(environment)}")
1003 case "quote", "center":
1004 // Emacs formats nil contents as `nil`.
1005 var contents: String?
1006 if let first = body.first, first.allSatisfy(\.isWhitespace) {
1007 // Org parses a blank first line as a paragraph of that line, which runs on to
1008 // the next blank line or element when it holds spaces.
1009 let blanks = body.prefix { $0.allSatisfy(\.isWhitespace) }.count
1010 if !first.isEmpty, blanks == 1, blanks < body.count { throw Unsupported(reason: "A line of spaces opening a \(type) block") }
1011 let paragraph = first.isEmpty ? "\n\n" : first + "\n"
1012 let rest = unescaped.dropFirst(blanks).joined(separator: "\n")
1013 contents = paragraph + String(repeating: "\n", count: blanks - 1) + (rest.isEmpty ? "" : try blockContents(rest) ?? "")
1014 } else if !body.isEmpty {
1015 contents = try blockContents(text)
1016 }
1017 let inner = contents.map(Self.normalize) ?? "nil"
1018 if type == "center" { return try wrapLabel(affiliated, "\\begin{center}\n\(inner)\\end{center}") }
1019 let environment = affiliated.value("environment") ?? "quote"
1020 return try wrapLabel(affiliated, "\\begin{\(environment)}\(affiliated.value("options") ?? "")\n\(inner)\\end{\(environment)}")
1021 case "verse":
1022 if !affiliated.attr.isEmpty { throw Unsupported(reason: "#+ATTR_LATEX on verse blocks") }
1023 return try wrapLabel(affiliated, try verse(unescaped))
1024 case "export":
1025 let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
1026 guard backend == "LATEX" || backend == "TEX" else { return nil }
1027 return try Self.removeIndentation(text + "\n")
1028 case "comment":
1029 return nil
1030 default:
1031 let caption = try captionLabel(affiliated, type: "figure", prefix: "")
1032 if !caption.isEmpty { throw Unsupported(reason: "Captioned special blocks") }
1033 return "\\begin{\(m.1)}\(affiliated.value("options") ?? "")\n" + Self.normalize(try blocks(text)) + "\\end{\(m.1)}"
1034 }
1035 }
1036
1037 /// `org-export-format-code-default` for a src or example block's lines.
1038 private func formatCode(_ lines: [String]) throws -> String {
1039 guard let parsed = Coderef.block(lines) else { return "" }
1040 let blockLoc = try blockLoc(lines, numbered: parsed.switches.numberLines != nil)
1041 var value = parsed.body.joined(separator: "\n")
1042 if !value.isEmpty { value += "\n" }
1043 let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
1044 var code = preserve ? value : try Self.removeIndentation(value)
1045 if code.hasSuffix("\n") { code.removeLast() }
1046 let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
1047 let loc = parsed.switches.numberLines == nil ? nil : blockLoc
1048 guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
1049 let width = loc.map { String($0 + lines.count).count } ?? 0
1050 let numberWidth = loc == nil ? 0 : width + 2
1051 let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
1052 return lines.enumerated().map { index, line in
1053 var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
1054 out += line
1055 if parsed.switches.retainLabels, let ref = refs[index + 1] {
1056 out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
1057 }
1058 return out
1059 }.joined(separator: "\n") + "\n"
1060 }
1061
1062 /// The src and example blocks the export writes, in order, as their lines: none under a
1063 /// section left out, with `:exports none`, or a src block's results.
1064 private lazy var exportedBlocks: [[String]] = {
1065 let source = ExportSource(tree: tree, text: self.source as String)
1066 return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
1067 var lines = node.text.components(separatedBy: "\n")
1068 if lines.last == "" { lines.removeLast() }
1069 guard Coderef.block(lines) != nil, !Self.excluded(node, by: self), !isResults(node) else { return nil }
1070 if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
1071 return lines
1072 }
1073 }()
1074
1075 /// Whether `node` is the results of the src block before it, which the export removes.
1076 private func isResults(_ node: SyntaxNode) -> Bool {
1077 guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
1078 let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
1079 guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
1080 let before = index - keywords.count - 1
1081 return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
1082 }
1083
1084 /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
1085 private lazy var blockLocs: [String: [Int?]] = {
1086 let blocks = exportedBlocks
1087 var locs: [String: [Int?]] = [:]
1088 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
1089 locs[lines.joined(separator: "\n"), default: []].append(loc)
1090 }
1091 return locs
1092 }()
1093
1094 /// `org-export-get-loc` of the block with `lines`, the next of those with the same text.
1095 private func blockLoc(_ lines: [String], numbered: Bool) throws -> Int? {
1096 let key = lines.joined(separator: "\n")
1097 guard let queue = blockLocs[key], !queue.isEmpty else {
1098 if numbered { throw Unsupported(reason: "Numbered blocks inside other blocks") }
1099 return nil
1100 }
1101 blockLocs[key] = Array(queue.dropFirst())
1102 return queue[0]
1103 }
1104
1105 /// `org-latex-verse-block` and the verse rules of `org-latex-plain-text`.
1106 private func verse(_ lines: [String]) throws -> String {
1107 let text = lines.joined(separator: "\n") + "\n"
1108 // The contents are objects: paragraphs and the blank lines between them.
1109 let tree = OrgParser.parse(text, defaults: settings)
1110 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1111 guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
1112 let ns = text as NSString
1113 var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
1114 for (index, node) in nodes.enumerated() {
1115 raw += try inlineItems(node)
1116 let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
1117 raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
1118 }
1119 inVerse = true
1120 defer { inVerse = false }
1121 let items = Self.normalizeIndentation(Self.merge(raw), ignoreFirst: false)
1122 var contents = try transcode(items)
1123 while let c = contents.last, c.isWhitespace { contents.removeLast() }
1124 return Self.cleanLineBreaks("\\begin{verse}\n" + contents + "\n\\end{verse}")
1125 }
1126
1127 private var inVerse = false
1128
1129 // MARK: - Objects
1130
1131 /// Inline content: text runs and objects with their own contents.
1132 indirect enum Inline {
1133 case text(String)
1134 case object(SyntaxNode, [Inline])
1135 }
1136
1137 /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
1138 func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) throws -> [Inline] {
1139 var items: [Inline] = []
1140 var skipNewline = false
1141 for element in node.elements {
1142 switch element {
1143 case .token(let token):
1144 switch token.kind {
1145 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1146 continue
1147 default:
1148 var text = token.text
1149 if skipNewline {
1150 let rest = text.drop { $0 == " " || $0 == "\t" }
1151 if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1152 }
1153 if !text.isEmpty { items.append(.text(text)) }
1154 }
1155 case .node(let child):
1156 skipNewline = false
1157 switch child.kind {
1158 case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1159 items.append(.object(child, try inlineItems(child)))
1160 case .link:
1161 items.append(.object(child, try child.firstChild(.linkDescription).map { try inlineItems($0) } ?? []))
1162 case .superscript, .subscript:
1163 let text = child.text
1164 let braced = text.dropFirst().hasPrefix("{")
1165 if options.scripts == .off || (options.scripts == .braces && !braced) {
1166 items.append(.text(text))
1167 } else if braced {
1168 items.append(.object(child, try inlineItems(child)))
1169 } else {
1170 items.append(.object(child, [.text(String(text.dropFirst()))]))
1171 }
1172 case .lineBreak where trimmed:
1173 // A table cell has no line ends.
1174 items.append(.text(child.text))
1175 case .lineBreak:
1176 items.append(.object(child, []))
1177 skipNewline = true
1178 default:
1179 items.append(.object(child, []))
1180 }
1181 }
1182 }
1183 if trimmed {
1184 if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1185 if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1186 }
1187 return Self.merge(items)
1188 }
1189
1190 /// Adjacent text runs joined.
1191 static func merge(_ items: [Inline]) -> [Inline] {
1192 var out: [Inline] = []
1193 for item in items {
1194 if case .text(let t) = item, case .text(let previous)? = out.last {
1195 out[out.count - 1] = .text(previous + t)
1196 } else if case .text(let t) = item, t.isEmpty {
1197 continue
1198 } else {
1199 out.append(item)
1200 }
1201 }
1202 return out
1203 }
1204
1205 /// `org-element-normalize-contents`: the common indentation of the lines taken away.
1206 static func normalizeIndentation(_ items: [Inline], ignoreFirst: Bool) -> [Inline] {
1207 var minimum = Int.max
1208 var zero = false
1209 func scan(_ items: [Inline], _ firstFlag: inout Bool) {
1210 for item in items {
1211 if zero { return }
1212 if firstFlag {
1213 firstFlag = false
1214 guard case .text(let t) = item, let m = t.firstMatch(of: /^([ \t]+)([^ \t\n]|\n|$)/) else { zero = true; return }
1215 if m.2 != "\n" { minimum = min(minimum, width(m.1)) }
1216 }
1217 switch item {
1218 case .text(let t):
1219 // Every line start, a blank line's next line included.
1220 var rest = t[...]
1221 while let newline = rest.firstIndex(of: "\n") {
1222 let after = rest[rest.index(after: newline)...]
1223 let indent = after.prefix { $0 == " " || $0 == "\t" }
1224 let next = after.dropFirst(indent.count).first
1225 if indent.isEmpty {
1226 if next != nil, next != "\n" { zero = true; return }
1227 } else if next != "\n" {
1228 minimum = min(minimum, width(indent))
1229 }
1230 rest = after
1231 }
1232 case .object(let node, let children):
1233 if node.kind == .lineBreak {
1234 firstFlag = true
1235 } else if [.bold, .italic, .underline, .strikeThrough, .link, .linkDescription, .superscript, .subscript].contains(node.kind) {
1236 scan(children, &firstFlag)
1237 }
1238 }
1239 }
1240 }
1241 var first = !ignoreFirst
1242 scan(items, &first)
1243 guard !zero, minimum != Int.max, minimum > 0 else { return items }
1244 func strip(_ items: [Inline], _ firstFlag: inout Bool) -> [Inline] {
1245 items.map { item in
1246 switch item {
1247 case .text(var t):
1248 if firstFlag {
1249 firstFlag = false
1250 t = dedent(t, atStart: true, by: minimum)
1251 } else {
1252 t = dedent(t, atStart: false, by: minimum)
1253 }
1254 return .text(t)
1255 case .object(let node, let children):
1256 if firstFlag { firstFlag = false }
1257 if node.kind == .lineBreak { firstFlag = true; return item }
1258 var flag = false
1259 return .object(node, strip(children, &flag))
1260 }
1261 }
1262 }
1263 var flag = !ignoreFirst
1264 return strip(items, &flag)
1265 }
1266
1267 static func width(_ s: Substring) -> Int { s.reduce(0) { $0 + ($1 == "\t" ? 8 : 1) } }
1268
1269 /// Indentation after each newline (and at the start) less `by` columns; blank lines lose theirs.
1270 static func dedent(_ t: String, atStart: Bool, by: Int) -> String {
1271 var lines = t.components(separatedBy: "\n")
1272 for i in lines.indices where i > 0 || atStart {
1273 let indent = lines[i].prefix { $0 == " " || $0 == "\t" }
1274 guard !indent.isEmpty else { continue }
1275 let rest = lines[i].dropFirst(indent.count)
1276 if rest.isEmpty && i < lines.count - 1 {
1277 lines[i] = ""
1278 } else if rest.isEmpty {
1279 lines[i] = String(repeating: " ", count: max(0, width(indent) - by))
1280 } else {
1281 lines[i] = String(repeating: " ", count: max(0, width(indent) - by)) + rest
1282 }
1283 }
1284 return lines.joined(separator: "\n")
1285 }
1286
1287 /// One line of Org text transcoded, for keywords and captions.
1288 func inlineString(_ text: String) throws -> String {
1289 let tree = OrgParser.parse(text, defaults: settings)
1290 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1291 let saved = exportSource
1292 exportSource = ExportSource(tree: tree, text: text)
1293 defer { exportSource = saved }
1294 return Self.trim(try transcode(try inlineItems(paragraph)))
1295 }
1296
1297 /// `node`'s contents transcoded, as a heading's title is.
1298 private func inline(_ node: SyntaxNode, sectionTitle: Bool) throws -> String {
1299 let saved = inTitle
1300 inTitle = sectionTitle
1301 defer { inTitle = saved }
1302 return try transcode(try inlineItems(node))
1303 }
1304
1305 private var inTitle = false
1306 /// Whether text is a link's description, where Org finds no plain links.
1307 private var inDescription = false
1308
1309 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
1310 /// objects that export nothing taking their blanks with them unless they are needed.
1311 func transcode(_ items: [Inline]) throws -> String {
1312 if !inDescription { try refusePlainLinksIntoObjects(items) }
1313 var out = ""
1314 var index = 0
1315 var dropBlanks = false
1316 // An object's post-blank, which Emacs writes as spaces.
1317 var afterObject = false
1318 while index < items.count {
1319 let item = items[index]
1320 switch item {
1321 case .text(var t):
1322 if dropBlanks {
1323 t = String(t.drop { $0 == " " || $0 == "\t" })
1324 } else if afterObject {
1325 let blanks = t.prefix { $0 == " " || $0 == "\t" }
1326 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1327 }
1328 dropBlanks = false
1329 afterObject = false
1330 out += try plainTextAndLinks(t)
1331 index += 1
1332 case .object(let node, let children):
1333 dropBlanks = false
1334 afterObject = true
1335 if let math = mathValue(node) {
1336 var values = [math]
1337 var next = index + 1
1338 while next < items.count, case .object(let n, _) = items[next], let v = mathValue(n) {
1339 values.append(v)
1340 next += 1
1341 }
1342 let joined = Self.trim(values.joined(separator: " "))
1343 if !joined.isEmpty { out += "\\(\(joined)\\)" }
1344 index = next
1345 continue
1346 }
1347 if var result = try object(node, children) {
1348 // `org-timestamp-translate` keeps the blanks after the timestamp.
1349 if node.kind == .timestamp, index + 1 < items.count, case .text(let t) = items[index + 1] {
1350 result = result.dropLast() + String(repeating: " ", count: t.prefix { $0 == " " || $0 == "\t" }.count) + "}"
1351 }
1352 out += result
1353 } else {
1354 // `org-export--keep-spaces`: blanks after a dropped object stay only
1355 // between text that has none.
1356 let previousBlank: Bool
1357 if index == 0 {
1358 previousBlank = true
1359 } else if case .text(let t) = items[index - 1] {
1360 previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1361 } else {
1362 previousBlank = false
1363 }
1364 dropBlanks = previousBlank
1365 }
1366 index += 1
1367 }
1368 }
1369 return out
1370 }
1371
1372 /// The LaTeX inside `\(…\)` for an object a math block takes, nil for others.
1373 private func mathValue(_ node: SyntaxNode) -> String? {
1374 switch node.kind {
1375 case .entity:
1376 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1377 guard let (latex, math) = OrgEntities.latex[name], math else { return nil }
1378 return latex
1379 case .latexFragment:
1380 guard options.tex else { return nil }
1381 let value = node.text
1382 if value.hasPrefix("\\(") { return String(value.dropFirst(2).dropLast(2)) }
1383 if value.hasPrefix("$"), !value.hasPrefix("$$") { return String(value.dropFirst().dropLast()) }
1384 return nil
1385 default:
1386 return nil
1387 }
1388 }
1389
1390 private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1391 switch node.kind {
1392 case .bold: return "\\textbf{\(try transcode(children))}"
1393 case .italic: return "\\emph{\(try transcode(children))}"
1394 case .underline: return inTitle ? "\\underline{\(try transcode(children))}" : "\\uline{\(try transcode(children))}"
1395 case .strikeThrough: return "\\sout{\(try transcode(children))}"
1396 case .verbatim, .code:
1397 return Self.texttt(String(node.text.dropFirst().dropLast()))
1398 case .link: return try link(node, children)
1399 case .linkDescription: return try transcode(children)
1400 case .timestamp: return try timestamp(node.text)
1401 case .footnoteReference: return try footnote(node)
1402 case .entity:
1403 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1404 guard let (latex, _) = OrgEntities.latex[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1405 return latex
1406 case .superscript: return "\\textsuperscript{\(try transcode(children))}"
1407 case .subscript: return "\\textsubscript{\(try transcode(children))}"
1408 case .lineBreak: return "\\\\\n"
1409 case .latexFragment: return options.tex ? node.text : nil
1410 case .statisticsCookie: return node.text.replacingOccurrences(of: "%", with: "\\%")
1411 case .exportSnippet:
1412 let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1413 guard backend == "latex" else { return nil }
1414 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1415 case .target:
1416 let name = String(node.text.dropFirst(2).dropLast(2))
1417 return "\\label{\(reference("target:" + name))}"
1418 case .macro:
1419 guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1420 return try value.map(inlineString)
1421 default:
1422 throw Unsupported(reason: "\(node.kind)")
1423 }
1424 }
1425
1426 // MARK: Plain text
1427
1428 /// `org-latex-plain-text`.
1429 func plainText(_ text: String) -> String {
1430 let special = options.specialStrings
1431 var out = ""
1432 let chars = Array(text)
1433 var i = 0
1434 while i < chars.count {
1435 let c = chars[i]
1436 switch c {
1437 case "%", "$", "#", "&", "{", "}", "_":
1438 out += "\\" + String(c)
1439 case "~": out += "\\textasciitilde{}"
1440 case "^": out += "\\^{}"
1441 case "\\":
1442 if special {
1443 if i + 1 < chars.count {
1444 if chars[i + 1] == "-" {
1445 out += "\\"
1446 } else {
1447 out += "$\\backslash$" + String(chars[i + 1])
1448 i += 1
1449 }
1450 } else {
1451 out += "$\\backslash$"
1452 }
1453 } else {
1454 out += "$\\backslash$"
1455 }
1456 default:
1457 out.append(c)
1458 }
1459 i += 1
1460 }
1461 out = Self.texLogos(out)
1462 if special { out = out.replacingOccurrences(of: "...", with: "\\ldots{}") }
1463 out = out.replacing(#/(?m)^(\s*)\[/#) { $0.1 + "{[}" }
1464 if inVerse {
1465 out = out.replacing(#/(?:[ \t]*\\\\)?[ \t]*\n/#, with: "\\\\\n")
1466 out = out.replacing(#/(\\\\\n)(?:(?m:^)[ \t]*\\\\\n)+/#, with: "\n\n")
1467 out = out.replacing(#/(?m)^[ \t]+/#) { "\\hspace*{\($0.output.count)\\fontdimen2\\font}" }
1468 }
1469 return out
1470 }
1471
1472 /// `LaTeX` and `TeX` as words, as their commands.
1473 static func texLogos(_ s: String) -> String {
1474 guard s.contains("TeX") else { return s }
1475 let chars = Array(s)
1476 var out = ""
1477 var i = 0
1478 // Word constituents in Org's syntax table, the apostrophe among them.
1479 func isWord(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "'" }
1480 outer: while i < chars.count {
1481 if i == 0 || !isWord(chars[i - 1]) {
1482 for word in ["LaTeX", "TeX"] {
1483 let w = Array(word)
1484 if i + w.count <= chars.count, Array(chars[i..<(i + w.count)]) == w, i + w.count == chars.count || !isWord(chars[i + w.count]) {
1485 out += "\\" + word + "{}"
1486 i += w.count
1487 continue outer
1488 }
1489 }
1490 }
1491 out.append(chars[i])
1492 i += 1
1493 }
1494 return out
1495 }
1496
1497 // MARK: Timestamps
1498
1499 /// `org-latex-timestamp`: `org-element-timestamp-interpreter`'s text in `\textit`, with the
1500 /// blanks after the timestamp.
1501 private func timestamp(_ text: String) throws -> String? {
1502 guard let stamp = Timestamp.parse(text) else { throw Unsupported(reason: "Timestamp \(text)") }
1503 let open = stamp.active ? "<" : "["
1504 let close = stamp.active ? ">" : "]"
1505 func date(_ p: Timestamp.Point, time: Bool) -> String {
1506 var components = DateComponents(year: p.year, month: p.month, day: p.day)
1507 components.calendar = Calendar(identifier: .gregorian)
1508 let weekday = components.calendar!.date(from: components).map { components.calendar!.component(.weekday, from: $0) } ?? 1
1509 let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][weekday - 1]
1510 var s = String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name
1511 if time, let h = p.hour, let m = p.minute { s += String(format: " %02d:%02d", h, m) }
1512 return s
1513 }
1514 var suffix = ""
1515 if let r = stamp.repeater {
1516 suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)"
1517 if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" }
1518 }
1519 if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" }
1520 var out = open + date(stamp.start, time: true)
1521 let dateRange = text.contains(">--<") || text.contains("]--[")
1522 if let end = stamp.end {
1523 if dateRange {
1524 out += suffix + close + "--" + open + date(end, time: true) + suffix + close
1525 } else {
1526 if let h = end.hour, let m = end.minute, h != stamp.start.hour || m != stamp.start.minute {
1527 out += String(format: "-%02d:%02d", h, m)
1528 }
1529 out += suffix + close
1530 }
1531 } else {
1532 out += suffix + close
1533 }
1534 guard options.items["<"] ?? "t" == "t" else { return nil }
1535 return "\\textit{\(plainText(out))}"
1536 }
1537
1538 // MARK: Links
1539
1540 private func linkTarget(_ node: SyntaxNode) -> (type: String, path: String) {
1541 var raw = node.linkPath ?? node.text
1542 if node.tokens.first(where: { $0.kind == .linkPath }) == nil, raw.hasPrefix("<"), raw.hasSuffix(">") {
1543 raw = String(raw.dropFirst().dropLast())
1544 }
1545 if raw.hasPrefix("#") { return ("custom-id", String(raw.dropFirst())) }
1546 if raw.hasPrefix("(") && raw.hasSuffix(")") { return ("coderef", String(raw.dropFirst().dropLast())) }
1547 if raw.hasPrefix("./") || raw.hasPrefix("../") || raw.hasPrefix("/") || raw.hasPrefix("~") { return ("file", raw) }
1548 if let m = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/), Self.linkTypes.contains(m.1.lowercased()) {
1549 let type = m.1.lowercased()
1550 var path = String(m.2)
1551 if type == "file", path.hasPrefix("//") == false, let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1552 return (type, path)
1553 }
1554 return ("fuzzy", raw)
1555 }
1556
1557 /// `org-link-parameters` under `emacs -Q` with ox-latex loaded.
1558 static let linkTypes: Set<String> = ["attachment", "id", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1559
1560 private func isImage(_ node: SyntaxNode) -> Bool {
1561 guard node.kind == .link, node.firstChild(.linkDescription) == nil else { return false }
1562 let (type, path) = linkTarget(node)
1563 guard type == "file" || type == "https" else { return false }
1564 let ext = (path as NSString).pathExtension.lowercased()
1565 let image = type == "file" ? ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"] : ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"]
1566 return image.contains(ext) && path.lowercased().hasSuffix("." + ext)
1567 }
1568
1569 /// The image link of a paragraph holding only it and blanks.
1570 private func soleImage(_ items: [Inline]) -> SyntaxNode? {
1571 var image: SyntaxNode?
1572 for item in items {
1573 switch item {
1574 case .text(let t): if t.contains(where: { !$0.isWhitespace }) { return nil }
1575 case .object(let node, _):
1576 guard image == nil, isImage(node) else { return nil }
1577 image = node
1578 }
1579 }
1580 return image
1581 }
1582
1583 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1584 let (type, path) = linkTarget(node)
1585 let saved = inDescription
1586 inDescription = true
1587 defer { inDescription = saved }
1588 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1589 inDescription = saved
1590 if description == "" { description = nil }
1591 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1592 throw Unsupported(reason: "Links in link descriptions")
1593 }
1594 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil {
1595 throw Unsupported(reason: "Images as link descriptions")
1596 }
1597 if isImage(node) { return try inlineImage(node, affiliated: currentAffiliated ?? Affiliated(), alone: false) }
1598 switch type {
1599 case "custom-id", "fuzzy", "id":
1600 let label: String
1601 let numberedHeading: Bool
1602 var title: String?
1603 if type == "fuzzy", !path.hasPrefix("*"), let found = target(path).map({ reference("target:" + $0) }) ?? namedElement(path) {
1604 return description.map { "\\hyperref[\(found)]{\($0)}" } ?? "\\ref{\(found)}"
1605 }
1606 guard let heading = try resolveHeading(type: type, path: path) else {
1607 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1608 }
1609 label = "sec:" + reference("heading@\(heading.headingRange.lowerBound)")
1610 numberedHeading = numbered && (num.map { heading.level + levelOffset <= $0 } ?? true)
1611 if description == nil, numberedHeading { return "\\ref{\(label)}" }
1612 if description == nil {
1613 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1614 title = try node?.firstChild(.title).map { try Self.trim(inline($0, sectionTitle: false)) } ?? ""
1615 }
1616 return "\\hyperref[\(label)]{\(description ?? title ?? "")}"
1617 case "coderef":
1618 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1619 // `org-export-get-coderef-format` on the transcoded description, then `format`.
1620 var format = description ?? "%s"
1621 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1622 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1623 case "file":
1624 let protected = Self.protect(try fileURI(path))
1625 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1626 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
1627 let protected = Self.protect(type + ":" + path)
1628 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1629 default:
1630 throw Unsupported(reason: "\(type): links")
1631 }
1632 }
1633
1634 private func fileURI(_ path: String) throws -> String {
1635 if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") }
1636 return path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1637 }
1638
1639 /// Org matches `org-link-plain-re` on the source, so a plain link the parser leaves as text
1640 /// can run on into what the parser reads as an object after it, such as `shell:a_b`.
1641 private func refusePlainLinksIntoObjects(_ items: [Inline]) throws {
1642 var raw = ""
1643 var textRuns: [(start: Int, end: Int)] = []
1644 for item in items {
1645 let start = (raw as NSString).length
1646 switch item {
1647 case .text(let t):
1648 raw += t
1649 textRuns.append((start, (raw as NSString).length))
1650 case .object(let node, _):
1651 raw += node.text
1652 }
1653 }
1654 guard textRuns.count < items.count else { return }
1655 for m in ASCIIRenderer.plainLink.matches(in: raw, range: NSRange(location: 0, length: (raw as NSString).length)) {
1656 if let text = textRuns.first(where: { $0.start <= m.range.location && m.range.location < $0.end }), NSMaxRange(m.range) > text.end {
1657 throw Unsupported(reason: "Plain links running into other objects")
1658 }
1659 }
1660 }
1661
1662 /// Text with the plain links the parser leaves in it, `shell:ls` and the like, written as Emacs does.
1663 private func plainTextAndLinks(_ t: String) throws -> String {
1664 guard !inDescription else { return plainText(t) }
1665 let ns = t as NSString
1666 var out = ""
1667 var last = 0
1668 for m in ASCIIRenderer.plainLink.matches(in: t, range: NSRange(location: 0, length: ns.length)) {
1669 let type = ns.substring(with: m.range(at: 1))
1670 var path = ns.substring(with: NSRange(location: NSMaxRange(m.range(at: 1)) + 1, length: NSMaxRange(m.range) - NSMaxRange(m.range(at: 1)) - 1))
1671 var before = ns.substring(with: NSRange(location: last, length: m.range.location - last))
1672 if last > 0 {
1673 // The previous link's post-blank, which Emacs writes as spaces.
1674 let blanks = before.prefix { $0 == " " || $0 == "\t" }
1675 before = String(repeating: " ", count: blanks.count) + before.dropFirst(blanks.count)
1676 }
1677 out += plainText(before)
1678 if type.lowercased() == "file", !path.hasPrefix("//"), let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1679 let ext = (path as NSString).pathExtension.lowercased()
1680 switch type.lowercased() {
1681 case "file":
1682 if ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
1683 out += "\\url{\(Self.protect(try fileURI(path)))}"
1684 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
1685 if ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
1686 out += "\\url{\(Self.protect(type + ":" + path))}"
1687 default:
1688 throw Unsupported(reason: "Plain links of type \(type)")
1689 }
1690 last = NSMaxRange(m.range)
1691 }
1692 guard last > 0 else { return plainText(t) }
1693 var rest = ns.substring(from: last)
1694 let blanks = rest.prefix { $0 == " " || $0 == "\t" }
1695 rest = String(repeating: " ", count: blanks.count) + rest.dropFirst(blanks.count)
1696 return out + plainText(rest)
1697 }
1698
1699 /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them.
1700 static func words(_ s: String) -> [String] {
1701 s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init)
1702 }
1703
1704 /// The `<<target>>` a fuzzy link names.
1705 private func target(_ path: String) -> String? {
1706 let search = Self.words(path)
1707 return tree.root.descendants().first { $0.kind == .target && Self.words(String($0.text.dropFirst(2).dropLast(2))) == search && !Self.excluded($0, by: self) }
1708 .map { String($0.text.dropFirst(2).dropLast(2)) }
1709 }
1710
1711 /// The label of the element whose `#+NAME` a fuzzy link names, as the element writes it.
1712 private func namedElement(_ path: String) -> String? {
1713 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1714 for node in tree.root.descendants() where node.kind == .affiliatedKeyword && !Self.excluded(node, by: self) {
1715 guard let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
1716 let name = String(m.1)
1717 let words = name.split(whereSeparator: \.isWhitespace).map(String.init)
1718 guard words == search || words == search.map({ $0.uppercased() }), let parent = node.parent else { continue }
1719 let siblings = parent.children
1720 guard let index = siblings.firstIndex(where: { $0.range == node.range }) else { continue }
1721 let keywords = siblings[index...].prefix { $0.kind == .affiliatedKeyword }
1722 guard let element = siblings[index...].first(where: { $0.kind != .affiliatedKeyword }) else { continue }
1723 let captioned = keywords.contains { $0.text.firstMatch(of: /^[ \t]*#\+(?i:caption)/) != nil }
1724 let prefix: String
1725 switch element.kind {
1726 case .table: prefix = "tab:"
1727 case .block where blockType(element) == "src": prefix = "lst:"
1728 case .paragraph where captioned: prefix = "fig:"
1729 default: prefix = ""
1730 }
1731 return prefix + reference("name:" + name)
1732 }
1733 return nil
1734 }
1735
1736 /// The headings the export writes.
1737 private lazy var exportedHeadings: [HeadingInfo] = {
1738 let starts = Set(tree.root.descendants().filter { node in
1739 node.kind == .heading && HTMLRenderer.sectionExport(node, options: options, selected: selected) != .nothing
1740 && !(node.parent?.parent.map { Self.excluded($0, by: self) } ?? false)
1741 }.map(\.range.lowerBound))
1742 return model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1743 }()
1744
1745 /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1746 private func resolveHeading(type: String, path: String) throws -> HeadingInfo? {
1747 let headings = exportedHeadings
1748 switch type {
1749 case "custom-id":
1750 return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1751 case "id":
1752 return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1753 default:
1754 let search = Self.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1755 return headings.first { heading in
1756 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1757 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1758 return Self.words(raw) == search
1759 }
1760 }
1761 }
1762
1763 /// `org-latex--inline-image`.
1764 private func inlineImage(_ node: SyntaxNode, affiliated: Affiliated, alone: Bool) throws -> String {
1765 let (type, path) = linkTarget(node)
1766 if type != "file" { throw Unsupported(reason: "Remote images") }
1767 if path.hasPrefix("~") || path.hasPrefix("/") { throw Unsupported(reason: "Images with absolute paths") }
1768 let ext = (path as NSString).pathExtension.lowercased()
1769 let caption = try captionLabel(affiliated, type: "figure", prefix: !affiliated.caption.isEmpty ? "fig:" : "")
1770 enum Float: Equatable { case none, nonfloat, figure, wrap, sideways, multicolumn, env(String) }
1771 var float: Float
1772 let attrFloat = affiliated.attribute("float")
1773 if !alone {
1774 float = .none
1775 } else {
1776 switch attrFloat {
1777 case .some(.some("wrap")): float = .wrap
1778 case .some(.some("sideways")): float = .sideways
1779 case .some(.some("multicolumn")): float = .multicolumn
1780 case .some(.some("t")): float = .figure
1781 case .some(nil): float = .nonfloat
1782 case .some(.some(let f)): float = .env(f)
1783 case .none: float = !affiliated.caption.isEmpty || affiliated.value("caption") != nil ? .figure : .nonfloat
1784 }
1785 }
1786 let placement: String
1787 if let p = affiliated.value("placement") {
1788 placement = p
1789 } else if float == .wrap {
1790 placement = "{l}{0.5\\textwidth}"
1791 } else if float == .figure {
1792 placement = "[htbp]"
1793 } else {
1794 placement = ""
1795 }
1796 let center = affiliated.has("center") ? affiliated.value("center") != nil : true
1797 let scale = float == .wrap ? "" : affiliated.value("scale") ?? ""
1798 let width: String = !scale.isEmpty ? "" : affiliated.value("width") ?? (affiliated.value("height") != nil ? "" : float == .wrap ? "0.48\\textwidth" : ".9\\linewidth")
1799 let height: String = !scale.isEmpty ? "" : affiliated.value("height") ?? ""
1800 var options = affiliated.value("options") ?? ""
1801 if let m = options.wholeMatch(of: /\[(.*)\]/) { options = String(m.1) }
1802 if ext == "tikz" || ext == "pgf" { throw Unsupported(reason: "TikZ images") }
1803 if affiliated.value("comment-include") != nil { throw Unsupported(reason: ":comment-include") }
1804 if !scale.isEmpty {
1805 options += ",scale=" + scale
1806 } else {
1807 if !width.isEmpty { options += ",width=" + width }
1808 if !height.isEmpty { options += ",height=" + height }
1809 }
1810 let optionString = options.isEmpty ? "" : options.hasPrefix(",") ? "[\(options.dropFirst())]" : "[\(options)]"
1811 var imagePath = path
1812 if ext == "svg", imagePath.contains(where: { !$0.isASCII }) { imagePath = "\\detokenize{\(imagePath)}" }
1813 var code = "\\includegraphics\(optionString){\(imagePath)}"
1814 if ext == "svg" {
1815 code = "\\includesvg" + code.dropFirst("\\includegraphics".count)
1816 code = code.replacingOccurrences(of: ".svg}", with: "}")
1817 }
1818 switch float {
1819 case .env(let env):
1820 return "\\begin{\(env)}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{\(env)}"
1821 case .wrap:
1822 return "\\begin{wrapfigure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{wrapfigure}"
1823 case .sideways:
1824 return "\\begin{sidewaysfigure}\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{sidewaysfigure}"
1825 case .multicolumn:
1826 return "\\begin{figure*}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure*}"
1827 case .figure:
1828 return "\\begin{figure}\(placement)\n\(center ? "\\centering" : "")\n\(code)\n\(caption)\\end{figure}"
1829 case .none, .nonfloat:
1830 if center { return "\\begin{center}\n\(code)\n\(caption)\\end{center}" }
1831 return code
1832 }
1833 }
1834
1835 // MARK: Footnotes
1836
1837 private var footnoteReferences: [String: Int] = [:]
1838 private var footnotesSeen: Set<String> = []
1839 private var definitions: [String: String] = [:]
1840 private var anonymous = 0
1841
1842 /// Footnote definitions, and how many references each label has.
1843 private func countFootnotes() throws {
1844 for node in tree.root.descendants() {
1845 if node.kind == .footnoteDefinition, let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
1846 // A definition goes on to the next one, a heading or two blank lines.
1847 if let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count {
1848 let next = parent.children[index + 1]
1849 if next.kind != .footnoteDefinition, next.kind != .section, blankLines(from: node.range.lowerBound, to: next.range.lowerBound) < 2 {
1850 throw Unsupported(reason: "Footnote definitions of several paragraphs")
1851 }
1852 }
1853 definitions[String(m.1)] = String(node.text[m.range.upperBound...])
1854 }
1855 if node.kind == .footnoteReference, let m = node.text.firstMatch(of: /^\[fn:([^:\]]+)/) {
1856 if node.parent.map({ Self.excluded($0, by: self) }) == true { continue }
1857 footnoteReferences[String(m.1), default: 0] += 1
1858 }
1859 }
1860 }
1861
1862 /// Whether `node` is under a section the export leaves out.
1863 private static func excluded(_ node: SyntaxNode, by renderer: LaTeXRenderer) -> Bool {
1864 var current: SyntaxNode? = node
1865 while let n = current {
1866 if n.kind == .section, let heading = n.firstChild(.heading),
1867 HTMLRenderer.sectionExport(heading, options: renderer.options, selected: renderer.selected) != .all { return true }
1868 current = n.parent
1869 }
1870 return false
1871 }
1872
1873 /// `org-latex-footnote-reference`.
1874 private func footnote(_ node: SyntaxNode) throws -> String {
1875 guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1876 let label = String(m.1)
1877 if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1878 var separator = ""
1879 if let previous = previousSibling(node), previous.kind == .footnoteReference { separator = "\\textsuperscript{,}\\," }
1880 if let inline = m.2 {
1881 if !label.isEmpty {
1882 if footnotesSeen.contains(label) { return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}" }
1883 footnotesSeen.insert(label)
1884 }
1885 inFootnote = true
1886 defer { inFootnote = false }
1887 let content = try inlineString(String(inline))
1888 let labelText = !label.isEmpty && (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1889 return separator + "\\footnote{\(content)\(labelText)}"
1890 }
1891 guard !label.isEmpty, let definition = definitions[label] else { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1892 if footnotesSeen.contains(label) {
1893 return separator + "\\textsuperscript{\\ref{\(reference("fn:" + label))}}"
1894 }
1895 footnotesSeen.insert(label)
1896 inFootnote = true
1897 defer { inFootnote = false }
1898 let content = Self.trim(try footnoteBody(definition))
1899 let labelText = (footnoteReferences[label] ?? 0) > 1 ? "\\label{\(reference("fn:" + label))}" : ""
1900 return separator + "\\footnote{\(content)\(labelText)}"
1901 }
1902
1903 private var inFootnote = false
1904
1905 /// A definition's text transcoded, its first paragraph's first line left as it is.
1906 private func footnoteBody(_ text: String) throws -> String {
1907 let tree = OrgParser.parse(text, defaults: settings)
1908 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1909 if nodes.count == 1, nodes[0].kind == .paragraph {
1910 return try paragraph(nodes[0], affiliated: Affiliated(), ignoreFirst: true)
1911 }
1912 return try blocks(text)
1913 }
1914
1915 /// The object before `node` in its parent, nil after text. Spaces and tabs after an object
1916 /// are its post-blank, not text.
1917 private func previousSibling(_ node: SyntaxNode) -> SyntaxNode? {
1918 guard let parent = node.parent else { return nil }
1919 var previous: SyntaxNode.Element?
1920 for element in parent.elements {
1921 if case .node(let n) = element, n.range == node.range {
1922 if case .node(let p)? = previous { return p }
1923 return nil
1924 }
1925 if case .token(let t) = element, !t.text.isEmpty, t.text.allSatisfy({ $0 == " " || $0 == "\t" }), case .node? = previous { continue }
1926 previous = element
1927 }
1928 return nil
1929 }
1930}