Sources/OrgCore/Export/ODTExport.swift

2df4420ff51f7e97a9c06eacf814f64cdb5a4351
orgstar/Sources/OrgCore/Export/ODTExport.swift

1361 lines · 75691 bytes

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