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