Sources/OrgCore/Export/ASCIIExport.swift

1429 lines · 76404 bytes

   1import Foundation
   2
   3/// Plain text export as ox-ascii (Org 9.8.7) writes it under `emacs -Q`, in its `ascii`,
   4/// `latin1` or `utf-8` charset: a centered title block, a table of contents, underlined and
   5/// numbered headings, links described at the end of their section, footnotes at the end. What
   6/// it can't write as Emacs would throws `Unsupported`, naming the construct, instead of writing
   7/// something else.
   8public enum ASCIIExport {
   9    public typealias Unsupported = LaTeXExport.Unsupported
  10
  11    /// `org-ascii-charset`.
  12    public enum Charset: String, Sendable, CaseIterable {
  13        case ascii, latin1
  14        case utf8 = "utf-8"
  15    }
  16
  17    /// A `.txt` document, or with `bodyOnly` the text without the title block and contents.
  18    /// `author` stands for `user-full-name`, `language` for `org-export-default-language`. `file`
  19    /// adds the final newline `org-export-to-file` writes.
  20    public static func document(
  21        _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), charset: Charset = .ascii,
  22        bodyOnly: Bool = false, author: String = "", language: String = "en", file: Bool = false
  23    ) throws -> String {
  24        let text = try LaTeXExport.expanded(text, settings: settings, path: path, now: now)
  25        let tree = OrgParser.parse(text, defaults: settings)
  26        let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
  27            + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
  28        let renderer = try ASCIIRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language, charset: charset)
  29        var output = try renderer.body()
  30        if !bodyOnly { output = try renderer.template(output, author: author) }
  31        output = output.replacingOccurrences(of: ASCIIRenderer.hardNewline, with: "\n")
  32        return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
  33    }
  34}
  35
  36final class ASCIIRenderer {
  37    typealias Unsupported = LaTeXExport.Unsupported
  38    typealias Inline = LaTeXRenderer.Inline
  39
  40    enum Justify { case left, center, right }
  41
  42    /// Where an element is: the text width `org-ascii--current-text-width` gives it and the
  43    /// justification of the blocks around it.
  44    struct Context {
  45        var width: Int
  46        var justify = Justify.left
  47    }
  48
  49    /// `hard-newline`: a newline that ends a line when filling.
  50    static let hardNewline = ASCIIText.hardNewline + "\n"
  51
  52    static let textWidth = 72
  53    static let innerMargin = 2
  54    static let quoteMargin = 6
  55
  56    let tree: OrgTree
  57    let source: NSString
  58    let settings: OrgSettings
  59    let options: ExportOptions
  60    /// Keyword values by name, in order.
  61    let keywords: [String: [String]]
  62    let language: String
  63    let charset: ASCIIExport.Charset
  64    var utf8: Bool { charset == .utf8 }
  65    let numbered: Bool
  66    let num: Int?
  67    let withTOC: Bool
  68    let toc: Int?
  69    private var selected: Set<Int>?
  70    /// Added to heading levels.
  71    private var levelOffset = 0
  72    private var exportSource: ExportSource
  73    private let model: DocumentModel
  74    /// Section numbers of the numbered headings the export writes, by heading start.
  75    private var numbers: [Int: [Int]] = [:]
  76    /// The headings the export writes, by start, with their relative level.
  77    private var exported: [(start: Int, level: Int)] = []
  78    /// `:ascii-links-to-notes`, off in the title block and footnotes.
  79    private var linksToNotes = true
  80
  81    init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String, charset: ASCIIExport.Charset) throws {
  82        self.tree = tree
  83        source = text as NSString
  84        self.settings = settings
  85        self.charset = charset
  86        exportSource = ExportSource(tree: tree, text: text)
  87        model = DocumentModel(tree: tree)
  88        var keywords: [String: [String]] = [:]
  89        for line in lines {
  90            guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
  91            keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
  92        }
  93        self.keywords = keywords
  94        options = ExportOptions.parse(lines.joined(separator: "\n"))
  95        self.language = keywords["LANGUAGE"]?.last ?? language
  96
  97        // `#+OPTIONS` this export follows; any other item only at its default.
  98        let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
  99                        "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
 100                        "broken-links": "nil", "'": "nil", "d": "(not \"LOGBOOK\")", "expand-links": "t"]
 101        for (key, value) in options.items {
 102            if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
 103        }
 104        let items = options.items
 105        func depth(_ key: String) throws -> (Bool, Int?) {
 106            guard let v = items[key] else { return (true, nil) }
 107            if v == "nil" { return (false, nil) }
 108            if v == "t" { return (true, nil) }
 109            guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
 110            return (true, n)
 111        }
 112        (numbered, num) = try depth("num")
 113        (withTOC, toc) = try depth("toc")
 114        if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
 115        for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "CALL"] where keywords[key] != nil {
 116            throw Unsupported(reason: "#+\(key)")
 117        }
 118        // Radio links: links that are only words.
 119        if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
 120            throw Unsupported(reason: "Radio targets")
 121        }
 122        let kinds = Set(tree.root.descendants().map(\.kind))
 123        for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
 124                             (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
 125                             (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
 126            throw Unsupported(reason: name)
 127        }
 128        // Emacs measures text in columns, where these take two or none.
 129        if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
 130        // Tabs fill and align by column; in code they are copied.
 131        let code = tree.root.descendants().filter { $0.kind == .block && $0.text.firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b/) != nil }.map(\.range)
 132        if Array(text.utf16).enumerated().contains(where: { offset, unit in unit == 9 && !code.contains { $0.contains(offset) } }) {
 133            throw Unsupported(reason: "Tabs outside code")
 134        }
 135        // A definition goes on to the next one, a heading or two blank lines.
 136        for node in tree.root.descendants() where node.kind == .footnoteDefinition {
 137            guard let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count else { continue }
 138            let next = parent.children[index + 1]
 139            let gap = (text as NSString).substring(with: NSRange(location: node.range.lowerBound, length: next.range.lowerBound - node.range.lowerBound))
 140            if next.kind != .footnoteDefinition, next.kind != .section, !gap.hasSuffix("\n\n\n") {
 141                throw Unsupported(reason: "Footnote definitions of several paragraphs")
 142            }
 143        }
 144        for heading in model.headings {
 145            let keys = heading.properties.map { $0.key.uppercased() }
 146            if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
 147        }
 148        selected = HTMLRenderer.selection(tree, tags: options.selectTags)
 149        let options = options
 150        let selected = selected
 151        let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
 152            .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
 153        levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
 154        collectHeadings(tree.root.children)
 155    }
 156
 157    static func isWideOrZeroWidth(_ s: Unicode.Scalar) -> Bool { isWide(s) || isZeroWidth(s) }
 158
 159    static func isWide(_ s: Unicode.Scalar) -> Bool {
 160        switch s.value {
 161        case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3,
 162             0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD:
 163            return true
 164        default:
 165            return false
 166        }
 167    }
 168
 169    static func isZeroWidth(_ s: Unicode.Scalar) -> Bool {
 170        switch s.value {
 171        case 0x200B...0x200F, 0xFE00...0xFE0F: return true
 172        default: return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark
 173        }
 174    }
 175
 176    /// `string-width`.
 177    static func width(_ s: String) -> Int {
 178        s.unicodeScalars.reduce(0) { $0 + (isWide($1) ? 2 : isZeroWidth($1) ? 0 : 1) }
 179    }
 180
 181    /// `org-export--collect-headline-numbering` over the headings the export writes.
 182    private func collectHeadings(_ nodes: [SyntaxNode]) {
 183        var counters: [Int] = []
 184        func walk(_ nodes: [SyntaxNode]) {
 185            for node in nodes where node.kind == .section {
 186                guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { continue }
 187                let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
 188                if export == .nothing { continue }
 189                let level = self.level(heading)
 190                exported.append((heading.range.lowerBound, level))
 191                if isNumbered(level) {
 192                    while counters.count < level { counters.append(0) }
 193                    counters[level - 1] += 1
 194                    for deeper in level..<counters.count { counters[deeper] = 0 }
 195                    numbers[heading.range.lowerBound] = Array(counters.prefix(level))
 196                }
 197                if export == .all { walk(node.children) }
 198            }
 199        }
 200        walk(nodes)
 201    }
 202
 203    private func isFootnoteSection(_ heading: SyntaxNode) -> Bool { heading.firstChild(.title)?.text == "Footnotes" }
 204
 205    private func level(_ heading: SyntaxNode) -> Int {
 206        (heading.tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
 207    }
 208
 209    private func isNumbered(_ level: Int) -> Bool { numbered && (num.map { level <= $0 } ?? true) }
 210
 211    // MARK: - Template
 212
 213    /// `org-ascii-template`: the title block and table of contents before `body`.
 214    func template(_ body: String, author: String) throws -> String {
 215        var out = try titleBlock(author: author)
 216        if withTOC { out += try tableOfContents(depth: toc, width: Self.textWidth, keyword: false) + "\n\n\n" }
 217        return out + body
 218    }
 219
 220    /// `org-ascii-template--document-title`.
 221    private func titleBlock(author defaultAuthor: String) throws -> String {
 222        let width = Self.textWidth
 223        linksToNotes = false
 224        defer { linksToNotes = true }
 225        let title = options.title ? try keywords["TITLE"].map(parsed) ?? "" : ""
 226        let subtitle = options.title ? try keywords["SUBTITLE"].map(parsed) ?? "" : ""
 227        var author: String?
 228        if options.author { author = try keywords["AUTHOR"].map(parsed) ?? (defaultAuthor.isEmpty ? nil : try inlineString(defaultAuthor)) }
 229        let date = options.date ? try keywords["DATE"].map(parsed) : nil
 230        func nw(_ s: String?) -> String? { s.flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil } }
 231        if title.isEmpty {
 232            switch (nw(date), nw(author)) {
 233            case (let date?, let author?):
 234                return author + String(repeating: " ", count: max(0, width - date.count - author.count)) + date + "\n\n\n"
 235            case (let date?, nil):
 236                return Self.justifyLines(date, width: width, .right) + "\n\n\n"
 237            case (nil, let author?):
 238                return author + "\n\n\n"
 239            default:
 240                return ""
 241            }
 242        }
 243        let titleLength = min((title + "\n" + subtitle).components(separatedBy: "\n").map(\.count).max() ?? 0, 2 * width / 3)
 244        let formattedTitle = ASCIIText.fill(title, width: titleLength)
 245        let formattedSubtitle = nw(subtitle).map { ASCIIText.fill($0, width: titleLength) }
 246        let line = String(repeating: utf8 ? "━" : "_", count: min(max(titleLength, author?.count ?? 0) + 2, width))
 247        var block = line + "\n" + (utf8 ? "" : "\n") + formattedTitle.uppercased()
 248        if let formattedSubtitle { block += "\n" + formattedSubtitle }
 249        if let author = nw(author) { block += "\n\n" + author }
 250        block += "\n" + line
 251        if let date = nw(date) { block += "\n\n\n" + date }
 252        return Self.justifyLines(block + "\n\n\n", width: width, .center)
 253    }
 254
 255    /// A keyword parsed as Org text, its lines joined with spaces.
 256    private func parsed(_ values: [String]) throws -> String {
 257        if values.count > 1, values.contains("") { throw Unsupported(reason: "Repeated keywords with an empty value") }
 258        return try inlineString(values.joined(separator: " "))
 259    }
 260
 261    /// `org-ascii--build-toc` over the whole document.
 262    private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String {
 263        let title = translate("Table of Contents")
 264        var out = title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n"
 265        let limit = min(depth ?? options.headlineLevels, options.headlineLevels)
 266        var lines: [String] = []
 267        for (start, level) in exported where level <= limit {
 268            guard let heading = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == start }) else { continue }
 269            let indent = (level - 1) * 3
 270            let prefix = indent == 0 ? "" : String(repeating: ".", count: indent - 1) + " "
 271            lines.append(prefix + (try buildTitle(heading, width: width - indent, underline: false, notags: !options.tags || !options.tagsInTOC, toc: true)))
 272        }
 273        out += lines.joined(separator: "\n")
 274        _ = keyword
 275        return out
 276    }
 277
 278    // MARK: - Strings
 279
 280    /// `org-ascii--translate`.
 281    func translate(_ term: String) -> String {
 282        ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii)
 283    }
 284
 285    /// A translation for text that is filled, which counts characters, not columns.
 286    func translateFilled(_ term: String) throws -> String {
 287        let text = translate(term)
 288        if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
 289        return text
 290    }
 291
 292    /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs`
 293    /// indents as `fill-region` does, with tabs where they fit.
 294    static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String {
 295        guard how != .left else { return s }
 296        return s.components(separatedBy: "\n").map { line in
 297            let trimmed = line.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
 298            guard !trimmed.isEmpty else { return trimmed }
 299            let room = width - trimmed.count
 300            let indent = max(0, how == .center ? room / 2 : room)
 301            return (tabs ? Self.indentation(indent) : String(repeating: " ", count: indent)) + trimmed
 302        }.joined(separator: "\n")
 303    }
 304
 305    /// `org-ascii--justify-element` for anything but a paragraph: the lines moved as a block
 306    /// so the widest is centered or flushed right.
 307    static func justifyBlock(_ s: String, context: Context) -> String {
 308        guard context.justify != .left, s.contains(where: { !$0.isWhitespace }) else { return s }
 309        let lines = s.components(separatedBy: "\n")
 310        var widest = 0
 311        for line in lines where line.contains(where: { $0 != " " && $0 != "\t" }) {
 312            if line.count >= context.width { return s }
 313            widest = max(widest, line.count)
 314        }
 315        let offset = (context.width - widest) / (context.justify == .right ? 1 : 2)
 316        guard offset > 0 else { return s }
 317        return lines.map { line in
 318            line.contains(where: { $0 != " " && $0 != "\t" }) ? indentation(offset) + line : line
 319        }.joined(separator: "\n")
 320    }
 321
 322    /// `indent-to` from the line start with `indent-tabs-mode`.
 323    static func indentation(_ columns: Int) -> String {
 324        String(repeating: "\t", count: columns / 8) + String(repeating: " ", count: columns % 8)
 325    }
 326
 327    /// `org-ascii--box-string`.
 328    func box(_ s: String) -> String {
 329        let body = s.replacing(#/\n[ \t]*\z/#, with: "")
 330        let bar = utf8 ? "│ " : "| "
 331        // `replace-regexp-in-string' finds no line start in the empty string.
 332        let lines = body.isEmpty ? "" : body.components(separatedBy: "\n").map { bar + $0 }.joined(separator: "\n")
 333        return utf8 ? "┌────\n" + lines + "\n└────" : ",----\n" + lines + "\n`----"
 334    }
 335
 336    /// `org-element-normalize-string`.
 337    static func normalize(_ s: String) -> String { LaTeXRenderer.normalize(s) }
 338
 339    /// The headline and section filter: whatever blank lines end `s`, two.
 340    static func spaced(_ s: String) -> String {
 341        var end = s.endIndex
 342        var cut: String.Index?
 343        while end > s.startIndex {
 344            let before = s.index(before: end)
 345            if s[before] == " " || s[before] == "\t" {
 346                end = before
 347            } else if s[before] == "\n" {
 348                end = before
 349                cut = before
 350            } else {
 351                break
 352            }
 353        }
 354        guard let cut else { return s }
 355        return String(s[..<cut]) + "\n\n\n"
 356    }
 357
 358    // MARK: - Document
 359
 360    /// The transcoded document with its footnotes, `org-ascii-inner-template`.
 361    func body() throws -> String {
 362        var nodes = tree.root.children
 363        // With a select tag, the text before the first heading isn't exported.
 364        if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
 365        var out = ""
 366        for node in nodes {
 367            if node.kind == .zerothSection {
 368                out += try section(node.children, end: node.range.upperBound, heading: nil)
 369            } else if node.kind == .section {
 370                out += try headline(node) ?? ""
 371            }
 372        }
 373        out = Self.normalize(out)
 374        let notes = try footnotes()
 375        if !notes.isEmpty {
 376            let title = translate("Footnotes")
 377            out += "\n\n\n" + title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n" + notes
 378        }
 379        return Self.normalize(out)
 380    }
 381
 382    /// Blank lines at the end of `source[from..<to]`.
 383    func blankLines(from: Int, to: Int) -> Int {
 384        guard to > from else { return 0 }
 385        let source = currentSource ?? self.source
 386        let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
 387        return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
 388    }
 389
 390    /// The text being transcoded when it isn't the document: a block's contents.
 391    private var currentSource: NSString?
 392
 393    /// A section's elements as `org-ascii-section` writes them, the section filter applied: its
 394    /// contents indented under a heading, then for the text before the first heading the
 395    /// links it holds. `heading` is the relative level of the heading above, nil for none.
 396    private func section(_ nodes: [SyntaxNode], end: Int, heading: Int?) throws -> String {
 397        let low = heading.map { $0 > options.headlineLevels }
 398        let width = Self.textWidth - (heading.map { $0 > options.headlineLevels ? ($0 - options.headlineLevels) * 2 : Self.innerMargin } ?? 0)
 399        let linkStart = noted.count
 400        var contents = try elements(nodes, end: end, context: Context(width: width))
 401        if heading == nil {
 402            let links = try describeLinks(from: linkStart, width: width)
 403            if !links.isEmpty { contents = Self.normalize(contents) + "\n\n" + links }
 404        }
 405        if heading != nil, low == false { contents = ASCIIText.indent(contents, Self.innerMargin) }
 406        return Self.spaced(Self.normalize(contents))
 407    }
 408
 409    /// `org-ascii-headline`, the headline filter applied; nil when not exported.
 410    private func headline(_ node: SyntaxNode) throws -> String? {
 411        guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { return nil }
 412        let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
 413        if export == .nothing { return nil }
 414        let level = self.level(heading)
 415        let low = level > options.headlineLevels ? level - options.headlineLevels : nil
 416        let width = Self.textWidth - (low.map { $0 * 2 } ?? 0)
 417        let linkStart = noted.count
 418        let title = try buildTitle(heading, width: width, underline: low == nil, notags: false, toc: false)
 419        var body = ""
 420        if export == .all {
 421            let children = node.children.filter { $0.kind != .heading }
 422            let elements = children.filter { $0.kind != .section }
 423            let subsections = children.filter { $0.kind == .section }
 424            var sectionText: String?
 425            if !elements.isEmpty {
 426                let end = subsections.first?.range.lowerBound ?? node.range.upperBound
 427                sectionText = try section(elements, end: end, heading: level)
 428            }
 429            let links = try describeLinks(from: linkStart, width: width)
 430            let sub = try subsections.compactMap { try headline($0) }.joined()
 431            if links.isEmpty {
 432                body = (sectionText ?? "") + sub
 433            } else {
 434                body = (sectionText.map { Self.normalize($0) + "\n\n" } ?? "") + links + sub
 435            }
 436        } else {
 437            _ = try? describeLinks(from: linkStart, width: width)
 438        }
 439        let out: String
 440        if let low {
 441            let bullets: [Character] = switch charset {
 442            case .ascii: ["*", "+", "-"]
 443            case .latin1: ["§", ""]
 444            case .utf8: ["◊"]
 445            }
 446            let bullet = "\(bullets[(low - 1) % bullets.count]) "
 447            out = bullet + title + "\n\n" + ASCIIText.indent(body, bullet.count)
 448        } else {
 449            out = title + "\n\n" + body
 450        }
 451        return Self.spaced(Self.normalize(out))
 452    }
 453
 454    /// `org-ascii--build-title` for a heading.
 455    private func buildTitle(_ heading: SyntaxNode, width: Int, underline: Bool, notags: Bool, toc: Bool) throws -> String {
 456        let tokens = heading.tokens
 457        let level = self.level(heading)
 458        var first = ""
 459        if let number = numbers[heading.range.lowerBound] {
 460            first += toc ? "\(number.last!). " : number.map(String.init).joined(separator: ".") + " "
 461        }
 462        if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text { first += plainText(todo) + " " }
 463        if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text, let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
 464            first += "(#\(letter)) "
 465        }
 466        let titleNode = heading.firstChild(.title)
 467        if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
 468        first += try titleText(heading, toc: toc)
 469        var out = first
 470        if !notags, options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
 471            let names = tags.split(separator: ":").map(String.init)
 472            if !names.isEmpty {
 473                let tagString = ":" + names.joined(separator: ":") + ":"
 474                let column = max(width - (first.count + 1), tagString.count)
 475                out += " " + String(repeating: " ", count: column - tagString.count) + tagString
 476            }
 477        }
 478        let underlines: [Character] = switch charset {
 479        case .ascii, .latin1: ["=", "~", "-"]
 480        case .utf8: ["═", "─", "╌", "┄", "┈"]
 481        }
 482        if underline, level <= underlines.count {
 483            out += "\n" + String(repeating: underlines[level - 1], count: first.count)
 484        }
 485        return out
 486    }
 487
 488    /// A heading's title transcoded and trimmed, once: links in it are noted where it is first
 489    /// written.
 490    private func titleText(_ heading: SyntaxNode, toc: Bool) throws -> String {
 491        if let cached = titles[heading.range.lowerBound] { return cached }
 492        let text = try heading.firstChild(.title).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
 493        titles[heading.range.lowerBound] = text
 494        return text
 495    }
 496
 497    private var titles: [Int: String] = [:]
 498
 499    // MARK: - Elements
 500
 501    /// Affiliated keywords of the element being transcoded.
 502    typealias Affiliated = LaTeXRenderer.Affiliated
 503
 504    private func blockType(_ node: SyntaxNode) -> String {
 505        node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
 506    }
 507
 508    /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
 509    /// `org-export-data` joins a greater element's contents.
 510    /// `firstParagraph` says which paragraph's first line follows a bullet; `written` hears
 511    /// what each element wrote.
 512    func elements(
 513        _ nodes: [SyntaxNode], end: Int, context: Context,
 514        firstParagraph: ((SyntaxNode) -> Bool)? = nil, written: ((SyntaxNode, String) -> Void)? = nil
 515    ) throws -> String {
 516        var out = ""
 517        var affiliated = Affiliated()
 518        // The element before and its blank lines, which a comment after it may add to; they
 519        // show only when it wrote something.
 520        var pendingBlank = 0
 521        var previous: SyntaxNode?
 522        var previousWrote = false
 523        var afterSrc = false
 524        for (index, node) in nodes.enumerated() {
 525            let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
 526            if node.kind == .affiliatedKeyword {
 527                let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
 528                guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
 529                let key = m.1.uppercased()
 530                if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
 531                switch key {
 532                case "CAPTION":
 533                    if m.2 != nil { throw Unsupported(reason: "Short captions") }
 534                    affiliated.caption.append(String(m.3))
 535                case "NAME": affiliated.name = String(m.3)
 536                case "ATTR_ASCII": affiliated.attr.append(String(m.3))
 537                case "RESULTS": affiliated.results = String(m.3)
 538                default: break
 539                }
 540                continue
 541            }
 542            defer { affiliated = Affiliated() }
 543            // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
 544            // the block too, as if they had never been there.
 545            if node.kind == .block, blockType(node) == "src" {
 546                let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
 547                if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
 548                afterSrc = true
 549                if exports == "none" { continue }
 550            } else if let results = affiliated.results {
 551                if afterSrc {
 552                    afterSrc = false
 553                    continue
 554                }
 555                if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
 556                if affiliated.name == nil { affiliated.name = results }
 557            } else {
 558                afterSrc = false
 559            }
 560            if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
 561                // `org-export--skip-p`: the element before keeps at least one blank line.
 562                if previous != nil {
 563                    let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
 564                    if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
 565                    pendingBlank = blank
 566                }
 567                continue
 568            }
 569            let result: String?
 570            if node.kind == .paragraph, let firstParagraph {
 571                result = try paragraph(node, context: context, ignoreFirst: firstParagraph(node))
 572            } else {
 573                result = try element(node, affiliated: affiliated, context: context)
 574            }
 575            guard let result else {
 576                if !pruned(node) {
 577                    previous = node
 578                    previousWrote = false
 579                    pendingBlank = blankLines(from: node.range.lowerBound, to: next)
 580                }
 581                continue
 582            }
 583            previous = node
 584            previousWrote = true
 585            pendingBlank = blankLines(from: node.range.lowerBound, to: next)
 586            written?(node, result)
 587            out += Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
 588        }
 589        return out
 590    }
 591
 592    /// Elements `org-export--prune-tree` takes out of the tree.
 593    private func pruned(_ node: SyntaxNode) -> Bool {
 594        switch node.kind {
 595        case .planning, .propertyDrawer, .clock: return true
 596        case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
 597        case .latexEnvironment: return !options.tex
 598        default: return false
 599        }
 600    }
 601
 602    private func drawerName(_ node: SyntaxNode) -> String {
 603        node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
 604    }
 605
 606    /// One element's transcoding, nil for none.
 607    private func element(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
 608        switch node.kind {
 609        case .paragraph:
 610            return try paragraph(node, context: context, ignoreFirst: false)
 611        case .plainList:
 612            return try list(node, context: context)
 613        case .table:
 614            return try table(node, affiliated: affiliated, context: context)
 615        case .block:
 616            return try block(node, affiliated: affiliated, context: context)
 617        case .fixedWidth:
 618            let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in
 619                let trimmed = line.drop { $0 == " " || $0 == "\t" }
 620                return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1))
 621            }
 622            return Self.justifyBlock(box(try LaTeXRenderer.removeIndentation(lines.joined(separator: "\n"))), context: context)
 623        case .horizontalRule:
 624            let width = affiliated.value("width").flatMap { $0.allSatisfy(\.isNumber) ? Int($0) : nil } ?? context.width
 625            return Self.justifyLines(String(repeating: utf8 ? "―" : "-", count: width), width: context.width, .center)
 626        case .drawer:
 627            if drawerName(node).uppercased() == "LOGBOOK" { return nil }
 628            guard hasContents(node.children) else { return nil }
 629            return Self.normalize(try elements(node.children, end: node.range.upperBound, context: context))
 630        case .dynamicBlock:
 631            let lines = node.text.components(separatedBy: "\n")
 632            return try blockContents(Array(lines.dropFirst().dropLast(2)), context: context)
 633        case .latexEnvironment:
 634            guard options.tex else { return nil }
 635            return Self.justifyBlock(try LaTeXRenderer.removeIndentation(node.text), context: context)
 636        case .keyword:
 637            return try keyword(node, context: context)
 638        case .planning, .propertyDrawer, .clock, .footnoteDefinition:
 639            return nil
 640        default:
 641            throw Unsupported(reason: "\(node.kind)")
 642        }
 643    }
 644
 645    /// Whether `nodes` hold an element the export keeps.
 646    private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
 647        nodes.indices.contains { index in
 648            let node = nodes[index]
 649            switch node.kind {
 650            case .comment: return false
 651            case .affiliatedKeyword:
 652                // Org parses affiliated keywords with no element right after them as keywords.
 653                var last = index
 654                while last + 1 < nodes.count, nodes[last + 1].kind == .affiliatedKeyword,
 655                      nodes[last].range.upperBound == nodes[last + 1].range.lowerBound { last += 1 }
 656                return last + 1 == nodes.count || nodes[last].range.upperBound != nodes[last + 1].range.lowerBound
 657            case .block:
 658                let type = blockType(node)
 659                if type == "comment" { return false }
 660                if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
 661                return !isResults(node)
 662            default: return !pruned(node)
 663            }
 664        }
 665    }
 666
 667    private func keyword(_ node: SyntaxNode, context: Context) throws -> String? {
 668        guard let m = node.text.firstMatch(of: /^[ \t]*#\+([^:\s]+):[ \t]*(.*?)[ \t]*\n?$/) else { return nil }
 669        let value = String(m.2)
 670        switch m.1.uppercased() {
 671        case "ASCII":
 672            return Self.justifyBlock(value, context: context)
 673        case "TOC":
 674            guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else {
 675                throw Unsupported(reason: "#+TOC: \(value)")
 676            }
 677            if value.range(of: "\\blocal\\b|:target", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: \(value)") }
 678            let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) }
 679            return Self.justifyBlock(try tableOfContents(depth: depth, width: context.width, keyword: true), context: context)
 680        default:
 681            return nil
 682        }
 683    }
 684
 685    // MARK: Paragraphs
 686
 687    private func paragraph(_ node: SyntaxNode, context: Context, ignoreFirst: Bool, prefix: String = "") throws -> String {
 688        // `:with-timestamps` decides on timestamps alone in a paragraph.
 689        isolatedTimestamps = ASCIIText.isolatedTimestamps(node)
 690        defer { isolatedTimestamps = false }
 691        let items = LaTeXRenderer.normalizeIndentation(inlineItems(node), ignoreFirst: ignoreFirst)
 692        // `org-remove-blank-lines`, whose newline isn't a hard one.
 693        let contents = (prefix + (try transcode(items))).replacing(#/\x{1}?\n(?:[ \t]*\x{1}?\n)+/#, with: "\n")
 694        guard contents.contains(where: { !$0.isWhitespace && $0 != "\u{1}" }) else { return contents }
 695        return Self.fill(contents.replacingOccurrences(of: Self.hardNewline, with: ASCIIText.hardNewline), context: context)
 696    }
 697
 698    /// `org-ascii--fill-string` with the context's justification.
 699    static func fill(_ s: String, context: Context) -> String {
 700        let filled = ASCIIText.fill(s, width: context.width)
 701        return justifyLines(filled, width: context.width, context.justify, tabs: true)
 702    }
 703
 704    // MARK: Lists
 705
 706    private func list(_ node: SyntaxNode, context: Context) throws -> String {
 707        let items = node.children.filter { $0.kind == .item }
 708        guard let first = items.first else { return "" }
 709        let firstBullet = (first.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
 710        let ordered = firstBullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
 711        let descriptive = !ordered && first.firstChild(.itemTag) != nil
 712        var out = ""
 713        var number = 0
 714        for (index, item) in items.enumerated() {
 715            let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
 716            let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
 717            let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text.uppercased() {
 718            case "[X]"?: utf8 ? "☑ " : "[X] "
 719            case "[ ]"?: utf8 ? "☐ " : "[ ] "
 720            case "[-]"?: utf8 ? "☒ " : "[-] "
 721            default: ""
 722            }
 723            let bullet: String
 724            if descriptive {
 725                let tag = try item.firstChild(.itemTag).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
 726                bullet = checkbox + tag
 727            } else if ordered {
 728                if let counter = item.tokens.first(where: { $0.kind == .counter })?.text {
 729                    guard let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) else { throw Unsupported(reason: "Alphabetical counters") }
 730                    number = n
 731                } else {
 732                    number += 1
 733                }
 734                bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " "
 735            } else {
 736                bullet = utf8 ? (["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " ") : bulletText + " "
 737            }
 738            let indentation = descriptive ? Self.quoteMargin : bullet.count
 739            let inner = Context(width: context.width - (descriptive ? Self.quoteMargin : bullet.count + checkbox.count), justify: context.justify)
 740            let children = item.children.filter { $0.kind != .itemTag }
 741            if children.isEmpty { throw Unsupported(reason: "Empty list items") }
 742            let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
 743            var firstWriter: SyntaxNode?
 744            let contents = try elements(children, end: item.range.upperBound, context: inner, firstParagraph: { paragraph in
 745                paragraph.range == children[0].range && paragraph.range.lowerBound < NSMaxRange(bulletLine)
 746            }, written: { node, text in
 747                if firstWriter == nil, text.contains(where: { !$0.isWhitespace }) { firstWriter = node }
 748            })
 749            if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") }
 750            let indented = ASCIIText.indent(children.isEmpty ? "" : Self.normalize(contents), indentation)
 751            var text = bullet + checkbox
 752            if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstWriter?.kind == .paragraph {
 753                text += LaTeXRenderer.trim(indented)
 754            } else {
 755                text += "\n" + indented
 756            }
 757            out += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
 758        }
 759        return out
 760    }
 761
 762    // MARK: Tables
 763
 764    private func table(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String {
 765        let rows = node.children.filter { $0.kind == .tableRow }
 766        // Each row's cells, nil for a rule.
 767        let raw: [[SyntaxNode]?] = rows.map { row in
 768            let cells = row.children.filter { $0.kind == .tableCell }
 769            return cells.isEmpty ? nil : cells
 770        }
 771        let cookie = /^<[lrc]?[0-9]*>$/
 772        func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: CharacterSet(charactersIn: " |\n")) }
 773        // Rows of only alignment cookies and empty cells.
 774        let special = raw.map { cells -> Bool in
 775            guard let cells else { return false }
 776            let values = cells.map(value)
 777            return values.contains { $0.wholeMatch(of: cookie) != nil } && values.allSatisfy { $0.isEmpty || $0.wholeMatch(of: cookie) != nil }
 778        }
 779        for cells in raw.compactMap({ $0 }) {
 780            let first = value(cells[0])
 781            if first == "/" || ["#", "!", "$", "*", "_", "^"].contains(first) { throw Unsupported(reason: "Tables with special columns or column groups") }
 782        }
 783        // Transcoded cells.
 784        var data: [[String]?] = []
 785        for (r, cells) in raw.enumerated() {
 786            guard let cells, !special[r] else { data.append(nil); continue }
 787            data.append(try cells.map { try LaTeXRenderer.trim(transcode(inlineItems($0, trimmed: true))) })
 788        }
 789        let columns = raw.compactMap { $0?.count }.max() ?? 0
 790        var widths = Array(repeating: 0, count: columns)
 791        var cookieWidth = Array(repeating: Int?.none, count: columns)
 792        var cookieAlign = Array(repeating: String?.none, count: columns)
 793        for (r, cells) in raw.enumerated() where special[r] {
 794            for (c, cell) in cells!.enumerated() {
 795                guard let m = value(cell).wholeMatch(of: /<([lrc])?([0-9]+)?>/) else { continue }
 796                if let w = m.2.flatMap({ Int($0) }), cookieWidth[c] == nil { cookieWidth[c] = w }
 797                if let a = m.1 { cookieAlign[c] = String(a) }
 798            }
 799        }
 800        for row in data.compactMap({ $0 }) { for (c, cell) in row.enumerated() { widths[c] = max(widths[c], cell.count) } }
 801        for c in 0..<columns { if let w = cookieWidth[c] { widths[c] = max(widths[c], w) } }
 802        let number = LaTeXRenderer.numberPattern
 803        let align: [Justify] = (0..<columns).map { c in
 804            switch cookieAlign[c] {
 805            case "l": return .left
 806            case "r": return .right
 807            case "c": return .center
 808            default: break
 809            }
 810            var numbers = 0
 811            var total = 0
 812            var previousNumber = false
 813            for (r, row) in data.enumerated() where raw[r] != nil && !special[r] {
 814                let cell = c < row!.count ? row![c] : ""
 815                total += 1
 816                let isNumber = number.firstMatch(in: cell, range: NSRange(cell.startIndex..., in: cell)) != nil || (cell.isEmpty && previousNumber)
 817                previousNumber = isNumber
 818                if isNumber { numbers += 1 }
 819            }
 820            return total > 0 && Double(numbers) / Double(total) >= 0.5 ? .right : .left
 821        }
 822        let standard = data.indices.filter { data[$0] != nil }
 823        var out = ""
 824        for (position, r) in standard.enumerated() {
 825            let row = data[r]!
 826            let ruleAbove = raw[(position == 0 ? 0 : standard[position - 1] + 1)..<r].contains { $0 == nil }
 827            let ruleBelow = raw[(r + 1)..<(position + 1 < standard.count ? standard[position + 1] : raw.count)].contains { $0 == nil }
 828            func hline(_ char: String) -> String { row.indices.map { String(repeating: char, count: widths[$0] + 2) }.joined() + "\n" }
 829            if position == 0, utf8 || ruleAbove {
 830                out += hline(utf8 ? "━" : "-")
 831            } else if position > 0, ruleAbove {
 832                out += hline(utf8 ? "─" : "-")
 833            }
 834            out += row.enumerated().map { c, cell in
 835                let pad = widths[c] - cell.count
 836                let justified: String = switch align[c] {
 837                case .left: cell + String(repeating: " ", count: pad)
 838                case .right: String(repeating: " ", count: pad) + cell
 839                case .center: String(repeating: " ", count: pad / 2) + cell + String(repeating: " ", count: pad - pad / 2)
 840                }
 841                return " " + justified + " "
 842            }.joined() + "\n"
 843            if position == standard.count - 1, utf8 || ruleBelow { out += hline(utf8 ? "━" : "-") }
 844        }
 845        let caption = try buildCaption(affiliated, type: "Table %d:", counter: &tableCount, context: context)
 846        return Self.justifyBlock(out + (caption ?? ""), context: context)
 847    }
 848
 849    private var isolatedTimestamps = false
 850    private var tableCount = 0
 851    private var listingCount = 0
 852
 853    /// `org-ascii--build-caption`.
 854    private func buildCaption(_ affiliated: Affiliated, type: String, counter: inout Int, context: Context) throws -> String? {
 855        guard !affiliated.caption.isEmpty else { return nil }
 856        if affiliated.caption.count > 1 { throw Unsupported(reason: "Several captions") }
 857        counter += 1
 858        let saved = noting
 859        noting = false
 860        defer { noting = saved }
 861        let text = try inlineString(affiliated.caption[0])
 862        return ASCIIText.fill(try translateFilled(type).replacingOccurrences(of: "%d", with: String(counter)) + " " + text, width: context.width)
 863    }
 864
 865    // MARK: Blocks
 866
 867    private func block(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
 868        var lines = node.text.components(separatedBy: "\n")
 869        if lines.last == "" { lines.removeLast() }
 870        guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
 871        let type = m.1.lowercased()
 872        let parameters = String(m.2)
 873        let body = Array(lines.dropFirst().dropLast())
 874        let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 875        let text = unescaped.joined(separator: "\n")
 876        switch type {
 877        case "src", "example":
 878            let code = try formatCode(lines)
 879            var out = box(code)
 880            if type == "src", let caption = try buildCaption(affiliated, type: "Listing %d:", counter: &listingCount, context: context) {
 881                out += "\n" + caption
 882            }
 883            return Self.justifyBlock(out, context: context)
 884        case "quote":
 885            guard let contents = try blockContents(unescaped, context: Context(width: context.width - 2 * Self.quoteMargin, justify: context.justify)) else { return nil }
 886            return ASCIIText.indent(contents, Self.quoteMargin)
 887        case "center":
 888            return try blockContents(unescaped, context: Context(width: context.width, justify: .center))
 889        case "verse":
 890            return ASCIIText.indent(Self.justifyBlock(try verse(unescaped), context: context), Self.quoteMargin)
 891        case "export":
 892            let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
 893            guard backend == "ASCII" else { return nil }
 894            return Self.justifyBlock(text + "\n", context: context)
 895        case "comment":
 896            return nil
 897        default:
 898            var inner = context
 899            if m.1 == "JUSTIFYRIGHT" { inner.justify = .right }
 900            if m.1 == "JUSTIFYLEFT" { inner.justify = .left }
 901            return try blockContents(unescaped, context: inner)
 902        }
 903    }
 904
 905    /// A greater block's contents, parsed as elements; nil when it has none.
 906    private func blockContents(_ lines: [String], context: Context) throws -> String? {
 907        guard !lines.isEmpty else { return nil }
 908        if lines[0].allSatisfy({ $0 == " " || $0 == "\t" }) { throw Unsupported(reason: "Blocks opening with a blank line") }
 909        let text = lines.joined(separator: "\n") + "\n"
 910        let tree = OrgParser.parse(text, defaults: settings)
 911        let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
 912        if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
 913        let saved = (currentSource, exportSource)
 914        currentSource = text as NSString
 915        exportSource = ExportSource(tree: tree, text: text)
 916        defer { (currentSource, exportSource) = saved }
 917        guard hasContents(nodes) else { return nil }
 918        return Self.normalize(try elements(nodes, end: (text as NSString).length, context: context))
 919    }
 920
 921    /// `org-export-format-code-default` for a src or example block's lines.
 922    private func formatCode(_ lines: [String]) throws -> String {
 923        guard let parsed = Coderef.block(lines) else { return "\n" }
 924        let blockLoc = try blockLoc(lines, numbered: parsed.switches.numberLines != nil)
 925        var value = parsed.body.joined(separator: "\n")
 926        if !value.isEmpty { value += "\n" }
 927        let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
 928        var code = preserve ? value : try LaTeXRenderer.removeIndentation(value)
 929        // Emacs writes a src block's leading tabs as spaces.
 930        if !preserve, lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_src)\b/) != nil {
 931            code = code.components(separatedBy: "\n").map { line in
 932                var column = 0
 933                let indentation = line.prefix { $0 == " " || $0 == "\t" }
 934                for c in indentation { column = c == "\t" ? (column / 8 + 1) * 8 : column + 1 }
 935                return String(repeating: " ", count: column) + line.dropFirst(indentation.count)
 936            }.joined(separator: "\n")
 937        }
 938        if code.hasSuffix("\n") { code.removeLast() }
 939        let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
 940        let loc = parsed.switches.numberLines == nil ? nil : blockLoc
 941        guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
 942        let width = loc.map { String($0 + lines.count).count } ?? 0
 943        let numberWidth = loc == nil ? 0 : width + 2
 944        let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
 945        return lines.enumerated().map { index, line in
 946            var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1)  " } ?? ""
 947            out += line
 948            if parsed.switches.retainLabels, let ref = refs[index + 1] {
 949                out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
 950            }
 951            return out
 952        }.joined(separator: "\n") + "\n"
 953    }
 954
 955    /// The src and example blocks the export writes, in order, as their lines.
 956    private lazy var exportedBlocks: [[String]] = {
 957        let source = ExportSource(tree: tree, text: self.source as String)
 958        return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
 959            var lines = node.text.components(separatedBy: "\n")
 960            if lines.last == "" { lines.removeLast() }
 961            guard Coderef.block(lines) != nil, !excluded(node), !isResults(node) else { return nil }
 962            if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
 963            return lines
 964        }
 965    }()
 966
 967    /// Whether `node` is the results of the src block before it, which the export removes.
 968    private func isResults(_ node: SyntaxNode) -> Bool {
 969        guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
 970        let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
 971        guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
 972        let before = index - keywords.count - 1
 973        return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
 974    }
 975
 976    /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
 977    private lazy var blockLocs: [String: [Int?]] = {
 978        let blocks = exportedBlocks
 979        var locs: [String: [Int?]] = [:]
 980        for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
 981            locs[lines.joined(separator: "\n"), default: []].append(loc)
 982        }
 983        return locs
 984    }()
 985
 986    /// `org-export-get-loc` of the block with `lines`, the next of those with the same text.
 987    private func blockLoc(_ lines: [String], numbered: Bool) throws -> Int? {
 988        let key = lines.joined(separator: "\n")
 989        guard let queue = blockLocs[key], !queue.isEmpty else {
 990            if numbered { throw Unsupported(reason: "Numbered blocks inside other blocks") }
 991            return nil
 992        }
 993        blockLocs[key] = Array(queue.dropFirst())
 994        return queue[0]
 995    }
 996
 997    /// Whether `node` is under a section the export leaves out.
 998    private func excluded(_ node: SyntaxNode) -> Bool {
 999        var current: SyntaxNode? = node
1000        while let n = current {
1001            if n.kind == .section, let heading = n.firstChild(.heading),
1002               HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .all { return true }
1003            current = n.parent
1004        }
1005        return false
1006    }
1007
1008    /// A verse block's objects, their common indentation removed.
1009    private func verse(_ lines: [String]) throws -> String {
1010        let text = lines.joined(separator: "\n") + "\n"
1011        let tree = OrgParser.parse(text, defaults: settings)
1012        let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1013        guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
1014        let ns = text as NSString
1015        var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
1016        for (index, node) in nodes.enumerated() {
1017            raw += inlineItems(node)
1018            let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
1019            raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
1020        }
1021        return try transcode(LaTeXRenderer.normalizeIndentation(LaTeXRenderer.merge(raw), ignoreFirst: false))
1022    }
1023
1024    // MARK: - Objects
1025
1026    /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
1027    func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) -> [Inline] {
1028        var items: [Inline] = []
1029        var skipNewline = false
1030        for element in node.elements {
1031            switch element {
1032            case .token(let token):
1033                switch token.kind {
1034                case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1035                    continue
1036                default:
1037                    var text = token.text
1038                    if skipNewline {
1039                        let rest = text.drop { $0 == " " || $0 == "\t" }
1040                        if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1041                    }
1042                    if !text.isEmpty { items.append(.text(text)) }
1043                }
1044            case .node(let child):
1045                skipNewline = false
1046                switch child.kind {
1047                case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1048                    items.append(.object(child, inlineItems(child)))
1049                case .link:
1050                    items.append(.object(child, child.firstChild(.linkDescription).map { inlineItems($0) } ?? []))
1051                case .superscript, .subscript:
1052                    let text = child.text
1053                    let braced = text.dropFirst().hasPrefix("{")
1054                    if options.scripts == .off || (options.scripts == .braces && !braced) {
1055                        items.append(.text(text))
1056                    } else if braced {
1057                        items.append(.object(child, inlineItems(child)))
1058                    } else {
1059                        items.append(.object(child, [.text(String(text.dropFirst()))]))
1060                    }
1061                case .lineBreak where trimmed:
1062                    items.append(.text(child.text))
1063                case .lineBreak:
1064                    items.append(.object(child, []))
1065                    skipNewline = true
1066                default:
1067                    items.append(.object(child, []))
1068                }
1069            }
1070        }
1071        if trimmed {
1072            if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1073            if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1074        }
1075        return LaTeXRenderer.merge(items)
1076    }
1077
1078    /// One line of Org text transcoded, for keywords and captions.
1079    func inlineString(_ text: String) throws -> String {
1080        let tree = OrgParser.parse(text, defaults: settings)
1081        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1082        if tree.root.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in keywords and captions") }
1083        let saved = exportSource
1084        exportSource = ExportSource(tree: tree, text: text)
1085        defer { exportSource = saved }
1086        return LaTeXRenderer.trim(try transcode(inlineItems(paragraph)))
1087    }
1088
1089    /// `org-export-data` over objects: objects that export nothing taking their blanks with
1090    /// them unless they are needed.
1091    func transcode(_ items: [Inline]) throws -> String {
1092        var out = ""
1093        var index = 0
1094        var dropBlanks = false
1095        var afterObject = false
1096        while index < items.count {
1097            let item = items[index]
1098            switch item {
1099            case .text(var t):
1100                if dropBlanks {
1101                    t = String(t.drop { $0 == " " || $0 == "\t" })
1102                } else if afterObject {
1103                    let blanks = t.prefix { $0 == " " || $0 == "\t" }
1104                    t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1105                }
1106                dropBlanks = false
1107                afterObject = false
1108                out += try plainTextAndLinks(t)
1109                index += 1
1110            case .object(let node, let children):
1111                dropBlanks = false
1112                afterObject = true
1113                if let result = try object(node, children) {
1114                    out += result
1115                } else {
1116                    // `org-export--keep-spaces`: blanks after a dropped object stay only
1117                    // between text that has none.
1118                    let previousBlank: Bool
1119                    if index == 0 {
1120                        previousBlank = true
1121                    } else if case .text(let t) = items[index - 1] {
1122                        previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1123                    } else {
1124                        previousBlank = false
1125                    }
1126                    dropBlanks = previousBlank
1127                }
1128                index += 1
1129            }
1130        }
1131        return out
1132    }
1133
1134    private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1135        switch node.kind {
1136        case .bold: return "*\(try transcode(children))*"
1137        case .italic: return "/\(try transcode(children))/"
1138        case .underline: return "_\(try transcode(children))_"
1139        case .strikeThrough: return "+\(try transcode(children))+"
1140        case .verbatim, .code: return "`\(node.text.dropFirst().dropLast())'"
1141        case .link: return try link(node, children)
1142        case .linkDescription: return try transcode(children)
1143        case .timestamp:
1144            if isolatedTimestamps, ICalendarExport.skipsTimestamp(node.text, with: options.timestamps ?? "t") { return nil }
1145            return plainText(ASCIIText.timestamp(node.text))
1146        case .footnoteReference: return try footnoteReference(node)
1147        case .entity:
1148            let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1149            guard let entity = OrgEntities.text[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1150            return switch charset {
1151            case .ascii: entity.ascii
1152            case .latin1: entity.latin1
1153            case .utf8: entity.utf8
1154            }
1155        case .superscript: return node.text.dropFirst().hasPrefix("{") ? "^{\(try transcode(children))}" : "^\(try transcode(children))"
1156        case .subscript: return node.text.dropFirst().hasPrefix("{") ? "_{\(try transcode(children))}" : "_\(try transcode(children))"
1157        case .lineBreak: return Self.hardNewline
1158        case .latexFragment: return options.tex ? node.text : nil
1159        case .statisticsCookie: return node.text
1160        case .exportSnippet:
1161            let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1162            guard backend == "ascii" else { return nil }
1163            return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1164        case .target:
1165            return nil
1166        case .macro:
1167            guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1168            return try value.map(inlineString)
1169        default:
1170            throw Unsupported(reason: "\(node.kind)")
1171        }
1172    }
1173
1174    /// `org-ascii-plain-text`.
1175    func plainText(_ text: String) -> String {
1176        guard options.specialStrings else { return text }
1177        let text = text.replacingOccurrences(of: "\\-", with: "")
1178        guard utf8 else { return text }
1179        return text.replacingOccurrences(of: "---", with: "—").replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…")
1180    }
1181
1182    /// Text with the plain links the parser leaves in it, `FILE:x` and the like, written as Emacs does.
1183    private func plainTextAndLinks(_ t: String) throws -> String {
1184        let ns = t as NSString
1185        var out = ""
1186        var last = 0
1187        for m in Self.plainLink.matches(in: t, range: NSRange(location: 0, length: ns.length)) {
1188            let type = ns.substring(with: m.range(at: 1))
1189            guard ["http", "https", "mailto", "file"].contains(type.lowercased()) else { throw Unsupported(reason: "Plain links of type \(type)") }
1190            out += plainText(ns.substring(with: NSRange(location: last, length: m.range.location - last))) + "<" + ns.substring(with: m.range) + ">"
1191            last = NSMaxRange(m.range)
1192        }
1193        return out + plainText(ns.substring(from: last))
1194    }
1195
1196    // MARK: Links
1197
1198    /// A link written in notes mode: its footprint and how `org-ascii--describe-links`
1199    /// describes it, nil for none.
1200    private struct Noted {
1201        var footprint: String
1202        var note: String?
1203    }
1204
1205    /// Links written so far, for their section's notes.
1206    private var noted: [Noted] = []
1207    /// Whether links written now are noted: not in captions.
1208    private var noting = true
1209
1210    /// `org-ascii--describe-links` for the links noted since `start`, each once.
1211    private func describeLinks(from start: Int, width: Int) throws -> String {
1212        guard linksToNotes else { return "" }
1213        var seen: Set<String> = []
1214        var out = ""
1215        for link in noted[start...] where !seen.contains(link.footprint) {
1216            seen.insert(link.footprint)
1217            if let note = link.note {
1218                let filled = ASCIIText.fill(note, width: width)
1219                // Emacs fills by columns: the same unless wide characters take a line past them.
1220                if note.unicodeScalars.contains(where: Self.isZeroWidth) || filled.split(separator: "\n").contains(where: { Self.width(String($0)) > max(width, $0.count) }) {
1221                    throw Unsupported(reason: "Wide or combining characters")
1222                }
1223                out += filled + "\n\n"
1224            }
1225        }
1226        noted.removeSubrange(start...)
1227        return out
1228    }
1229
1230    /// Link types Org registers in an Org buffer that this export doesn't write as Emacs does.
1231    private static let unrenderedTypes: Set<String> = ["attachment", "bbdb", "bibtex", "docview", "doi", "eww", "gnus", "info", "irc", "mhe", "rmail", "w3m"]
1232
1233    /// `org-link-plain-re`, in any case, for the plain links the parser leaves as text.
1234    static let plainLink: NSRegularExpression = {
1235        let plain = #"[^\[\]\s()<>]"#
1236        let parens = #"[<(\[](?:\#(plain)|[<(\[]\#(plain)*[\])>])*[\])>]"#
1237        let types = "attachment|bbdb|bibtex|docview|doi|elisp|eww|file\\+emacs|file\\+sys|file|ftp|gnus|help|https?|id|info|irc|mailto|mhe|news|rmail|shell|shortdoc|w3m"
1238        return try! NSRegularExpression(pattern: #"(?i)(?<![\p{L}\p{N}_])("# + types + #"):(?:\#(plain)|\#(parens))+(?:[^\p{P}\p{S}\s]|[/-]|\#(parens))"#)
1239    }()
1240
1241    private static let externalTypes: Set<String> = ["file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1242
1243    private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1244        if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1245            throw Unsupported(reason: "Links in link descriptions")
1246        }
1247        let pathToken = node.linkPath
1248        var raw = pathToken ?? node.text
1249        if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) }
1250        var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1251        if description?.contains(where: { !$0.isWhitespace }) != true { description = nil }
1252        let linkType = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1) }
1253        if let linkType, Self.unrenderedTypes.contains(linkType) { throw Unsupported(reason: "Links of type \(linkType)") }
1254        let footprint = raw + "\u{0}" + (node.firstChild(.linkDescription)?.text ?? "").split(whereSeparator: { " \t\n\r".contains($0) }).joined(separator: " ")
1255        // Only the link types Org knows, in any case, have a scheme; `foo:bar` is a fuzzy link.
1256        // Only `id` in lower case is an ID link; `ID:x` and `DOI:x` are written as they are.
1257        let scheme = linkType.map { $0.lowercased() }.flatMap { Self.externalTypes.contains($0) || Self.unrenderedTypes.contains($0) || $0 == "id" ? $0 : nil }
1258        if raw.hasPrefix("(") && raw.hasSuffix(")") {
1259            let path = String(raw.dropFirst().dropLast())
1260            guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1261            var format = description ?? "%s"
1262            if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1263            return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1264        }
1265        let internalLink = raw.hasPrefix("#") || linkType == "id" || (scheme == nil && !raw.hasPrefix("/") && !raw.hasPrefix("./") && !raw.hasPrefix("../") && !raw.hasPrefix("~"))
1266        if internalLink {
1267            let type = raw.hasPrefix("#") ? "custom-id" : linkType == "id" ? "id" : "fuzzy"
1268            let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw
1269            if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) {
1270                throw Unsupported(reason: "Links to targets and named elements")
1271            }
1272            guard let heading = resolveHeading(type: type, path: path) else {
1273                throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1274            }
1275            let reference = try describeHeading(heading)
1276            if let description {
1277                let see = try seeSection(reference)
1278                if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(see)" : nil)) }
1279                return linksToNotes ? "[\(description)]" : "[\(description)] (\(see))"
1280            }
1281            if noting { noted.append(Noted(footprint: footprint, note: nil)) }
1282            return reference
1283        }
1284        if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) }
1285        return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>"
1286    }
1287
1288    /// A heading as a link without a description writes it: its number, else its title.
1289    private func describeHeading(_ heading: HeadingInfo) throws -> String {
1290        let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".")
1291        let text: String
1292        if let number {
1293            text = number
1294        } else {
1295            guard let node = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }) else { return "" }
1296            let saved = noting
1297            noting = false
1298            defer { noting = saved }
1299            text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? ""
1300        }
1301        return text
1302    }
1303
1304    /// `org-ascii--describe-datum` for a heading `reference` names.
1305    private func seeSection(_ reference: String) throws -> String {
1306        // In notes, `describeLinks` checks the width.
1307        let format = linksToNotes ? translate("See section %s") : try translateFilled("See section %s")
1308        // Emacs's `format` stops at `%d` given a string (Slovenian).
1309        if format.contains("%d") { throw Unsupported(reason: "Format specifier doesn't match argument type") }
1310        return format.replacingOccurrences(of: "%s", with: reference)
1311    }
1312
1313    /// Whether a `<<target>>` has the name a fuzzy link gives.
1314    private func target(_ path: String) -> Bool {
1315        let search = LaTeXRenderer.words(path)
1316        return tree.root.descendants().contains { $0.kind == .target && LaTeXRenderer.words(String($0.text.dropFirst(2).dropLast(2))) == search }
1317    }
1318
1319    /// Whether an element has the `#+NAME` a fuzzy link gives.
1320    private func namedElement(_ path: String) -> Bool {
1321        let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1322        return tree.root.descendants().contains { node in
1323            guard node.kind == .affiliatedKeyword, let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { return false }
1324            let words = String(m.1).split(whereSeparator: \.isWhitespace).map(String.init)
1325            return words == search || words == search.map { $0.uppercased() }
1326        }
1327    }
1328
1329    /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1330    private func resolveHeading(type: String, path: String) -> HeadingInfo? {
1331        let starts = Set(exported.map(\.start))
1332        let headings = model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1333        switch type {
1334        case "custom-id":
1335            return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1336        case "id":
1337            return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1338        default:
1339            let search = LaTeXRenderer.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1340            return headings.first { heading in
1341                let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1342                let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1343                return LaTeXRenderer.words(raw) == search
1344            }
1345        }
1346    }
1347
1348    // MARK: Footnotes
1349
1350    /// Footnote numbers by label, in the order of first references.
1351    private var footnoteNumbers: [String: Int] = [:]
1352    /// What each number's footnote says: a definition's label, or an inline definition.
1353    private var footnoteOrder: [(label: String?, inline: String?)] = []
1354    private var inFootnote = false
1355
1356    /// `org-ascii-footnote-reference`.
1357    private func footnoteReference(_ node: SyntaxNode) throws -> String {
1358        guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1359        if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1360        let label = String(m.1)
1361        if !label.isEmpty, let number = footnoteNumbers[label] { return "[\(number)]" }
1362        if m.2 == nil, label.isEmpty || definition(label) == nil { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1363        footnoteOrder.append((label.isEmpty ? nil : label, m.2.map(String.init)))
1364        if !label.isEmpty { footnoteNumbers[label] = footnoteOrder.count }
1365        return "[\(footnoteOrder.count)]"
1366    }
1367
1368    /// The definition of `label` and the text width where it is.
1369    private func definition(_ label: String) -> (text: String, width: Int)? {
1370        for node in tree.root.descendants() where node.kind == .footnoteDefinition {
1371            guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/), m.1 == label else { continue }
1372            var width = Self.textWidth
1373            var current = node.parent
1374            while let n = current {
1375                if n.kind == .section, let heading = n.firstChild(.heading) {
1376                    let level = self.level(heading)
1377                    width -= level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin
1378                    break
1379                }
1380                current = n.parent
1381            }
1382            if excluded(node) { return nil }
1383            return (String(node.text[m.range.upperBound...]), width)
1384        }
1385        return nil
1386    }
1387
1388    /// The footnote definitions, as `org-ascii-inner-template` writes them.
1389    private func footnotes() throws -> String {
1390        linksToNotes = false
1391        inFootnote = true
1392        defer {
1393            linksToNotes = true
1394            inFootnote = false
1395        }
1396        var parts: [String] = []
1397        for (index, footnote) in footnoteOrder.enumerated() {
1398            let id = "[\(index + 1)] "
1399            if let inline = footnote.inline {
1400                parts.append(LaTeXRenderer.trim(ASCIIText.fill(id + (try inlineObjects(inline)), width: Self.textWidth)))
1401                continue
1402            }
1403            guard let label = footnote.label, let (text, width) = definition(label) else { continue }
1404            let tree = OrgParser.parse(text, defaults: settings)
1405            let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1406            let saved = (currentSource, exportSource)
1407            currentSource = text as NSString
1408            exportSource = ExportSource(tree: tree, text: text)
1409            defer { (currentSource, exportSource) = saved }
1410            let context = Context(width: width)
1411            if let first = nodes.first, first.kind == .paragraph {
1412                var out = Self.normalize(try paragraph(first, context: context, ignoreFirst: true, prefix: id))
1413                out += String(repeating: "\n", count: blankLines(from: first.range.lowerBound, to: nodes.count > 1 ? nodes[1].range.lowerBound : (text as NSString).length))
1414                out += try elements(Array(nodes.dropFirst()), end: (text as NSString).length, context: context)
1415                parts.append(LaTeXRenderer.trim(out))
1416            } else {
1417                parts.append(LaTeXRenderer.trim(id + "\n" + (try elements(nodes, end: (text as NSString).length, context: context))))
1418            }
1419        }
1420        return parts.joined(separator: "\n\n")
1421    }
1422
1423    /// An inline definition's objects transcoded.
1424    private func inlineObjects(_ text: String) throws -> String {
1425        let tree = OrgParser.parse(text, defaults: settings)
1426        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1427        return try transcode(inlineItems(paragraph))
1428    }
1429}