Sources/OrgCore/Export/ODTExport.swift

1535 lines · 85929 bytes

85 symbols in this file
   1import Foundation
   2import ImageIO
   3
   4/// OpenDocument text export written from the parse tree, in the shape ox-odt (Org 9.8.7) gives
   5/// `content.xml` under `emacs -Q`: LaTeX left verbatim, as without a MathML converter, and source
   6/// blocks without colors. `styles.xml` is a reduced template holding ox-odt's style names.
   7public enum ODTExport {
   8    public struct Failure: LocalizedError, Equatable {
   9        public let message: String
  10        public var errorDescription: String? { message }
  11    }
  12
  13    /// The `.odt` file: `content.xml`, `styles.xml`, `meta.xml`, the images and the manifest,
  14    /// with `mimetype` first and stored. `path` is the file's, for `#+INCLUDE`, macros and
  15    /// images; `author` is used without `#+AUTHOR` (`user-full-name`); `language` is
  16    /// `org-export-default-language`. Throws what makes ox-odt stop: broken links and missing
  17    /// images among them.
  18    public static func document(
  19        _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
  20        author: String? = nil, language: String = "en"
  21    ) throws -> Data {
  22        var zip = ZipWriter()
  23        for part in try parts(text, settings: settings, path: path, now: now, author: author, language: language) {
  24            zip.add(part.name, data: part.data)
  25        }
  26        return zip.data()
  27    }
  28
  29    /// The image files `text` embeds, for the sandbox to reach before exporting.
  30    /// Images in `#+INCLUDE`d files and images shown as a link's description count.
  31    public static func imageFiles(_ text: String, settings: OrgSettings = .default, path: String) -> [String] {
  32        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
  33        let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, setup: settings.setupKeywords)
  34        return OrgParser.parse(text, defaults: settings).root.descendants().compactMap { node in
  35            guard node.kind == .link else { return nil }
  36            let file: String?
  37            if let description = node.firstChild(.linkDescription) {
  38                file = ODTRenderer.describedImage(description)
  39            } else {
  40                file = ODTRenderer.linkPath(node).flatMap(ODTRenderer.filePath).flatMap { ODTRenderer.isImage($0) ? $0 : nil }
  41            }
  42            return file.map { ODTRenderer.expand($0, directory: directory).path }
  43        }
  44    }
  45
  46    static func parts(
  47        _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(),
  48        author: String? = nil, language: String = "en"
  49    ) throws -> [(name: String, data: Data)] {
  50        let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
  51        let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
  52        let options = ExportOptions.parse(settings.setupKeywords + text)
  53        let meta = HTMLExport.metadata(text, settings: settings)
  54        let keywords = Self.keywords(text, settings: settings)
  55        let renderer = ODTRenderer(settings: settings, options: options, directory: directory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
  56        try Self.read(settings.setupKeywords + text, into: renderer)
  57        renderer.language = meta.language ?? language
  58
  59        // The title isn't part of the document Org processes citations in: they drop out.
  60        renderer.inTitle = true
  61        let title = meta.title.map(renderer.inlineString) ?? ""
  62        let subtitle = keywords["SUBTITLE"].map(renderer.inlineString) ?? ""
  63        let authorName = (meta.author ?? author).flatMap { $0.isEmpty ? nil : $0 }.map(renderer.inlineString)
  64        renderer.inTitle = false
  65        renderer.author = authorName
  66        renderer.dated = !(meta.date ?? "").isEmpty
  67        renderer.citations = CiteProcessor(text: text, directory: directory)
  68        let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
  69        let date = options.date ? meta.date.flatMap { $0.isEmpty ? nil : renderer.inlineString($0) } : nil
  70        if let failure = renderer.failure { throw failure }
  71
  72        var preamble = ""
  73        if options.title, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  74            preamble += "\n<text:p text:style-name=\"OrgTitle\">\n<text:title>\(title)</text:title></text:p>\n"
  75            preamble += "\n<text:p text:style-name=\"OrgTitle\"/>\n"
  76            if !subtitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  77                preamble += "<text:p text:style-name=\"OrgSubtitle\">\n<text:user-defined style:data-style-name=\"N0\" text:name=\"subtitle\">\n\(subtitle)</text:user-defined>\n\n</text:p>\n"
  78                preamble += "<text:p text:style-name=\"OrgSubtitle\"/>\n"
  79            }
  80        }
  81        if options.author, let authorName {
  82            preamble += "\n<text:p text:style-name=\"OrgSubtitle\"><text:initial-creator>\(authorName)</text:initial-creator></text:p>"
  83            preamble += "\n<text:p text:style-name=\"OrgSubtitle\"/>"
  84        }
  85        if let date { preamble += "\n<text:p text:style-name=\"OrgSubtitle\">\(date)</text:p><text:p text:style-name=\"OrgSubtitle\"/>" }
  86        let contents = ODTTemplate.content(automaticStyles: renderer.automaticStyles(), body: preamble + renderer.tableOfContents() + body)
  87
  88        let stamp = meta.date.flatMap(Timestamp.parse).map { stamp -> String in
  89            let p = stamp.start
  90            return String(format: "%04d-%02d-%02dT%02d:%02d:00", p.year, p.month, p.day, p.hour ?? 0, p.minute ?? 0)
  91        } ?? Self.isoDate(now)
  92        let metaXML = ODTTemplate.meta(
  93            author: authorName.map(ODTRenderer.stripped) ?? "", date: options.date ? stamp : nil, keywords: keywords["KEYWORDS"] ?? "",
  94            description: keywords["DESCRIPTION"] ?? "", title: ODTRenderer.stripped(title), subtitle: ODTRenderer.stripped(subtitle)
  95        )
  96
  97        var parts: [(name: String, data: Data)] = [("mimetype", Data(ODTTemplate.mimetype.utf8))]
  98        parts.append(("content.xml", Data(contents.utf8)))
  99        parts.append(("styles.xml", Data(ODTTemplate.styles(numbered: min(renderer.numbered ?? 0, 10)).utf8)))
 100        parts.append(("meta.xml", Data(metaXML.utf8)))
 101        parts += renderer.images.map { ($0.name, $0.data) }
 102        parts.append(("META-INF/manifest.xml", Data(ODTTemplate.manifest(images: renderer.images.map(\.name)).utf8)))
 103        return parts
 104    }
 105
 106    /// The `#+OPTIONS` items ox-odt reads that `ExportOptions` doesn't, or reads differently:
 107    /// `num` to any depth, `\\n`, `f`, `|`, `e` and `d` honored; other items at a value other
 108    /// than their default stop the export.
 109    static func read(_ text: String, into renderer: ODTRenderer) throws {
 110        var items: [String: String] = [:]
 111        for line in text.matches(of: #/(?mi)^[ \t]*#\+OPTIONS:[ \t]*(.*?)[ \t]*$/#) {
 112            for item in line.1.matches(of: /(\S+?):(\S+)/) { items[String(item.1)] = String(item.2) }
 113        }
 114        let defaults = [
 115            "p": "nil", "broken-links": "nil", "c": "nil", "prop": "nil", ":": "t", "*": "t", "stat": "t",
 116            "tasks": "t", "<": "t", "arch": "headline", "email": "nil", "'": "nil",
 117        ]
 118        for (key, value) in items.sorted(by: { $0.key < $1.key }) {
 119            if let standard = defaults[key], value != standard {
 120                throw Failure(message: "ODT export doesn't support #+OPTIONS: \(key):\(value)")
 121            }
 122        }
 123        if let tex = items["tex"], tex != "t", tex != "nil" { throw Failure(message: "ODT export doesn't support #+OPTIONS: tex:\(tex)") }
 124        switch items["d"] {
 125        case nil: renderer.drawers = nil
 126        case "nil": renderer.drawers = false
 127        case "t": renderer.drawers = true
 128        case let value?: throw Failure(message: "ODT export doesn't support #+OPTIONS: d:\(value)")
 129        }
 130        // `org-export-numbered-headline-p`: `t` numbers every level, `N` levels to N, past `H`.
 131        switch items["num"] {
 132        case "nil": renderer.numbered = nil
 133        case let value?: renderer.numbered = Int(value) ?? Int.max
 134        case nil: renderer.numbered = Int.max
 135        }
 136        renderer.preserveBreaks = items["\\n"].map { $0 != "nil" } ?? false
 137        renderer.withFootnotes = items["f"] != "nil"
 138        renderer.withTables = items["|"] != "nil"
 139        renderer.withEntities = items["e"] != "nil"
 140    }
 141
 142    /// `#+SUBTITLE`, `#+KEYWORDS` and `#+DESCRIPTION`: lines of the same keyword joined.
 143    static func keywords(_ text: String, settings: OrgSettings) -> [String: String] {
 144        let tree = OrgParser.parse(text, defaults: settings)
 145        let own = tree.root.children.filter { $0.kind == .zerothSection }.flatMap { $0.children.filter { $0.kind == .keyword } }.map(\.text)
 146        var values: [String: String] = [:]
 147        for line in settings.setupKeywords.split(separator: "\n").map(String.init) + own {
 148            guard let m = line.firstMatch(of: /^[ \t]*#\+([A-Za-z_]+):[ \t]*(.*?)[ \t]*\n?$/) else { continue }
 149            let key = m.1.uppercased()
 150            guard ["SUBTITLE", "KEYWORDS", "DESCRIPTION"].contains(key) else { continue }
 151            values[key] = values[key].map { $0 + (key == "DESCRIPTION" ? "\n" : " ") + m.2 } ?? String(m.2)
 152        }
 153        return values
 154    }
 155
 156    static func isoDate(_ date: Date) -> String {
 157        let formatter = DateFormatter()
 158        formatter.locale = Locale(identifier: "en_US_POSIX")
 159        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
 160        return formatter.string(from: date)
 161    }
 162}
 163
 164final class ODTRenderer {
 165    let settings: OrgSettings
 166    let options: ExportOptions
 167    let directory: URL
 168    var language = "en"
 169    var citations: CiteProcessor?
 170    /// Rendering the title, where Org exports citations as nothing.
 171    var inTitle = false
 172    /// The document's author, rendered, and whether it has a date, for annotations.
 173    var author: String?
 174    var dated = false
 175    /// The first error, which stops the export as ox-odt's errors do.
 176    private(set) var failure: ODTExport.Failure?
 177    private(set) var images: [(name: String, data: Data)] = []
 178
 179    /// `num`: headings numbered to this relative level, `Int.max` for all; nil for none.
 180    var numbered: Int? = Int.max
 181    /// `\\n`, `f`, `|` and `e`.
 182    var preserveBreaks = false
 183    var withFootnotes = true
 184    var withTables = true
 185    var withEntities = true
 186    /// `d`: nil for every drawer but `LOGBOOK`, true for every drawer, false for none.
 187    var drawers: Bool?
 188
 189    init(settings: OrgSettings, options: ExportOptions, directory: URL) {
 190        self.settings = settings
 191        self.options = options
 192        self.directory = directory
 193    }
 194
 195    private func fail(_ message: String) -> String {
 196        if failure == nil { failure = ODTExport.Failure(message: message) }
 197        return ""
 198    }
 199
 200    // MARK: - Collecting
 201
 202    /// An exported heading, by its start in the document.
 203    struct Heading {
 204        var key: Int
 205        var level: Int
 206        var ancestors: [Int]
 207        var info: HeadingInfo?
 208        var node: SyntaxNode
 209        var relative = 1
 210        var number: [Int]?
 211        var lowLevel = false
 212        var reference = ""
 213    }
 214
 215    /// A captioned or named table, source block or image: its category, sequence and label.
 216    struct Label {
 217        var category: String
 218        var variable: String
 219        var sequence: String
 220        var reference: String?
 221    }
 222
 223    private var headings: [Int: Heading] = [:]
 224    private var headingOrder: [Int] = []
 225    private var targets: [(words: [String], key: Int, reference: String)] = []
 226    private var names: [(words: [String], key: Int)] = []
 227    private var labels: [Int: Label] = [:]
 228    private var enumerables: [(key: Int, category: String, ancestors: [Int])] = []
 229    private var references = 0
 230    private var selected: Set<Int>?
 231    private var documentTree: OrgTree?
 232    private var blockLocs: [String: [Int?]] = [:]
 233    /// Footnote definitions by label: the last in the document, a definition or an inline one.
 234    private var definitions: [String: (text: String, base: Int, inline: Bool)] = [:]
 235
 236    /// Where the tree being read starts in the document, so elements read from a block's or a
 237    /// footnote's contents keep their place; how deep in such contents it is.
 238    private var base = 0
 239    private var depth = 0
 240    /// Elements after a footnote definition that belong to it, by their start.
 241    private var absorbed: Set<Int> = []
 242
 243    private func newReference() -> String {
 244        references += 1
 245        return String(format: "org%07x", references &* 2_654_435_761 & 0xFFF_FFFF)
 246    }
 247
 248    private static func words(_ s: String) -> [String] { s.split(whereSeparator: \.isWhitespace).map(String.init) }
 249
 250    private func collect(_ tree: OrgTree) {
 251        let model = DocumentModel(tree: tree)
 252        var infos: [Int: HeadingInfo] = [:]
 253        for heading in model.headings { infos[heading.headingRange.lowerBound] = heading }
 254        collect(tree.root, ancestors: [], infos: infos)
 255        let top = headingOrder.compactMap { headings[$0]?.level }.min() ?? 1
 256        var counters: [Int] = []
 257        for key in headingOrder {
 258            var heading = headings[key]!
 259            heading.relative = heading.level - top + 1
 260            heading.lowLevel = heading.relative > options.headlineLevels
 261            heading.reference = newReference()
 262            let unnumbered = unnumberedValue(heading).map { $0 != "nil" } ?? false
 263            if let numbered, heading.relative <= numbered, !unnumbered {
 264                let index = heading.relative - 1
 265                if counters.count <= index { counters += Array(repeating: 0, count: index + 1 - counters.count) }
 266                counters[index] += 1
 267                for i in (index + 1)..<counters.count { counters[i] = 0 }
 268                heading.number = Array(counters.prefix(index + 1))
 269            }
 270            headings[key] = heading
 271        }
 272        // `org-odt--enumerate`: numbered within the closest numbered heading at level 2 or
 273        // above, else through the document.
 274        for (index, item) in enumerables.enumerated() {
 275            let scope = item.ancestors.reversed().first { headings[$0].map { $0.relative <= 2 && $0.number != nil } ?? false }
 276            let ordinal = enumerables[...index].filter { $0.category == item.category && (scope.map($0.ancestors.contains) ?? true) }.count
 277            let sequence = (scope.flatMap { headings[$0]?.number }.map { $0.map(String.init).joined(separator: ".") + "." } ?? "") + String(ordinal)
 278            let named = names.contains { $0.key == item.key }
 279            let variable = ["Table": "Table", "Figure": "Illustration", "Listing": "Listing"][item.category]!
 280            labels[item.key] = Label(category: item.category, variable: variable, sequence: sequence, reference: named ? newReference() : nil)
 281        }
 282    }
 283
 284    /// `UNNUMBERED` of the heading or its closest ancestor that has it.
 285    private func unnumberedValue(_ heading: Heading) -> String? {
 286        for key in [heading.key] + heading.ancestors.reversed() {
 287            if let value = headings[key]?.info?.properties.last(where: { $0.key.uppercased() == "UNNUMBERED" })?.value {
 288                return value.trimmingCharacters(in: .whitespaces)
 289            }
 290        }
 291        return nil
 292    }
 293
 294    private func collect(_ node: SyntaxNode, ancestors: [Int], infos: [Int: HeadingInfo]) {
 295        var affiliated: [String: String] = [:]
 296        for child in node.children {
 297            if child.kind == .affiliatedKeyword {
 298                if let m = child.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
 299                    affiliated[m.1.uppercased()] = String(m.2)
 300                }
 301                continue
 302            }
 303            defer { affiliated = [:] }
 304            if depth == 0, absorbed.contains(child.range.lowerBound) { continue }
 305            let key = base + child.range.lowerBound
 306            if let name = affiliated["NAME"] { names.append((Self.words(name), key)) }
 307            let captioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
 308            switch child.kind {
 309            case .section:
 310                guard let heading = child.firstChild(.heading) else { collect(child, ancestors: ancestors, infos: infos); continue }
 311                let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
 312                if export == .nothing { continue }
 313                let headingKey = base + heading.range.lowerBound
 314                let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
 315                headings[headingKey] = Heading(key: headingKey, level: level, ancestors: ancestors, info: infos[heading.range.lowerBound], node: heading)
 316                headingOrder.append(headingKey)
 317                collect(heading, ancestors: ancestors, infos: infos)
 318                if export == .all { collect(child, ancestors: ancestors + [headingKey], infos: infos) }
 319            case .heading, .footnoteDefinition:
 320                continue
 321            case .target, .radioTarget:
 322                let inner = child.kind == .target ? child.text.dropFirst(2).dropLast(2) : child.text.dropFirst(3).dropLast(3)
 323                targets.append((Self.words(inner.uppercased()), key, newReference()))
 324            case .table:
 325                guard withTables else { continue }
 326                if captioned { enumerables.append((key, "Table", ancestors)) }
 327                collect(child, ancestors: ancestors, infos: infos)
 328            case .paragraph:
 329                if captioned, soleImage(child) != nil { enumerables.append((key, "Figure", ancestors)) }
 330                collect(child, ancestors: ancestors, infos: infos)
 331            case .block:
 332                let (type, _, _, body) = Self.blockParts(child)
 333                if type == "src", captioned { enumerables.append((key, "Listing", ancestors)) }
 334                if ["src", "example", "export", "comment", "verse"].contains(type) { continue }
 335                within(body.text, base: key + body.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
 336            case .drawer, .dynamicBlock:
 337                guard let inner = inner(child) else { continue }
 338                within(inner.text, base: key + inner.offset) { tree in collect(tree.root, ancestors: ancestors, infos: [:]) }
 339            default:
 340                collect(child, ancestors: ancestors, infos: infos)
 341            }
 342        }
 343    }
 344
 345    /// A drawer's or dynamic block's contents and their offset in it; nil for a drawer `d`
 346    /// leaves out.
 347    private func inner(_ node: SyntaxNode) -> (text: String, offset: Int)? {
 348        var lines = node.text.components(separatedBy: "\n")
 349        if lines.last == "" { lines.removeLast() }
 350        guard let first = lines.first else { return nil }
 351        if node.kind == .drawer, !(drawers ?? (first.trimmingCharacters(in: .whitespaces).uppercased() != ":LOGBOOK:")) { return nil }
 352        return (lines.dropFirst().dropLast().joined(separator: "\n"), first.utf16.count + 1)
 353    }
 354
 355    /// `body` with `text`, which starts at `base` in the document, parsed.
 356    private func within<T>(_ text: String, base: Int, _ body: (OrgTree) -> T) -> T {
 357        let saved = self.base
 358        self.base = base
 359        depth += 1
 360        defer { self.base = saved; depth -= 1 }
 361        return body(OrgParser.parse(text, defaults: settings))
 362    }
 363
 364    // MARK: - Document
 365
 366    private var source: ExportSource?
 367
 368    /// `body` with `tree` as the source of `:exports`. As in `emacs -Q`, which loads no `ob-`
 369    /// library for dot, LaTeX and the like, their blocks export their code.
 370    private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
 371        let saved = source
 372        source = ExportSource(tree: tree, text: text, languages: false)
 373        defer { source = saved }
 374        return body()
 375    }
 376
 377    func document(_ text: String) -> String {
 378        let tree = OrgParser.parse(text, defaults: settings)
 379        documentTree = tree
 380        let codeBlocks = Coderef.blocks(tree)
 381        for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
 382            blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
 383        }
 384        // A definition runs to the next definition or heading, or two blank lines.
 385        let ns = text as NSString
 386        for node in tree.root.descendants() where node.kind == .footnoteDefinition {
 387            guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) else { continue }
 388            let start = node.range.lowerBound + node.text.utf16.distance(from: node.text.startIndex, to: m.range.upperBound)
 389            var end = node.range.upperBound
 390            let siblings = node.parent?.children ?? []
 391            if let index = siblings.firstIndex(where: { $0.range == node.range }) {
 392                for sibling in siblings[(index + 1)...] {
 393                    if [.footnoteDefinition, .section, .heading].contains(sibling.kind) { break }
 394                    let gap = ns.substring(with: NSRange(location: node.range.lowerBound, length: sibling.range.lowerBound - node.range.lowerBound))
 395                    if gap.range(of: "\n[ \t]*\n[ \t]*\n[ \t]*$", options: .regularExpression) != nil { break }
 396                    absorbed.insert(sibling.range.lowerBound)
 397                    end = sibling.range.upperBound
 398                }
 399            }
 400            definitions[String(m.1)] = (ns.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .newlines), start, false)
 401        }
 402        selected = HTMLRenderer.selection(tree, tags: options.selectTags)
 403        collect(tree)
 404        if footnotePass == nil, withFootnotes { numberFootnotes(text) }
 405        return rendering(tree, text) { tree.root.children.map(element).joined() }
 406    }
 407
 408    /// Org text that starts at `base` in the document, rendered as elements.
 409    private func blocks(_ text: String, base: Int) -> String {
 410        within(text, base: base) { tree in rendering(tree, text) { tree.root.children.map(element).joined() } }
 411    }
 412
 413    /// One line of org text rendered inline.
 414    func inlineString(_ text: String) -> String {
 415        let tree = OrgParser.parse(text, defaults: settings)
 416        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
 417        return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
 418    }
 419
 420    // MARK: - Table of contents
 421
 422    /// `org-odt-toc` for the whole document: headings to `toc`, or nothing.
 423    func tableOfContents() -> String {
 424        guard let depth = options.toc else { return "" }
 425        return toc(depth: depth, scope: nil, template: true)
 426    }
 427
 428    /// `org-export-collect-headlines`: `depth` relative to `scope`, within `H`, without the
 429    /// headings `org-export-excluded-from-toc-p` leaves out.
 430    /// In the `template` one, ox-odt reads `org-done-keywords` outside the Org buffer, where
 431    /// it's empty: every keyword is a TODO one.
 432    /// A `local` one has no title, even outside any heading.
 433    private func toc(depth: Int, scope: Int?, local: Bool = false, template: Bool = false) -> String {
 434        let limit = min(scope.flatMap { headings[$0].map { $0.relative + depth } } ?? depth, options.headlineLevels)
 435        let keys = headingOrder.filter { key in
 436            let heading = headings[key]!
 437            let excluded = heading.lowLevel || unnumberedValue(heading) == "notoc" || options.toc.map { heading.relative > $0 } ?? false
 438            return heading.relative <= limit && !excluded && (scope.map { heading.ancestors.contains($0) } ?? true)
 439        }
 440        guard !keys.isEmpty else { return "" }
 441        let title = local ? nil : ExportDictionary.translate("Table of Contents", language: language, encoding: .utf8)
 442        var out = "\n<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n"
 443        out += "  <text:table-of-content-source text:outline-level=\"\(depth)\">"
 444        if let title { out += "\n    <text:index-title-template text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:index-title-template>\n" }
 445        for level in 1...10 {
 446            out += """
 447
 448                  <text:table-of-content-entry-template text:outline-level="\(level)" text:style-name="Contents_20_\(level)">
 449                   <text:index-entry-link-start text:style-name="Internet_20_link"/>
 450                   <text:index-entry-chapter/>
 451                   <text:index-entry-text/>
 452                   <text:index-entry-link-end/>
 453                  </text:table-of-content-entry-template>
 454
 455            """
 456        }
 457        out += "\n  </text:table-of-content-source>\n  <text:index-body>"
 458        if let title {
 459            out += "\n    <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">\n      <text:p text:style-name=\"Contents_20_Heading\">\(Self.escape(title))</text:p>\n    </text:index-title>\n"
 460        }
 461        tocEntry = true
 462        out += keys.map { key in
 463            let heading = headings[key]!
 464            var entry = heading.number.map { $0.map(String.init).joined(separator: ".") + ". " } ?? ""
 465            let parts = headlineParts(heading.node)
 466            if let todo = parts.todo { entry += "<text:span text:style-name=\"\(settings.isDone(todo) && !template ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
 467            if let priority = parts.priority { entry += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
 468            entry += parts.title
 469            if options.tagsInTOC, !parts.tags.isEmpty { entry += " " + tagsSpan(parts.tags) }
 470            return "\n<text:p text:style-name=\"Contents_20_\(heading.relative)\"><text:a xlink:type=\"simple\" xlink:href=\"#\(heading.reference)\">\(entry)</text:a></text:p>"
 471        }.joined(separator: "\n")
 472        tocEntry = false
 473        return out + "\n  </text:index-body>\n</text:table-of-content>"
 474    }
 475
 476    /// Rendering a table of contents entry: footnotes and targets drop out, links become text.
 477    private var tocEntry = false
 478
 479    // MARK: - Elements
 480
 481    private var affiliated: [String: String] = [:]
 482    /// `:exports` of the last src block or call: its results are exported only for `results`
 483    /// and `both`; nothing runs.
 484    private var lastExports = "code"
 485
 486    func element(_ node: SyntaxNode) -> String {
 487        if depth == 0, absorbed.contains(node.range.lowerBound) { return "" }
 488        defer { if node.kind != .affiliatedKeyword { affiliated = [:] } }
 489        if node.kind != .affiliatedKeyword, affiliated["RESULTS"] != nil {
 490            defer { lastExports = "code" }
 491            if lastExports != "results", lastExports != "both" { return "" }
 492        }
 493        if node.kind == .block || node.kind == .keyword, let exports = source?.exports(at: node.range.lowerBound) {
 494            lastExports = exports
 495            if exports == "results" || exports == "none" { return "" }
 496        }
 497        switch node.kind {
 498        case .section:
 499            guard let heading = node.firstChild(.heading) else { fallthrough }
 500            switch HTMLRenderer.sectionExport(heading, options: options, selected: selected) {
 501            case .nothing: return ""
 502            case .heading: return section(node, heading: heading, contents: false)
 503            case .all: return section(node, heading: heading, contents: true)
 504            }
 505        case .zerothSection, .document:
 506            return node.children.map(element).joined()
 507        case .affiliatedKeyword:
 508            let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
 509            if let m = line.firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) {
 510                affiliated[m.1.uppercased()] = String(m.2)
 511            }
 512            return ""
 513        case .paragraph:
 514            return paragraph(node)
 515        case .keyword:
 516            return keyword(node)
 517        case .plainList:
 518            return list(node)
 519        case .table:
 520            return withTables ? table(node) : ""
 521        case .block:
 522            return block(node)
 523        case .horizontalRule:
 524            return "\n<text:p text:style-name=\"Horizontal_20_Line\"></text:p>"
 525        case .drawer, .dynamicBlock:
 526            guard let inner = inner(node) else { return "" }
 527            return blocks(inner.text, base: base + node.range.lowerBound + inner.offset)
 528        case .inlineTask:
 529            // `emacs -Q` doesn't load org-inlinetask, so ox-odt reads them as headings.
 530            return fail("ODT export doesn't support inline tasks")
 531        case .latexEnvironment:
 532            guard options.tex else { return "" }
 533            // Its value ends with a newline, which ox-odt writes as an empty last line.
 534            return code(Self.dedent(node.text.trimmingCharacters(in: .newlines).components(separatedBy: "\n")), emptyLast: node.text.hasSuffix("\n"))
 535        case .fixedWidth:
 536            let lines = node.text.trimmingCharacters(in: .newlines).split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
 537                let trimmed = line.drop { $0 == " " || $0 == "\t" }
 538                return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
 539            }
 540            return code(lines)
 541        case .tableEl:
 542            // ox-odt strips table.el tables, the list around them closed and opened again.
 543            return frames.isEmpty || !withTables ? "" : "\n" + reopening(nil, for: node)
 544        default:
 545            // Comments, property drawers, planning, clocks, footnote definitions, formulas.
 546            return ""
 547        }
 548    }
 549
 550    // MARK: - Headings
 551
 552    private func headlineParts(_ node: SyntaxNode) -> (todo: String?, priority: String?, title: String, tags: [String]) {
 553        let tokens = node.tokens
 554        let todo = options.todo ? tokens.first { $0.kind == .todoKeyword }?.text : nil
 555        let priority = options.priority ? tokens.first { $0.kind == .priority }?.text.firstMatch(of: /\[#(.+)\]/).map { String($0.1) } : nil
 556        let title = node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
 557        let tags = options.tags ? tokens.first { $0.kind == .tags }?.text.split(separator: ":").map(String.init) ?? [] : []
 558        return (todo, priority, title, tags)
 559    }
 560
 561    private func tagsSpan(_ tags: [String]) -> String {
 562        "<text:span text:style-name=\"OrgTags\">[" + tags.map { "<text:span text:style-name=\"OrgTag\">\(Self.escape($0))</text:span>" }.joined(separator: " : ") + "]</text:span>"
 563    }
 564
 565    /// `org-odt-format-headline-default-function`.
 566    private func headline(_ node: SyntaxNode) -> String {
 567        let parts = headlineParts(node)
 568        var out = ""
 569        if let todo = parts.todo { out += "<text:span text:style-name=\"\(settings.isDone(todo) ? "OrgDone" : "OrgTodo")\">\(Self.escape(todo))</text:span> " }
 570        if let priority = parts.priority { out += "<text:span text:style-name=\"OrgPriority-\(priority)\">[#\(priority)]</text:span> " }
 571        out += parts.title
 572        if !parts.tags.isEmpty { out += "<text:tab/>" + tagsSpan(parts.tags) }
 573        return out
 574    }
 575
 576    private static func target(_ text: String, _ id: String) -> String {
 577        "\n<text:bookmark-start text:name=\"OrgXref.\(id)\"/>\n<text:bookmark text:name=\"\(id)\"/>\(text)\n<text:bookmark-end text:name=\"OrgXref.\(id)\"/>"
 578    }
 579
 580    private func section(_ node: SyntaxNode, heading node0: SyntaxNode, contents: Bool) -> String {
 581        guard let heading = headings[base + node0.range.lowerBound] else { return "" }
 582        let extra = heading.info?.id.map { Self.target("", "ID-" + $0) } ?? ""
 583        let anchored = Self.target(headline(node0), heading.reference)
 584        let numbered = heading.number != nil
 585        headingStack.append(heading.key)
 586        defer { headingStack.removeLast() }
 587        guard heading.lowLevel else {
 588            let open = "\n<text:h text:style-name=\"Heading_20_\(heading.relative)\(numbered ? "" : "_unnumbered")\" text:outline-level=\"\(heading.relative)\" text:is-list-header=\"\(numbered ? "false" : "true")\">\(extra)\(anchored)</text:h>"
 589            return open + (contents ? node.children.filter { $0.kind != .heading }.map(element).joined() : "")
 590        }
 591        // A heading deeper than `H` is a list item, its siblings in one list.
 592        let siblings = (node.parent?.children ?? []).filter { section in
 593            section.kind == .section && section.firstChild(.heading).map { headings[base + $0.range.lowerBound] != nil } ?? false
 594        }
 595        let style = numbered ? "OrgNumberedList" : "OrgBulletedList"
 596        var out = ""
 597        if siblings.first?.range == node.range {
 598            let parentLow = heading.ancestors.last.flatMap { headings[$0]?.lowLevel } ?? false
 599            out += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(parentLow)\">"
 600        }
 601        frames.append(Frame(style: style, heading: true))
 602        let body = "\n<text:p text:style-name=\"Text_20_body\">\(extra)\(anchored)</text:p>" + (contents ? node.children.filter { $0.kind != .heading }.map(element).joined() : "")
 603        let frame = frames.removeLast()
 604        out += "\n<text:list-item>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
 605        if siblings.last?.range == node.range { out += "</text:list>" }
 606        return out
 607    }
 608
 609    // MARK: - Paragraphs
 610
 611    private enum Container { case quote, center }
 612    /// The quote or center block paragraphs are in.
 613    private var container: Container?
 614    /// Paragraph styles outside, in a center block and in a quote block.
 615    private var paragraphStyles = ("Text_20_body", "OrgCenter", "Quotations")
 616    /// Rendering a paragraph that is only an image link.
 617    private var standalone = false
 618
 619    private func paragraph(_ node: SyntaxNode, prefix: String = "", style: String? = nil) -> String {
 620        let named = style ?? paragraphStyles.0
 621        let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : named
 622        standalone = soleImage(node) != nil
 623        defer { standalone = false }
 624        imageKey = base + node.range.lowerBound
 625        imageCaptioned = affiliated["CAPTION"] != nil || affiliated["NAME"] != nil
 626        imageCaption = affiliated["CAPTION"]
 627        imageAttributes = affiliated["ATTR_ODT"]
 628        defer { imageKey = nil; imageCaptioned = false; imageCaption = nil; imageAttributes = nil }
 629        var contents = inline(node)
 630        // The paragraph's own last newline isn't a line break.
 631        if preserveBreaks, node.text.hasSuffix("\n"), node.text.range(of: "\\\\\\\\[ \t]*\n$", options: .regularExpression) == nil,
 632           contents.hasSuffix("<text:line-break/>") {
 633            contents.removeLast("<text:line-break/>".count)
 634        }
 635        return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(contents.trimmingCharacters(in: .whitespacesAndNewlines))</text:p>"
 636    }
 637
 638    /// The link of a paragraph that is only an image link.
 639    private func soleImage(_ node: SyntaxNode) -> SyntaxNode? {
 640        let links = node.children.filter { $0.kind == .link }
 641        guard links.count == 1, node.children.count == 1,
 642              node.tokens.allSatisfy({ $0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }),
 643              links[0].firstChild(.linkDescription) == nil,
 644              let file = Self.linkPath(links[0]).flatMap(Self.filePath), Self.isImage(file) else { return nil }
 645        return links[0]
 646    }
 647
 648    private func keyword(_ node: SyntaxNode) -> String {
 649        guard let m = node.text.trimmingCharacters(in: .whitespacesAndNewlines).firstMatch(of: /^#\+([A-Za-z_]+):[ \t]*(.*)$/) else { return "" }
 650        let value = String(m.2)
 651        switch m.1.uppercased() {
 652        case "ODT":
 653            return value
 654        case "TOC":
 655            guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else { return "" }
 656            let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) } ?? options.headlineLevels
 657            if value.range(of: ":target", options: .caseInsensitive) != nil { return fail("ODT export doesn't support #+TOC with :target") }
 658            let local = value.range(of: "\\blocal\\b", options: [.regularExpression, .caseInsensitive]) != nil
 659            return toc(depth: depth, scope: local ? currentHeading() : nil, local: local)
 660        case "PRINT_BIBLIOGRAPHY":
 661            guard let citations else { return "" }
 662            return citations.bibliography.map { "\n<text:p text:style-name=\"Text_20_body\">" + render($0) + "</text:p>" }.joined()
 663        default:
 664            return ""
 665        }
 666    }
 667
 668    /// The heading whose section is being rendered.
 669    private var headingStack: [Int] = []
 670    private func currentHeading() -> Int? { headingStack.last }
 671
 672    // MARK: - Lists
 673
 674    /// An open list item, closed and opened again around a table; `heading` for a heading
 675    /// deeper than `H`.
 676    private struct Frame {
 677        var style: String
 678        var heading = false
 679        var header = false
 680    }
 681
 682    private var frames: [Frame] = []
 683
 684    private func list(_ node: SyntaxNode) -> String {
 685        let items = node.children.filter { $0.kind == .item }
 686        guard let first = items.first else { return "" }
 687        let bullet = first.tokens.first { $0.kind == .bullet }?.text ?? "-"
 688        let ordered = bullet.first.map { $0.isNumber || $0.isLetter } ?? false
 689        let descriptive = !ordered && first.firstChild(.itemTag) != nil
 690        let style = ordered ? "OrgNumberedList" : descriptive ? "OrgDescriptionList" : "OrgBulletedList"
 691        let nested = node.parent?.kind == .item
 692        var out = "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"\(nested)\">\n"
 693        for item in items {
 694            let box = checkbox(item)
 695            if descriptive {
 696                // As `org-odt--translate-description-lists`: the term in bold, the definition
 697                // an item of a list inside.
 698                frames.append(Frame(style: style))
 699                let term = item.firstChild(.itemTag).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "(no term)"
 700                var body = paragraphText(term, prefix: box, style: "Text_20_body_20_bold")
 701                body += "\n<text:list text:style-name=\"\(style)\" text:continue-numbering=\"true\">\n"
 702                body += itemBody(item, prefix: "")
 703                body += "</text:list>"
 704                out += close(body, start: nil)
 705            } else {
 706                frames.append(Frame(style: style))
 707                let counter = item.tokens.first { $0.kind == .counter }?.text.firstMatch(of: /\[@([0-9A-Za-z]+)\]/).map { String($0.1) }
 708                out += closeItem(item, prefix: box, start: counter)
 709            }
 710        }
 711        return out + "</text:list>"
 712    }
 713
 714    private func itemBody(_ item: SyntaxNode, prefix: String) -> String {
 715        frames.append(Frame(style: "OrgDescriptionList"))
 716        return closeItem(item, prefix: prefix, start: nil)
 717    }
 718
 719    /// The item's contents, the first paragraph after `prefix`, in the open frame.
 720    private func closeItem(_ item: SyntaxNode, prefix: String, start: String?) -> String {
 721        var body = ""
 722        for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
 723            body += index == 0 && child.kind == .paragraph ? paragraph(child, prefix: prefix) : element(child)
 724        }
 725        return close(body, start: start)
 726    }
 727
 728    private func close(_ body: String, start: String?) -> String {
 729        let frame = frames.removeLast()
 730        return "\n<text:list-item\(start.map { " text:start-value=\"\($0)\"" } ?? "")>\n\(body)\n\(frame.header ? "</text:list-header>" : "</text:list-item>")"
 731    }
 732
 733    private func paragraphText(_ content: String, prefix: String, style: String) -> String {
 734        let chosen = container == .quote ? paragraphStyles.2 : container == .center ? paragraphStyles.1 : style
 735        return "\n<text:p text:style-name=\"\(chosen)\">\(prefix)\(content)</text:p>"
 736    }
 737
 738    private func checkbox(_ item: SyntaxNode) -> String {
 739        guard let box = item.tokens.first(where: { $0.kind == .checkbox })?.text else { return "" }
 740        let mark = ["[X]": "[&#x2713;] ", "[x]": "[&#x2713;] ", "[-]": "[-] "][box] ?? "[ ] "
 741        return "<text:span text:style-name=\"OrgCode\">\(mark)</text:span>"
 742    }
 743
 744    /// `org-odt-table`'s list handling for `node`: the open lists closed, `inner` in an indented
 745    /// section, the lists opened again, the innermost item as a header.
 746    private func reopening(_ inner: String?, for node: SyntaxNode) -> String {
 747        // ox-odt doesn't close the lists around a table in a block, and writes XML that doesn't
 748        // nest.
 749        if let parent = node.parent, parent.kind != .item, parent.kind != .section, frames.contains(where: { !$0.heading }) {
 750            return fail("ODT export doesn't support a table in a block inside a list")
 751        }
 752        var closing: [String] = []
 753        for frame in frames.reversed() {
 754            closing.append(frame.header ? "</text:list-header>" : "</text:list-item>")
 755            closing.append("</text:list>")
 756        }
 757        var opening: [String] = []
 758        for (index, frame) in frames.enumerated() {
 759            opening.append("\n<text:list text:style-name=\"\(frame.style)\" text:continue-numbering=\"true\">")
 760            opening.append(index == frames.count - 1 || frame.header ? "<text:list-header>" : "<text:list-item>")
 761        }
 762        if !frames.isEmpty { frames[frames.count - 1].header = true }
 763        let section = inner.map { inner -> String in
 764            sections += 1
 765            return "\n<text:section text:style-name=\"OrgIndentedSection-Level-\(closing.count / 2)\" text:name=\"Section\(sections)\">\n\(inner)\n</text:section>"
 766        } ?? ""
 767        return closing.joined(separator: "\n") + section + opening.joined(separator: "\n")
 768    }
 769
 770    private var sections = 0
 771
 772    // MARK: - Tables
 773
 774    private var tableStyles: [(name: String, width: String)] = []
 775    private var tableCount = 0
 776
 777    private func table(_ node: SyntaxNode) -> String {
 778        let attributeLine = affiliated["ATTR_ODT"]
 779        let attributes = attributeLine.map(Self.attributes) ?? [:]
 780        if attributes["style"] != nil { return fail("ODT export doesn't support table templates (#+ATTR_ODT: :style)") }
 781        let caption = label(base + node.range.lowerBound, caption: affiliated["CAPTION"])
 782        let rows = node.children.filter { $0.kind == .tableRow }
 783        enum Kind { case rule, special, data }
 784        var cells: [[SyntaxNode]] = rows.map { $0.children.filter { $0.kind == .tableCell } }
 785        var kinds: [Kind] = rows.indices.map { cells[$0].isEmpty && rows[$0].text.trimmingCharacters(in: .whitespaces).hasPrefix("|-") ? .rule : .data }
 786        func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "|")).trimmingCharacters(in: .whitespaces) }
 787        // `org-export-table-has-special-column-p`.
 788        let firsts = rows.indices.filter { kinds[$0] == .data }.map { cells[$0].first.map(value) ?? "" }
 789        let specialColumn = firsts.contains { !$0.isEmpty } && firsts.allSatisfy { ["", "/", "#", "!", "$", "*", "_", "^"].contains($0) }
 790        for r in rows.indices where kinds[r] == .data {
 791            let values = cells[r].map(value)
 792            let cookies = values.allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil } && values.contains { !$0.isEmpty }
 793            if values.first == "/" || (specialColumn && ["^", "_", "$", "!"].contains(values.first ?? "")) || cookies { kinds[r] = .special }
 794        }
 795        let firstValues = rows.indices.map { cells[$0].first.map(value) ?? "" }
 796        if specialColumn { cells = cells.map { Array($0.dropFirst()) } }
 797        let columns = rows.indices.filter { kinds[$0] != .rule }.map { cells[$0].count }.max() ?? 0
 798        // Alignment and width cookies, and column groups.
 799        var align = Array(repeating: "", count: columns)
 800        var width = Array(repeating: 0, count: columns)
 801        var groups = Array(repeating: "", count: columns)
 802        for r in rows.indices where kinds[r] == .special {
 803            let values = cells[r].map(value)
 804            for (c, v) in values.enumerated() {
 805                if let m = v.firstMatch(of: /^<([lrc])?([0-9]+)?>$/) {
 806                    if let a = m.1 { align[c] = String(a) }
 807                    if let w = m.2 { width[c] = Int(w) ?? 0 }
 808                }
 809                if firstValues[r] == "/" { groups[c] = v }
 810            }
 811        }
 812        let data = rows.indices.filter { kinds[$0] == .data }
 813        for c in 0..<columns where align[c].isEmpty {
 814            var numbers = 0
 815            var total = 0
 816            var previousNumber = false
 817            for r in data {
 818                let v = c < cells[r].count ? value(cells[r][c]) : ""
 819                total += 1
 820                if TablePlot.isNumber(v) || (v.isEmpty && previousNumber) {
 821                    previousNumber = true
 822                    numbers += 1
 823                } else {
 824                    previousNumber = false
 825                }
 826            }
 827            align[c] = total > 0 && Double(numbers) / Double(total) >= 0.5 ? "r" : "l"
 828        }
 829        // Row groups: data rows between rules.
 830        var group: [Int: Int] = [:]
 831        var current = 1
 832        var seen = false
 833        for r in rows.indices {
 834            if kinds[r] == .rule, seen { current += 1; seen = false }
 835            if kinds[r] == .data { group[r] = current; seen = true }
 836        }
 837        // `org-export-table-has-header-p`: a rule between data rows; special rows don't count.
 838        let firstData = data.first
 839        let hasHeader = firstData.map { start in
 840            guard let rule = rows.indices.first(where: { $0 > start && kinds[$0] == .rule }) else { return false }
 841            return data.contains { $0 > rule }
 842        } ?? false
 843        let headerColumns = attributes["header-columns"].map { Int($0) ?? 1 } ?? 0
 844        var body = ""
 845        for (index, r) in data.enumerated() {
 846            let previous = rows.indices.reversed().first { $0 < r && kinds[$0] != .special }
 847            let next = rows.indices.first { $0 > r && kinds[$0] != .special }
 848            let starts = previous.map { kinds[$0] == .rule } ?? true
 849            let ends = next.map { kinds[$0] == .rule } ?? true
 850            let header = group[r] == 1 && hasHeader
 851            if starts { body += header ? "\n<table:table-header-rows>" : "\n<table:table-rows>" }
 852            var row = ""
 853            for c in 0..<columns {
 854                let cell = c < cells[r].count ? cells[r][c] : nil
 855                let startsGroup = c == 0 || ["<", "<>"].contains(groups[c]) || [">", "<>"].contains(groups[c - 1])
 856                let style = "OrgTblCell" + (starts || index == 0 ? "T" : "") + (ends ? "B" : "") + (startsGroup && c != 0 ? "L" : "")
 857                let paragraph = (header || c < headerColumns ? "OrgTableHeading" : "OrgTableContents") + ["l": "Left", "r": "Right", "c": "Center"][align[c]]!
 858                let span = width[c]
 859                row += "\n<table:table-cell table:style-name=\"\(style)\"\(span > 0 ? " table:number-columns-spanned=\"\(span + 1)\"" : "")>\n"
 860                row += "\n<text:p text:style-name=\"\(paragraph)\">\(cell.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "")</text:p>"
 861                row += "\n</table:table-cell>" + String(repeating: "\n<table:covered-table-cell/>", count: span) + "\n"
 862            }
 863            body += "\n<table:table-row>\n\(row)\n</table:table-row>"
 864            if ends { body += header ? "\n</table:table-header-rows>" : "\n</table:table-rows>" }
 865        }
 866        // Every table counts toward the automatic style names, given only with `#+ATTR_ODT`.
 867        tableCount += 1
 868        var style = "OrgTable"
 869        if attributeLine != nil {
 870            style = "OrgTable\(tableCount)"
 871            tableStyles.append((style, attributes["rel-width"] ?? "96"))
 872        }
 873        let firstRow = data.first.map { cells[$0] } ?? []
 874        let columnSpecs = firstRow.indices.map { c in
 875            String(repeating: "\n<table:table-column table:style-name=\"OrgTableColumn\"/>", count: (c < width.count ? width[c] : 0) + 1)
 876        }.joined(separator: "\n")
 877        var out = caption.map { "\n<text:p text:style-name=\"Table\">\($0)</text:p>" } ?? ""
 878        out += "\n<table:table table:style-name=\"\(style)\">" + columnSpecs + "\n" + body + "</table:table>"
 879        return "\n" + reopening(out, for: node)
 880    }
 881
 882    /// `org-odt-format-label` as a definition: a bookmark, then the category, sequence number
 883    /// and caption; nil without a caption or name.
 884    private func label(_ key: Int, caption: String?) -> String? {
 885        guard let label = labels[key] else { return nil }
 886        let reference = label.reference ?? "nil"
 887        let category = ExportDictionary.translate(label.category, language: language, encoding: .utf8)
 888        let number = "<text:sequence text:ref-name=\"\(reference)\" text:name=\"\(label.variable)\" text:formula=\"ooow:\(label.variable)+1\" style:num-format=\"1\">\(label.sequence)</text:sequence>"
 889        let format = ExportDictionary.translate("%e %n: %c", language: language, encoding: .utf8)
 890        let text = format.replacingOccurrences(of: "%e", with: category).replacingOccurrences(of: "%n", with: number)
 891            .replacingOccurrences(of: "%c", with: caption.map(inlineString) ?? "")
 892        return "\n<text:bookmark text:name=\"\(reference)\"/>" + text
 893    }
 894
 895    // MARK: - Blocks
 896
 897    /// A block's type, parameters, its first line and its contents with their offset in the block.
 898    static func blockParts(_ node: SyntaxNode) -> (type: String, parameters: String, lines: [String], body: (text: String, offset: Int)) {
 899        var lines = node.text.components(separatedBy: "\n")
 900        if lines.last == "" { lines.removeLast() }
 901        guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return ("", "", lines, ("", 0)) }
 902        let body = lines.dropFirst().dropLast().map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 903        return (m.1.lowercased(), String(m.2), lines, (body.joined(separator: "\n"), first.utf16.count + 1))
 904    }
 905
 906    private func block(_ node: SyntaxNode) -> String {
 907        let (type, parameters, lines, body) = Self.blockParts(node)
 908        guard !lines.isEmpty, !type.isEmpty else { return "" }
 909        let key = base + node.range.lowerBound
 910        let unescaped = body.text.isEmpty && lines.count <= 2 ? [] : body.text.components(separatedBy: "\n")
 911        switch type {
 912        case "src":
 913            let caption = label(key, caption: affiliated["CAPTION"]).map { "\n<text:p text:style-name=\"Listing\">\($0)</text:p>" } ?? ""
 914            let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
 915            let language = parameters.split(whereSeparator: \.isWhitespace).first.map(String.init).flatMap { $0.hasPrefix("-") || $0.hasPrefix(":") ? nil : $0 }
 916            // Babel rewrites the block, which empties lines of only blanks unless `-i` keeps
 917            // the indentation.
 918            let preserve = Coderef.block(lines)?.switches.preserveIndent ?? false
 919            let kept = preserve ? unescaped : unescaped.map { $0.allSatisfy { $0 == " " || $0 == "\t" } ? "" : $0 }
 920            let formatted = numbered(lines, Self.dedent(kept), fontified: language.map(ODTSourceModes.fontified) ?? true)
 921            if let textbox = attributes["textbox"], textbox != "nil" {
 922                return caption + "\n<text:p text:style-name=\"Text_20_body\">\(self.textbox(formatted, width: nil, height: nil, style: nil, extra: nil, anchor: nil))</text:p>"
 923            }
 924            return caption + formatted
 925        case "example":
 926            return numbered(lines, Self.dedent(unescaped))
 927        case "quote", "center":
 928            let saved = container
 929            container = type == "quote" ? .quote : .center
 930            defer { container = saved }
 931            return blocks(body.text, base: key + body.offset)
 932        case "verse":
 933            let rendered = unescaped.map { line -> String in
 934                inlineString(line, verse: true).replacingOccurrences(of: "[ \\t]+$", with: "", options: .regularExpression)
 935            }
 936            var out = rendered.map { $0 + "<text:line-break/>" }.joined()
 937            if let indent = out.firstMatch(of: /^[ \t]+/) {
 938                out = Self.encodeSpaces(String(indent.output)) + out[indent.range.upperBound...]
 939            }
 940            return "\n<text:p text:style-name=\"OrgVerse\">\(out)</text:p>"
 941        case "export":
 942            return parameters.split(separator: " ").first?.lowercased() == "odt" ? Self.dedent(unescaped).joined(separator: "\n") : ""
 943        case "comment":
 944            return ""
 945        default:
 946            let attributes = affiliated["ATTR_ODT"].map(Self.attributes) ?? [:]
 947            let contents = blocks(body.text, base: key + body.offset)
 948            switch type {
 949            case "textbox":
 950                let size = { (key: String) in attributes[key].flatMap(Double.init) }
 951                return "\n<text:p text:style-name=\"Text_20_body\">\(textbox(contents, width: size("width"), height: size("height"), style: attributes["style"], extra: attributes["extra"], anchor: attributes["anchor"]))</text:p>"
 952            case "annotation":
 953                if attributes["date"] != nil || dated { return fail("ODT export doesn't support dated annotations") }
 954                let author = attributes["author"].map { Self.escape($0) } ?? author
 955                return "\n<text:p><office:annotation>\n\(author.map { "<dc:creator>\($0)</dc:creator>" } ?? "")\(contents)\n</office:annotation></text:p>"
 956            default:
 957                return contents
 958            }
 959        }
 960    }
 961
 962    /// The code of a src or example block, labels and numbers as its switches ask.
 963    private func numbered(_ block: [String], _ body: [String], fontified: Bool = true) -> String {
 964        let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
 965        let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
 966        let key = block.joined(separator: "\n")
 967        let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
 968        return code(lines, refs: refs, retain: switches.retainLabels, loc: switches.numberLines == nil ? nil : loc, fontified: fontified)
 969    }
 970
 971    /// `org-odt-do-format-code`: one paragraph per line. From the line `org-split-string`
 972    /// counts as the last, which leaves out a leading and a trailing empty line, the style is
 973    /// the last line's. Without a mode for the language, no fontifying: another style and
 974    /// spaces encoded as in text.
 975    private func code(_ lines: [String], refs: [Int: String] = [:], retain: Bool = false, loc: Int? = nil, emptyLast: Bool = false, fontified: Bool = true) -> String {
 976        let lines = emptyLast ? lines + [""] : lines
 977        let joined = lines.joined(separator: "\n")
 978        let last = lines.count - (joined.hasPrefix("\n") ? 1 : 0) - (joined.hasSuffix("\n") ? 1 : 0)
 979        let style = fontified ? "OrgSrcBlock" : "OrgFixedWidthBlock"
 980        let out = lines.enumerated().map { index, line -> String in
 981            var text = line
 982            if let ref = refs[index + 1], retain { text += " (\(ref))" }
 983            var encoded = fontified
 984                ? Self.escape(text, quotes: true).replacingOccurrences(of: " ", with: "<text:s/>").replacingOccurrences(of: "\t", with: "<text:tab/>")
 985                : Self.encodeSpaces(Self.escape(text))
 986            if let ref = refs[index + 1] { encoded = Self.target(encoded, "coderef-" + ref) }
 987            let paragraph = "\n<text:p text:style-name=\"\(style)\(last > 0 && index >= last - 1 ? "LastLine" : "")\">\(encoded)</text:p>"
 988            return loc == nil ? paragraph : "\n<text:list-item>\(paragraph)\n</text:list-item>"
 989        }.joined()
 990        guard let loc else { return out }
 991        return "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\" text:continue-numbering=\"\(loc != 0)\">\(out)</text:list>"
 992    }
 993
 994    static func dedent(_ lines: [String]) -> [String] {
 995        let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
 996        let common = indents.min() ?? 0
 997        return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
 998    }
 999
1000    // MARK: - Frames
1001
1002    private var frameCount = 0
1003
1004    /// `org-odt--frame`.
1005    private func frame(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
1006        frameCount += 1
1007        var attributes = width.map { String(format: " svg:width=\"%0.2fcm\"", $0) } ?? ""
1008        attributes += height.map { String(format: " svg:height=\"%0.2fcm\"", $0) } ?? ""
1009        attributes += (extra ?? "") + " text:anchor-type=\"\(anchor ?? "paragraph")\" draw:name=\"Frame\(frameCount)\""
1010        return "\n<draw:frame draw:style-name=\"\(style ?? "nil")\"\(attributes)>\n\(text)\n</draw:frame>"
1011    }
1012
1013    /// `org-odt--textbox`.
1014    private func textbox(_ text: String, width: Double?, height: Double?, style: String?, extra: String?, anchor: String?) -> String {
1015        let box = String(format: " fo:min-height=\"%0.2fcm\"", height ?? 0.2) + (width == nil ? String(format: " fo:min-width=\"%0.2fcm\"", 0.2) : "")
1016        return frame("\n<draw:text-box \(box)>\(text)\n</draw:text-box>", width: width, height: nil, style: style, extra: extra, anchor: anchor)
1017    }
1018
1019    // MARK: - Images
1020
1021    /// The paragraph holding the image being rendered, and its caption and attributes.
1022    private var imageKey: Int?
1023    private var imageCaptioned = false
1024    private var imageCaption: String?
1025    private var imageAttributes: String?
1026
1027    /// A bracket link's path, or a plain or angle `file:` link's.
1028    static func linkPath(_ node: SyntaxNode) -> String? {
1029        if let path = node.linkPath { return path }
1030        var text = node.text
1031        if text.hasPrefix("<"), text.hasSuffix(">") { text = String(text.dropFirst().dropLast()) }
1032        return text.hasPrefix("file:") ? text : nil
1033    }
1034
1035    /// A link's file, for `file:` links and paths Org reads as files.
1036    static func filePath(_ path: String) -> String? {
1037        var file: String
1038        if path.hasPrefix("file:") {
1039            file = String(path.dropFirst(5))
1040        } else if ["/", "./", "../", "~/"].contains(where: path.hasPrefix) {
1041            file = path
1042        } else {
1043            return nil
1044        }
1045        if let range = file.range(of: "::") { file = String(file[..<range.lowerBound]) }
1046        return file
1047    }
1048
1049    /// `org-export-insert-image-links`: the image a link's description shows, if it is one.
1050    static func describedImage(_ description: SyntaxNode) -> String? {
1051        filePath(description.text.trimmingCharacters(in: .whitespaces).replacing(/^\[\[(.*)\]\]$/) { String($0.1) }).flatMap { isImage($0) ? $0 : nil }
1052    }
1053
1054    static func isImage(_ file: String) -> Bool {
1055        file.range(of: "\\.(jpeg|jpg|png|gif|svg)", options: [.regularExpression, .caseInsensitive]) != nil
1056    }
1057
1058    static func expand(_ file: String, directory: URL) -> URL {
1059        let path = OrgPaths.expandingTilde(file)
1060        return path.hasPrefix("/") ? URL(fileURLWithPath: path) : directory.appendingPathComponent(path).standardizedFileURL
1061    }
1062
1063    /// `org-odt-link--inline-image`: the file embedded under `Images/`, sized from its pixels
1064    /// at 96 dpi or `#+ATTR_ODT`, within 17 by 20 cm.
1065    private func image(_ file: String) -> String {
1066        let url = Self.expand(file, directory: directory)
1067        guard let data = try? Data(contentsOf: url) else { return fail("Opening input file: No such file or directory, \(url.path)") }
1068        let ext = (file as NSString).pathExtension
1069        let name = String(format: "Images/%04d.%@", images.count + 1, ext)
1070        images.append((name, data))
1071        let attributes = imageAttributes.map(Self.attributes) ?? [:]
1072        let user = { (key: String) in attributes[key].flatMap(Double.init) }
1073        let scale = user("scale")
1074        let userWidth = scale == nil ? user("width") : nil
1075        let userHeight = scale == nil ? user("length") : nil
1076        var size = (width: 5.0, height: 5.0)
1077        if userWidth == nil || userHeight == nil {
1078            if let source = CGImageSourceCreateWithData(data as CFData, nil),
1079               let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
1080               let w = properties[kCGImagePropertyPixelWidth] as? Double, let h = properties[kCGImagePropertyPixelHeight] as? Double {
1081                size = (w / 96 * 2.54, h / 96 * 2.54)
1082            }
1083        }
1084        if let scale {
1085            size = (size.width * scale, size.height * scale)
1086        } else if let userWidth, let userHeight {
1087            size = (userWidth, userHeight)
1088        } else if let userHeight {
1089            size = (userHeight * size.width / size.height, userHeight)
1090        } else if let userWidth {
1091            size = (userWidth, userWidth * size.height / size.width)
1092        }
1093        if size.width > 17 || size.height > 20 {
1094            let factor = min(17 / size.width, 20 / size.height)
1095            size = (size.width * factor, size.height * factor)
1096        }
1097        let href = "\n<draw:image xlink:href=\"\(name)\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
1098        if !standalone, imageCaptioned { return fail("Don't know how to format label for an image inside text") }
1099        let caption = standalone ? imageKey.flatMap { label($0, caption: imageCaption) } : nil
1100        guard let caption else {
1101            return frame(href, width: size.width, height: size.height, style: standalone ? "OrgDisplayImage" : "OrgInlineImage", extra: nil, anchor: standalone ? "paragraph" : "as-char")
1102        }
1103        let inner = frame(href, width: size.width, height: size.height, style: "OrgCaptionedImage", extra: " style:rel-width=\"100%\" style:rel-height=\"scale\"", anchor: "paragraph")
1104        return textbox("\n<text:p text:style-name=\"Illustration\">\(inner)\(caption)</text:p>", width: size.width, height: size.height, style: "OrgImageCaptionFrame", extra: nil, anchor: "paragraph")
1105    }
1106
1107    // MARK: - Inline
1108
1109    func inline(_ node: SyntaxNode) -> String {
1110        afterFootnote = false
1111        var out = ""
1112        var text = ""
1113        // A line break object takes the newline after it, as Org's does.
1114        var afterBreak = false
1115        for element in node.elements {
1116            switch element {
1117            case .token(let token):
1118                switch token.kind {
1119                case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1120                    continue
1121                default:
1122                    text += afterBreak && text.isEmpty && token.text.hasPrefix("\n") ? String(token.text.dropFirst()) : token.text
1123                    afterBreak = false
1124                }
1125            case .node(let child):
1126                if !text.isEmpty { afterFootnote = false }
1127                out += plainText(text)
1128                text = ""
1129                out += object(child)
1130                afterBreak = child.kind == .lineBreak
1131            }
1132        }
1133        if !text.isEmpty { afterFootnote = false }
1134        return out + plainText(text)
1135    }
1136
1137    private var verse = false
1138
1139    private func inlineString(_ text: String, verse: Bool) -> String {
1140        let saved = self.verse
1141        self.verse = verse
1142        defer { self.verse = saved }
1143        let tree = OrgParser.parse(text, defaults: settings)
1144        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1145        return rendering(tree, text) { inline(paragraph) }
1146    }
1147
1148    static let textObjects = HTMLRenderer.textObjects
1149
1150    /// `org-odt-plain-text`, with the LaTeX fragments, entities and scripts the parser leaves in
1151    /// text.
1152    private func plainText(_ text: String) -> String {
1153        guard !text.isEmpty else { return "" }
1154        let ns = text as NSString
1155        var out = ""
1156        var at = 0
1157        for m in Self.textObjects.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
1158            out += plain(ns.substring(with: NSRange(location: at, length: m.range.location - at)))
1159            at = NSMaxRange(m.range)
1160            let whole = ns.substring(with: m.range)
1161            func group(_ i: Int) -> String? { m.range(at: i).location == NSNotFound ? nil : ns.substring(with: m.range(at: i)) }
1162            if group(1) != nil || group(2) != nil || group(3) != nil || group(4) != nil {
1163                if options.tex { out += "<text:span text:style-name=\"OrgCode\">\(Self.escape(whole))</text:span>" }
1164            } else if let name = group(5) {
1165                out += withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(whole) : plain(whole)
1166            } else if let marker = group(7), let body = group(8) {
1167                let braced = body.hasPrefix("{")
1168                if options.scripts == .off || (options.scripts == .braces && !braced) {
1169                    out += plain(whole)
1170                    continue
1171                }
1172                let inner = braced ? String(body.dropFirst().dropLast()) : body
1173                out += "<text:span text:style-name=\"\(marker == "_" ? "OrgSubscript" : "OrgSuperscript")\">\(plain(inner))</text:span>"
1174            } else {
1175                out += plain(whole)
1176            }
1177        }
1178        return out + plain(ns.substring(from: at))
1179    }
1180
1181    /// Escaped text with special strings, its line breaks as spaces outside verse, or as line
1182    /// breaks with `\\n`.
1183    private func plain(_ text: String) -> String {
1184        var out = Self.escape(text)
1185        if options.specialStrings {
1186            out = out.replacingOccurrences(of: "\\\\-", with: "&#x00ad;", options: .regularExpression)
1187                .replacingOccurrences(of: "---([^-])", with: "&#x2014;$1", options: .regularExpression)
1188                .replacingOccurrences(of: "--([^-])", with: "&#x2013;$1", options: .regularExpression)
1189                .replacingOccurrences(of: "...", with: "&#x2026;")
1190        }
1191        if verse { return out }
1192        if preserveBreaks { return out.replacingOccurrences(of: "[ \t]*\n", with: "<text:line-break/>", options: .regularExpression) }
1193        return out.replacingOccurrences(of: "\n", with: " ")
1194    }
1195
1196    private func span(_ style: String, _ content: String) -> String {
1197        "<text:span text:style-name=\"\(style)\">\(content)</text:span>"
1198    }
1199
1200    /// The previous object was a footnote reference, for the comma between two.
1201    private var afterFootnote = false
1202
1203    private func object(_ node: SyntaxNode) -> String {
1204        defer { afterFootnote = node.kind == .footnoteReference && !tocEntry }
1205        switch node.kind {
1206        case .bold: return span("Bold", inline(node))
1207        case .italic: return span("Emphasis", inline(node))
1208        case .underline: return span("Underline", inline(node))
1209        case .strikeThrough: return span("Strikethrough", inline(node))
1210        case .verbatim, .code:
1211            let value = node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1212            return span("OrgCode", Self.encodeSpaces(Self.escape(value)))
1213        case .link: return link(node)
1214        case .linkDescription: return inline(node)
1215        case .timestamp:
1216            let text = node.text.trimmingCharacters(in: .whitespaces)
1217            if text.hasPrefix("<%%") { return plain(text) }
1218            return span(text.hasPrefix("<") ? "OrgActiveTimestamp" : "OrgInactiveTimestamp", plain(text))
1219        case .footnoteReference:
1220            if tocEntry || !withFootnotes { return "" }
1221            let comma = afterFootnote ? span("OrgSuperscript", ",") : ""
1222            return comma + footnote(node)
1223        case .entity:
1224            let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
1225            return withEntities ? OrgEntities.display[name].map { Self.escape($0) } ?? plain(node.text) : plain(node.text)
1226        case .radioTarget:
1227            let inner = plain(String(node.text.dropFirst(3).dropLast(3)))
1228            if tocEntry { return inner }
1229            return Self.target(inner, targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1230        case .target:
1231            if tocEntry { return "" }
1232            return Self.target("", targets.first { $0.key == base + node.range.lowerBound }?.reference ?? "nil")
1233        case .superscript, .subscript:
1234            let text = node.text
1235            let body = text.dropFirst()
1236            let braced = body.hasPrefix("{") && body.hasSuffix("}")
1237            if options.scripts == .off || (options.scripts == .braces && !braced) { return plain(text) }
1238            let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
1239            return span(text.hasPrefix("_") ? "OrgSubscript" : "OrgSuperscript", plain(inner))
1240        case .lineBreak: return "<text:line-break/>"
1241        case .macro:
1242            guard case .some(let value) = source?.resultsMacro(node) else { return "" }
1243            return value.map(inlineString) ?? ""
1244        case .inlineSourceBlock:
1245            let exports = source?.exports(at: node.range.lowerBound) ?? "results"
1246            source?.inlineResults = exports == "results" || exports == "both"
1247            guard exports == "code" || exports == "both" else { return "" }
1248            // ox-odt has no transcoder for them.
1249            return fail("ODT export doesn't support inline source blocks")
1250        case .latexFragment:
1251            guard options.tex else { return "" }
1252            return span("OrgCode", Self.escape(node.text))
1253        case .statisticsCookie: return span("OrgCode", Self.escape(node.text))
1254        case .exportSnippet:
1255            guard node.tokens.first?.text.lowercased() == "@@odt:" else { return "" }
1256            return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1257        case .citation:
1258            if inTitle { return "" }
1259            guard let pieces = citations?.next(node.text) else { return plain(node.text) }
1260            return render(pieces)
1261        case .inlineBabelCall:
1262            source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
1263            return ""
1264        default: return inline(node)
1265        }
1266    }
1267
1268    /// A citation's or a bibliography entry's pieces.
1269    private func render(_ pieces: [CiteProcessor.Piece]) -> String {
1270        pieces.map { piece in
1271            switch piece {
1272            case .text(let s): plain(s)
1273            case .italic(let s): span("Emphasis", plain(s))
1274            case .org(let s) where s.allSatisfy(\.isWhitespace): s
1275            case .org(let s):
1276                String(s.prefix { $0.isWhitespace }) + inlineString(s) + String(s.reversed().prefix { $0.isWhitespace })
1277            }
1278        }.joined()
1279    }
1280
1281    // MARK: - Footnotes
1282
1283    /// Numbers by footnote, a label or `@` and an anonymous reference's place, and the place
1284    /// of each one's first reference.
1285    private var footnoteNumbers: [String: Int] = [:]
1286    private var firstReferences: [String: Int] = [:]
1287
1288    /// The passes that number footnotes as ox-odt does, `org-export-get-footnote-number` with
1289    /// BODY-FIRST: the references in the body in order, then those in the definitions of
1290    /// these, each definition entered at its first reference.
1291    private enum FootnotePass { case body, definitions }
1292    private var footnotePass: FootnotePass?
1293    private var referencesMet: [(id: String, key: Int)] = []
1294    private var labelsSeen: Set<String> = []
1295    private var definitionsWaiting: [(label: String?, inline: (text: String, base: Int)?)] = []
1296
1297    private func numberFootnotes(_ text: String) {
1298        let pass = ODTRenderer(settings: settings, options: options, directory: directory)
1299        pass.language = language
1300        pass.author = author
1301        pass.dated = dated
1302        pass.numbered = numbered
1303        pass.preserveBreaks = preserveBreaks
1304        pass.withTables = withTables
1305        pass.withEntities = withEntities
1306        pass.drawers = drawers
1307        pass.footnotePass = .body
1308        _ = pass.document(text)
1309        pass.footnotePass = .definitions
1310        for waiting in pass.definitionsWaiting { _ = pass.definition(label: waiting.label, inline: waiting.inline) }
1311        for reference in pass.referencesMet where footnoteNumbers[reference.id] == nil {
1312            footnoteNumbers[reference.id] = footnoteNumbers.count + 1
1313            firstReferences[reference.id] = reference.key
1314        }
1315        definitions = pass.definitions
1316    }
1317
1318    /// A footnote's definition rendered: an anonymous one's own, else the label's.
1319    private func definition(label: String?, inline: (text: String, base: Int)?) -> String? {
1320        if label == nil, let inline { return inlineDefinition(inline.text, base: inline.base) }
1321        guard let label, let found = definitions[label] else { return nil }
1322        if found.inline { return inlineDefinition(found.text, base: found.base) }
1323        return blocks(found.text, base: found.base).trimmingCharacters(in: .whitespacesAndNewlines)
1324    }
1325
1326    private func inlineDefinition(_ text: String, base: Int) -> String {
1327        let rendered = within(text, base: base) { tree -> String in
1328            guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return Self.escape(text) }
1329            return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
1330        }
1331        return "\n<text:p text:style-name=\"Footnote\">\(rendered)</text:p>"
1332    }
1333
1334    private func footnote(_ node: SyntaxNode) -> String {
1335        let text = node.text
1336        guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return plain(text) }
1337        let key = base + node.range.lowerBound
1338        let label = m.1.isEmpty ? nil : String(m.1)
1339        let id = label ?? "@\(key)"
1340        let inline = m.2.map { (text: String($0), base: key + text.utf16.distance(from: text.startIndex, to: $0.startIndex)) }
1341        if let label, let inline, definitions[label].map({ $0.base < inline.base }) ?? true {
1342            definitions[label] = (inline.text, inline.base, true)
1343        }
1344        if let pass = footnotePass {
1345            referencesMet.append((id, key))
1346            if let label, !labelsSeen.insert(label).inserted { return "" }
1347            if pass == .body {
1348                definitionsWaiting.append((label, inline))
1349            } else {
1350                _ = definition(label: label, inline: inline)
1351            }
1352            return ""
1353        }
1354        if footnoteNumbers[id] == nil {
1355            footnoteNumbers[id] = (footnoteNumbers.values.max() ?? 0) + 1
1356            firstReferences[id] = key
1357        }
1358        let n = footnoteNumbers[id]!
1359        if label != nil, firstReferences[id] != key {
1360            return span("OrgSuperscript", "<text:note-ref text:note-class=\"footnote\" text:reference-format=\"text\" text:ref-name=\"fn\(n)\">\(n)</text:note-ref>")
1361        }
1362        let saved = (paragraphStyles, container, frames, afterFootnote)
1363        paragraphStyles = ("Footnote", "OrgFootnoteCenter", "OrgFootnoteQuotations")
1364        container = nil
1365        frames = []
1366        defer { (paragraphStyles, container, frames, afterFootnote) = saved }
1367        guard let definition = definition(label: label, inline: inline) else { return fail("Definition not found for footnote \(m.1)") }
1368        return "<text:note text:id=\"fn\(n)\" text:note-class=\"footnote\"><text:note-citation>\(n)</text:note-citation><text:note-body>\(definition)</text:note-body></text:note>"
1369    }
1370
1371    // MARK: - Links
1372
1373    private enum Destination {
1374        case heading(Heading)
1375        case target(String)
1376        case element(Int)
1377    }
1378
1379    private func titleWords(_ heading: Heading) -> [String] {
1380        let title = heading.info?.title ?? heading.node.firstChild(.title)?.text ?? ""
1381        return Self.words(title.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression).uppercased())
1382    }
1383
1384    /// `org-export-resolve-fuzzy-link`: a target or name first, else the last heading with the
1385    /// title.
1386    private func resolve(_ path: String) -> Destination? {
1387        let all = headingOrder.compactMap { headings[$0] }
1388        if path.hasPrefix("*") {
1389            let words = Self.words(String(path.dropFirst()).uppercased())
1390            return all.last { titleWords($0) == words }.map(Destination.heading)
1391        }
1392        if path.hasPrefix("#") {
1393            let id = String(path.dropFirst())
1394            return all.last { $0.info?.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value == id }.map(Destination.heading)
1395        }
1396        let words = Self.words(path)
1397        let upper = words.map { $0.uppercased() }
1398        if let name = names.last(where: { $0.words == words }) { return .element(name.key) }
1399        if let target = targets.last(where: { $0.words == upper }) { return .target(target.reference) }
1400        if let name = names.last(where: { $0.words == upper }) { return .element(name.key) }
1401        return all.last { titleWords($0) == upper }.map(Destination.heading)
1402    }
1403
1404    private func link(_ node: SyntaxNode) -> String {
1405        let path = Self.linkPath(node)
1406        let descriptionNode = node.firstChild(.linkDescription)
1407        var description = descriptionNode.map(inline).flatMap { $0.isEmpty ? nil : $0 }
1408        // `org-export-insert-image-links`: a description that is an image's path shows it.
1409        let describedImage = descriptionNode.flatMap(Self.describedImage)
1410        if let describedImage, !tocEntry { description = image(describedImage) }
1411        guard let path else {
1412            // A radio link refers to its target.
1413            if !node.text.hasPrefix("<"), !node.text.contains(":") {
1414                let words = Self.words(node.text.uppercased())
1415                let text = plain(node.text)
1416                if tocEntry { return text }
1417                guard let target = targets.first(where: { $0.words == words }) else { return text }
1418                return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(target.reference)\">\(text)</text:bookmark-ref>"
1419            }
1420            var target = node.text
1421            if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
1422            if tocEntry { return plain(target) }
1423            return external(target, description: nil)
1424        }
1425        if tocEntry { return description ?? plain(path) }
1426        if let file = Self.filePath(path) {
1427            if description == nil, Self.isImage(file) { return image(file) }
1428            let uri = file.hasPrefix("/") || file.hasPrefix("~") ? "file://" + OrgPaths.expandingTilde(file) : "../" + file
1429            return external(uri, description: description, image: describedImage != nil)
1430        }
1431        // A code reference: its line's number.
1432        if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
1433            let name = String(path.dropFirst().dropLast())
1434            guard let resolved = documentTree.flatMap({ Coderef.resolve(name, in: $0) }) else { return fail("Unable to resolve code reference: \(name)") }
1435            guard Int(resolved) != nil else { return fail("ODT export only resolves code references to numbered lines: \(name)") }
1436            let reference = "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.coderef-\(Self.escape(name, quotes: true))\">\(resolved)</text:bookmark-ref>"
1437            return Coderef.linkText(reference, description: description)
1438        }
1439        if let colon = path.firstIndex(of: ":"), Links.types.contains(String(path[..<colon])) {
1440            if path.hasPrefix("id:") {
1441                let id = String(path.dropFirst(3))
1442                guard let heading = headingOrder.compactMap({ headings[$0] }).first(where: { $0.info?.id == id }) else { return fail("Unable to resolve link: \"\(id)\"") }
1443                return toHeading(heading, description: description, customID: nil)
1444            }
1445            return external(path, description: description, image: describedImage != nil)
1446        }
1447        let search = path
1448        guard let destination = resolve(search) else { return fail("Unable to resolve link: \"\(search)\"") }
1449        switch destination {
1450        case .heading(let heading):
1451            return toHeading(heading, description: description, customID: search.hasPrefix("#") ? String(search.dropFirst()) : nil)
1452        case .target(let reference):
1453            guard let description else { return fail("ODT export doesn't number links to targets without a description: \(search)") }
1454            return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1455        case .element(let key):
1456            guard let label = labels[key], let reference = label.reference else { return fail("FIXME: Unable to resolve \(search)") }
1457            guard let description else {
1458                return "<text:sequence-ref text:reference-format=\"value\" text:ref-name=\"\(reference)\">\(label.sequence)</text:sequence-ref>"
1459            }
1460            return "<text:a xlink:type=\"simple\" xlink:href=\"#\(reference)\">\(description)</text:a>"
1461        }
1462    }
1463
1464    /// A hyperlink, a clickable image when the description is only an image link.
1465    private func external(_ target: String, description: String?, image: Bool = false) -> String {
1466        let href = Self.escape(target, quotes: true)
1467        if image, let description { return "\n<draw:a xlink:type=\"simple\" xlink:href=\"\(href)\">\n\(description)\n</draw:a>" }
1468        return "<text:a xlink:type=\"simple\" xlink:href=\"\(href)\">\(description ?? Self.escape(target))</text:a>"
1469    }
1470
1471    /// A link to a heading: with a description, a hyperlink; without, its number or title.
1472    private func toHeading(_ heading: Heading, description: String?, customID: String?) -> String {
1473        if let description {
1474            return "<text:a xlink:type=\"simple\" xlink:href=\"#\(Self.escape(customID ?? heading.reference, quotes: true))\">\(description)</text:a>"
1475        }
1476        let chain = (heading.ancestors + [heading.key]).compactMap { headings[$0] }
1477        if chain.dropLast().contains(where: \.lowLevel) { return fail("ODT export doesn't number links to items under a heading deeper than H") }
1478        let regular = chain.reversed().first { !$0.lowLevel }
1479        if heading.number != nil, let numbered = chain.reversed().first(where: { !$0.lowLevel && $0.number != nil }) {
1480            return "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.\(heading.reference)\">\(numbered.number!.map(String.init).joined(separator: "."))</text:bookmark-ref>"
1481        }
1482        guard let regular else { return fail("FIXME?") }
1483        let title = regular.node.firstChild(.title).map { inline($0).trimmingCharacters(in: .whitespaces) } ?? ""
1484        return "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.\(heading.reference)\">\(title)</text:bookmark-ref>"
1485    }
1486
1487    // MARK: - Styles
1488
1489    /// The automatic styles of tables with `#+ATTR_ODT`.
1490    func automaticStyles() -> String {
1491        tableStyles.map {
1492            "\n<style:style style:name=\"\($0.name)\" style:family=\"table\">\n  <style:table-properties style:rel-width=\"\($0.width)%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>\n</style:style>\n"
1493        }.joined()
1494    }
1495
1496    // MARK: - Text
1497
1498    /// `:key value :other "quoted value"`.
1499    static func attributes(_ text: String) -> [String: String] {
1500        var pairs: [String: String] = [:]
1501        for m in text.matches(of: /:([A-Za-z_-]+)(?:[ \t]+("[^"]*"|[^:\s]\S*))?/) {
1502            var value = m.2.map(String.init) ?? "t"
1503            if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { value = String(value.dropFirst().dropLast()) }
1504            pairs[m.1.lowercased()] = value
1505        }
1506        return pairs
1507    }
1508
1509    /// `&`, `<`, `>` (and `"` with `quotes`) escaped, characters XML forbids removed.
1510    static func escape(_ s: String, quotes: Bool = false) -> String {
1511        var out = ""
1512        for c in s.unicodeScalars {
1513            switch c {
1514            case "&": out += "&amp;"
1515            case "<": out += "&lt;"
1516            case ">": out += "&gt;"
1517            case "\"" where quotes: out += "&quot;"
1518            case "\t", "\n", "\r": out.unicodeScalars.append(c)
1519            case _ where c.value < 0x20 || c.value == 0xFFFE || c.value == 0xFFFF: continue
1520            default: out.unicodeScalars.append(c)
1521            }
1522        }
1523        return out
1524    }
1525
1526    /// `org-odt--encode-tabs-and-spaces`.
1527    static func encodeSpaces(_ s: String) -> String {
1528        s.replacing(/\t| {2,}/) { m in m.output == "\t" ? "<text:tab/>" : " <text:s text:c=\"\(m.output.count - 1)\"/>" }
1529    }
1530
1531    /// Rendered markup without its elements, for `meta.xml`.
1532    static func stripped(_ xml: String) -> String {
1533        xml.replacingOccurrences(of: "<[^>]*>", with: "", options: .regularExpression)
1534    }
1535}