Sources/OrgCore/Export/LaTeXExport.swift

586bad784d2cb2ad1bb43da0e63f0819913ed1dc
orgstar/Sources/OrgCore/Export/LaTeXExport.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form