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