Sources/OrgCore/Export/LaTeXExport.swift

22ff42f0ad29d59255e2ac93e0b3a28f66fca672
orgstar/Sources/OrgCore/Export/LaTeXExport.swift

1846 lines · 97992 bytes

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