Sources/OrgCore/Export/LaTeXExport.swift

7624d81df5f4d9060bfc1c6dc3e9d71b075e2190
orgstar/Sources/OrgCore/Export/LaTeXExport.swift

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