Commit b832d253d5

b832d253d5bb00d0577d76490c0b27c4ec0beb2c

parent: fe1e04c329

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 19:19 UTC

Native plain text export matching ox-ascii in all three charsets

Layout: unified · split

Sources/OrgCore/Export/ASCIIExport.swift added +1346
@@ -0,0 +1,1346 @@
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`.
19 public static func document(
20 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), charset: Charset = .ascii,
21 bodyOnly: Bool = false, author: String = "", language: String = "en"
22 ) throws -> String {
23 let text = try LaTeXExport.expanded(text, settings: settings, path: path, now: now)
24 let tree = OrgParser.parse(text, defaults: settings)
25 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
26 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
27 let renderer = try ASCIIRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language, charset: charset)
28 var output = try renderer.body()
29 if !bodyOnly { output = try renderer.template(output, author: author) }
30 return output.replacingOccurrences(of: ASCIIRenderer.hardNewline, with: "\n")
31 }
32}
33
34final class ASCIIRenderer {
35 typealias Unsupported = LaTeXExport.Unsupported
36 typealias Inline = LaTeXRenderer.Inline
37
38 enum Justify { case left, center, right }
39
40 /// Where an element is: the text width `org-ascii--current-text-width` gives it and the
41 /// justification of the blocks around it.
42 struct Context {
43 var width: Int
44 var justify = Justify.left
45 }
46
47 /// `hard-newline`: a newline that ends a line when filling.
48 static let hardNewline = ASCIIText.hardNewline + "\n"
49
50 static let textWidth = 72
51 static let innerMargin = 2
52 static let quoteMargin = 6
53
54 let tree: OrgTree
55 let source: NSString
56 let settings: OrgSettings
57 let options: ExportOptions
58 /// Keyword values by name, in order.
59 let keywords: [String: [String]]
60 let language: String
61 let charset: ASCIIExport.Charset
62 var utf8: Bool { charset == .utf8 }
63 let numbered: Bool
64 let num: Int?
65 let withTOC: Bool
66 let toc: Int?
67 private var selected: Set<Int>?
68 /// Added to heading levels.
69 private var levelOffset = 0
70 private var exportSource: ExportSource
71 private let model: DocumentModel
72 /// Section numbers of the numbered headings the export writes, by heading start.
73 private var numbers: [Int: [Int]] = [:]
74 /// The headings the export writes, by start, with their relative level.
75 private var exported: [(start: Int, level: Int)] = []
76 /// `:ascii-links-to-notes`, off in the title block and footnotes.
77 private var linksToNotes = true
78
79 init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String, charset: ASCIIExport.Charset) throws {
80 self.tree = tree
81 source = text as NSString
82 self.settings = settings
83 self.charset = charset
84 exportSource = ExportSource(tree: tree, text: text)
85 model = DocumentModel(tree: tree)
86 var keywords: [String: [String]] = [:]
87 for line in lines {
88 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
89 keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
90 }
91 self.keywords = keywords
92 options = ExportOptions.parse(lines.joined(separator: "\n"))
93 self.language = keywords["LANGUAGE"]?.last ?? language
94
95 // `#+OPTIONS` this export follows; any other item only at its default.
96 let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
97 "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
98 "broken-links": "nil", "'": "nil", "d": "(not \"LOGBOOK\")", "expand-links": "t"]
99 for (key, value) in options.items {
100 if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
101 }
102 let items = options.items
103 func depth(_ key: String) throws -> (Bool, Int?) {
104 guard let v = items[key] else { return (true, nil) }
105 if v == "nil" { return (false, nil) }
106 if v == "t" { return (true, nil) }
107 guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
108 return (true, n)
109 }
110 (numbered, num) = try depth("num")
111 (withTOC, toc) = try depth("toc")
112 if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
113 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "CALL"] where keywords[key] != nil {
114 throw Unsupported(reason: "#+\(key)")
115 }
116 // Radio links: links that are only words.
117 if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
118 throw Unsupported(reason: "Radio targets")
119 }
120 let kinds = Set(tree.root.descendants().map(\.kind))
121 for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
122 (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
123 (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
124 throw Unsupported(reason: name)
125 }
126 // Emacs measures text in columns, where these take two or none.
127 if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
128 // Tabs fill and align by column; in code they are copied.
129 let code = tree.root.descendants().filter { $0.kind == .block && $0.text.firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b/) != nil }.map(\.range)
130 if Array(text.utf16).enumerated().contains(where: { offset, unit in unit == 9 && !code.contains { $0.contains(offset) } }) {
131 throw Unsupported(reason: "Tabs outside code")
132 }
133 // A definition goes on to the next one, a heading or two blank lines.
134 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
135 guard let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count else { continue }
136 let next = parent.children[index + 1]
137 let gap = (text as NSString).substring(with: NSRange(location: node.range.lowerBound, length: next.range.lowerBound - node.range.lowerBound))
138 if next.kind != .footnoteDefinition, next.kind != .section, !gap.hasSuffix("\n\n\n") {
139 throw Unsupported(reason: "Footnote definitions of several paragraphs")
140 }
141 }
142 for heading in model.headings {
143 let keys = heading.properties.map { $0.key.uppercased() }
144 if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
145 }
146 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
147 let options = options
148 let selected = selected
149 let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
150 .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
151 levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
152 collectHeadings(tree.root.children)
153 }
154
155 static func isWideOrZeroWidth(_ s: Unicode.Scalar) -> Bool {
156 switch s.value {
157 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3,
158 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD:
159 return true
160 case 0x200B...0x200F, 0xFE00...0xFE0F:
161 return true
162 default:
163 return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark
164 }
165 }
166
167 /// `org-export--collect-headline-numbering` over the headings the export writes.
168 private func collectHeadings(_ nodes: [SyntaxNode]) {
169 var counters: [Int] = []
170 func walk(_ nodes: [SyntaxNode]) {
171 for node in nodes where node.kind == .section {
172 guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { continue }
173 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
174 if export == .nothing { continue }
175 let level = self.level(heading)
176 exported.append((heading.range.lowerBound, level))
177 if isNumbered(level) {
178 while counters.count < level { counters.append(0) }
179 counters[level - 1] += 1
180 for deeper in level..<counters.count { counters[deeper] = 0 }
181 numbers[heading.range.lowerBound] = Array(counters.prefix(level))
182 }
183 if export == .all { walk(node.children) }
184 }
185 }
186 walk(nodes)
187 }
188
189 private func isFootnoteSection(_ heading: SyntaxNode) -> Bool { heading.firstChild(.title)?.text == "Footnotes" }
190
191 private func level(_ heading: SyntaxNode) -> Int {
192 (heading.tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
193 }
194
195 private func isNumbered(_ level: Int) -> Bool { numbered && (num.map { level <= $0 } ?? true) }
196
197 // MARK: - Template
198
199 /// `org-ascii-template`: the title block and table of contents before `body`.
200 func template(_ body: String, author: String) throws -> String {
201 var out = try titleBlock(author: author)
202 if withTOC { out += try tableOfContents(depth: toc, width: Self.textWidth, keyword: false) + "\n\n\n" }
203 return out + body
204 }
205
206 /// `org-ascii-template--document-title`.
207 private func titleBlock(author defaultAuthor: String) throws -> String {
208 let width = Self.textWidth
209 linksToNotes = false
210 defer { linksToNotes = true }
211 let title = options.title ? try keywords["TITLE"].map(parsed) ?? "" : ""
212 let subtitle = options.title ? try keywords["SUBTITLE"].map(parsed) ?? "" : ""
213 var author: String?
214 if options.author { author = try keywords["AUTHOR"].map(parsed) ?? (defaultAuthor.isEmpty ? nil : try inlineString(defaultAuthor)) }
215 let date = options.date ? try keywords["DATE"].map(parsed) : nil
216 func nw(_ s: String?) -> String? { s.flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil } }
217 if title.isEmpty {
218 switch (nw(date), nw(author)) {
219 case (let date?, let author?):
220 return author + String(repeating: " ", count: max(0, width - date.count - author.count)) + date + "\n\n\n"
221 case (let date?, nil):
222 return Self.justifyLines(date, width: width, .right) + "\n\n\n"
223 case (nil, let author?):
224 return author + "\n\n\n"
225 default:
226 return ""
227 }
228 }
229 let titleLength = min((title + "\n" + subtitle).components(separatedBy: "\n").map(\.count).max() ?? 0, 2 * width / 3)
230 let formattedTitle = ASCIIText.fill(title, width: titleLength)
231 let formattedSubtitle = nw(subtitle).map { ASCIIText.fill($0, width: titleLength) }
232 let line = String(repeating: utf8 ? "━" : "_", count: min(max(titleLength, author?.count ?? 0) + 2, width))
233 var block = line + "\n" + (utf8 ? "" : "\n") + formattedTitle.uppercased()
234 if let formattedSubtitle { block += "\n" + formattedSubtitle }
235 if let author = nw(author) { block += "\n\n" + author }
236 block += "\n" + line
237 if let date = nw(date) { block += "\n\n\n" + date }
238 return Self.justifyLines(block + "\n\n\n", width: width, .center)
239 }
240
241 /// A keyword parsed as Org text, its lines joined with spaces.
242 private func parsed(_ values: [String]) throws -> String {
243 if values.count > 1, values.contains("") { throw Unsupported(reason: "Repeated keywords with an empty value") }
244 return try inlineString(values.joined(separator: " "))
245 }
246
247 /// `org-ascii--build-toc` over the whole document.
248 private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String {
249 let title = translate("Table of Contents")
250 var out = title + "\n" + String(repeating: utf8 ? "─" : "_", count: title.count) + "\n\n"
251 let limit = min(depth ?? options.headlineLevels, options.headlineLevels)
252 var lines: [String] = []
253 for (start, level) in exported where level <= limit {
254 guard let heading = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == start }) else { continue }
255 let indent = (level - 1) * 3
256 let prefix = indent == 0 ? "" : String(repeating: ".", count: indent - 1) + " "
257 lines.append(prefix + (try buildTitle(heading, width: width - indent, underline: false, notags: !options.tags || !options.tagsInTOC, toc: true)))
258 }
259 out += lines.joined(separator: "\n")
260 _ = keyword
261 return out
262 }
263
264 // MARK: - Strings
265
266 /// `org-ascii--translate`.
267 func translate(_ term: String) -> String {
268 ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii)
269 }
270
271 /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs`
272 /// indents as `fill-region` does, with tabs where they fit.
273 static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String {
274 guard how != .left else { return s }
275 return s.components(separatedBy: "\n").map { line in
276 let trimmed = line.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
277 guard !trimmed.isEmpty else { return trimmed }
278 let room = width - trimmed.count
279 let indent = max(0, how == .center ? room / 2 : room)
280 return (tabs ? Self.indentation(indent) : String(repeating: " ", count: indent)) + trimmed
281 }.joined(separator: "\n")
282 }
283
284 /// `org-ascii--justify-element` for anything but a paragraph: the lines moved as a block
285 /// so the widest is centered or flushed right.
286 static func justifyBlock(_ s: String, context: Context) -> String {
287 guard context.justify != .left, s.contains(where: { !$0.isWhitespace }) else { return s }
288 let lines = s.components(separatedBy: "\n")
289 var widest = 0
290 for line in lines where line.contains(where: { $0 != " " && $0 != "\t" }) {
291 if line.count >= context.width { return s }
292 widest = max(widest, line.count)
293 }
294 let offset = (context.width - widest) / (context.justify == .right ? 1 : 2)
295 guard offset > 0 else { return s }
296 return lines.map { line in
297 line.contains(where: { $0 != " " && $0 != "\t" }) ? indentation(offset) + line : line
298 }.joined(separator: "\n")
299 }
300
301 /// `indent-to` from the line start with `indent-tabs-mode`.
302 static func indentation(_ columns: Int) -> String {
303 String(repeating: "\t", count: columns / 8) + String(repeating: " ", count: columns % 8)
304 }
305
306 /// `org-ascii--box-string`.
307 func box(_ s: String) -> String {
308 let body = s.replacing(#/\n[ \t]*\z/#, with: "")
309 let bar = utf8 ? "│ " : "| "
310 // `replace-regexp-in-string' finds no line start in the empty string.
311 let lines = body.isEmpty ? "" : body.components(separatedBy: "\n").map { bar + $0 }.joined(separator: "\n")
312 return utf8 ? "┌────\n" + lines + "\n└────" : ",----\n" + lines + "\n`----"
313 }
314
315 /// `org-element-normalize-string`.
316 static func normalize(_ s: String) -> String { LaTeXRenderer.normalize(s) }
317
318 /// The headline and section filter: whatever blank lines end `s`, two.
319 static func spaced(_ s: String) -> String {
320 var end = s.endIndex
321 var cut: String.Index?
322 while end > s.startIndex {
323 let before = s.index(before: end)
324 if s[before] == " " || s[before] == "\t" {
325 end = before
326 } else if s[before] == "\n" {
327 end = before
328 cut = before
329 } else {
330 break
331 }
332 }
333 guard let cut else { return s }
334 return String(s[..<cut]) + "\n\n\n"
335 }
336
337 // MARK: - Document
338
339 /// The transcoded document with its footnotes, `org-ascii-inner-template`.
340 func body() throws -> String {
341 var nodes = tree.root.children
342 // With a select tag, the text before the first heading isn't exported.
343 if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
344 var out = ""
345 for node in nodes {
346 if node.kind == .zerothSection {
347 out += try section(node.children, end: node.range.upperBound, heading: nil)
348 } else if node.kind == .section {
349 out += try headline(node) ?? ""
350 }
351 }
352 out = Self.normalize(out)
353 let notes = try footnotes()
354 if !notes.isEmpty {
355 let title = translate("Footnotes")
356 out += "\n\n\n" + title + "\n" + String(repeating: utf8 ? "─" : "_", count: title.count) + "\n\n" + notes
357 }
358 return Self.normalize(out)
359 }
360
361 /// Blank lines at the end of `source[from..<to]`.
362 func blankLines(from: Int, to: Int) -> Int {
363 guard to > from else { return 0 }
364 let source = currentSource ?? self.source
365 let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
366 return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
367 }
368
369 /// The text being transcoded when it isn't the document: a block's contents.
370 private var currentSource: NSString?
371
372 /// A section's elements as `org-ascii-section` writes them, the section filter applied: its
373 /// contents indented under a heading, then for the text before the first heading the
374 /// links it holds. `heading` is the relative level of the heading above, nil for none.
375 private func section(_ nodes: [SyntaxNode], end: Int, heading: Int?) throws -> String {
376 let low = heading.map { $0 > options.headlineLevels }
377 let width = Self.textWidth - (heading.map { $0 > options.headlineLevels ? ($0 - options.headlineLevels) * 2 : Self.innerMargin } ?? 0)
378 let linkStart = noted.count
379 var contents = try elements(nodes, end: end, context: Context(width: width))
380 if heading == nil {
381 let links = describeLinks(from: linkStart, width: width)
382 if !links.isEmpty { contents = Self.normalize(contents) + "\n\n" + links }
383 }
384 if heading != nil, low == false { contents = ASCIIText.indent(contents, Self.innerMargin) }
385 return Self.spaced(Self.normalize(contents))
386 }
387
388 /// `org-ascii-headline`, the headline filter applied; nil when not exported.
389 private func headline(_ node: SyntaxNode) throws -> String? {
390 guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { return nil }
391 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
392 if export == .nothing { return nil }
393 let level = self.level(heading)
394 let low = level > options.headlineLevels ? level - options.headlineLevels : nil
395 let width = Self.textWidth - (low.map { $0 * 2 } ?? 0)
396 let linkStart = noted.count
397 let title = try buildTitle(heading, width: width, underline: low == nil, notags: false, toc: false)
398 var body = ""
399 if export == .all {
400 let children = node.children.filter { $0.kind != .heading }
401 let elements = children.filter { $0.kind != .section }
402 let subsections = children.filter { $0.kind == .section }
403 var sectionText: String?
404 if !elements.isEmpty {
405 let end = subsections.first?.range.lowerBound ?? node.range.upperBound
406 sectionText = try section(elements, end: end, heading: level)
407 }
408 let links = describeLinks(from: linkStart, width: width)
409 let sub = try subsections.compactMap { try headline($0) }.joined()
410 if links.isEmpty {
411 body = (sectionText ?? "") + sub
412 } else {
413 body = (sectionText.map { Self.normalize($0) + "\n\n" } ?? "") + links + sub
414 }
415 } else {
416 _ = describeLinks(from: linkStart, width: width)
417 }
418 let out: String
419 if let low {
420 let bullets: [Character] = switch charset {
421 case .ascii: ["*", "+", "-"]
422 case .latin1: ["§", ""]
423 case .utf8: ["◊"]
424 }
425 let bullet = "\(bullets[(low - 1) % bullets.count]) "
426 out = bullet + title + "\n\n" + ASCIIText.indent(body, bullet.count)
427 } else {
428 out = title + "\n\n" + body
429 }
430 return Self.spaced(Self.normalize(out))
431 }
432
433 /// `org-ascii--build-title` for a heading.
434 private func buildTitle(_ heading: SyntaxNode, width: Int, underline: Bool, notags: Bool, toc: Bool) throws -> String {
435 let tokens = heading.tokens
436 let level = self.level(heading)
437 var first = ""
438 if let number = numbers[heading.range.lowerBound] {
439 first += toc ? "\(number.last!). " : number.map(String.init).joined(separator: ".") + " "
440 }
441 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text { first += plainText(todo) + " " }
442 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text, let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
443 first += "(#\(letter)) "
444 }
445 let titleNode = heading.firstChild(.title)
446 if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
447 first += try titleText(heading, toc: toc)
448 var out = first
449 if !notags, options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
450 let names = tags.split(separator: ":").map(String.init)
451 if !names.isEmpty {
452 let tagString = ":" + names.joined(separator: ":") + ":"
453 let column = max(width - (first.count + 1), tagString.count)
454 out += " " + String(repeating: " ", count: column - tagString.count) + tagString
455 }
456 }
457 let underlines: [Character] = switch charset {
458 case .ascii, .latin1: ["=", "~", "-"]
459 case .utf8: ["═", "─", "╌", "┄", "┈"]
460 }
461 if underline, level <= underlines.count {
462 out += "\n" + String(repeating: underlines[level - 1], count: first.count)
463 }
464 return out
465 }
466
467 /// A heading's title transcoded and trimmed, once: links in it are noted where it is first
468 /// written.
469 private func titleText(_ heading: SyntaxNode, toc: Bool) throws -> String {
470 if let cached = titles[heading.range.lowerBound] { return cached }
471 let text = try heading.firstChild(.title).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
472 titles[heading.range.lowerBound] = text
473 return text
474 }
475
476 private var titles: [Int: String] = [:]
477
478 // MARK: - Elements
479
480 /// Affiliated keywords of the element being transcoded.
481 typealias Affiliated = LaTeXRenderer.Affiliated
482
483 private func blockType(_ node: SyntaxNode) -> String {
484 node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
485 }
486
487 /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
488 /// `org-export-data` joins a greater element's contents.
489 func elements(_ nodes: [SyntaxNode], end: Int, context: Context, firstParagraph: ((SyntaxNode) -> Bool)? = nil) throws -> String {
490 var out = ""
491 var affiliated = Affiliated()
492 // The element before and its blank lines, which a comment after it may add to; they
493 // show only when it wrote something.
494 var pendingBlank = 0
495 var previous: SyntaxNode?
496 var previousWrote = false
497 var afterSrc = false
498 for (index, node) in nodes.enumerated() {
499 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
500 if node.kind == .affiliatedKeyword {
501 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
502 guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
503 let key = m.1.uppercased()
504 if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
505 switch key {
506 case "CAPTION":
507 if m.2 != nil { throw Unsupported(reason: "Short captions") }
508 affiliated.caption.append(String(m.3))
509 case "NAME": affiliated.name = String(m.3)
510 case "ATTR_ASCII": affiliated.attr.append(String(m.3))
511 case "RESULTS": affiliated.results = String(m.3)
512 default: break
513 }
514 continue
515 }
516 defer { affiliated = Affiliated() }
517 // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
518 // the block too, as if they had never been there.
519 if node.kind == .block, blockType(node) == "src" {
520 let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
521 if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
522 afterSrc = true
523 if exports == "none" { continue }
524 } else if let results = affiliated.results {
525 if afterSrc {
526 afterSrc = false
527 continue
528 }
529 if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
530 if affiliated.name == nil { affiliated.name = results }
531 } else {
532 afterSrc = false
533 }
534 if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
535 // `org-export--skip-p`: the element before keeps at least one blank line.
536 if previous != nil {
537 let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
538 if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
539 pendingBlank = blank
540 }
541 continue
542 }
543 let result: String?
544 if node.kind == .paragraph, let firstParagraph {
545 result = try paragraph(node, context: context, ignoreFirst: firstParagraph(node))
546 } else {
547 result = try element(node, affiliated: affiliated, context: context)
548 }
549 guard let result else {
550 if !pruned(node) {
551 previous = node
552 previousWrote = false
553 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
554 }
555 continue
556 }
557 previous = node
558 previousWrote = true
559 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
560 out += Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
561 }
562 return out
563 }
564
565 /// Elements `org-export--prune-tree` takes out of the tree.
566 private func pruned(_ node: SyntaxNode) -> Bool {
567 switch node.kind {
568 case .planning, .propertyDrawer, .clock: return true
569 case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
570 case .latexEnvironment: return !options.tex
571 default: return false
572 }
573 }
574
575 private func drawerName(_ node: SyntaxNode) -> String {
576 node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
577 }
578
579 /// One element's transcoding, nil for none.
580 private func element(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
581 switch node.kind {
582 case .paragraph:
583 return try paragraph(node, context: context, ignoreFirst: false)
584 case .plainList:
585 return try list(node, context: context)
586 case .table:
587 return try table(node, affiliated: affiliated, context: context)
588 case .block:
589 return try block(node, affiliated: affiliated, context: context)
590 case .fixedWidth:
591 let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in
592 let trimmed = line.drop { $0 == " " || $0 == "\t" }
593 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1))
594 }
595 return Self.justifyBlock(box(try LaTeXRenderer.removeIndentation(lines.joined(separator: "\n"))), context: context)
596 case .horizontalRule:
597 let width = affiliated.value("width").flatMap { $0.allSatisfy(\.isNumber) ? Int($0) : nil } ?? context.width
598 return Self.justifyLines(String(repeating: utf8 ? "―" : "-", count: width), width: context.width, .center)
599 case .drawer:
600 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
601 guard hasContents(node.children) else { return nil }
602 return Self.normalize(try elements(node.children, end: node.range.upperBound, context: context))
603 case .dynamicBlock:
604 let lines = node.text.components(separatedBy: "\n")
605 return try blockContents(Array(lines.dropFirst().dropLast(2)), context: context)
606 case .latexEnvironment:
607 guard options.tex else { return nil }
608 return Self.justifyBlock(try LaTeXRenderer.removeIndentation(node.text), context: context)
609 case .keyword:
610 return try keyword(node, context: context)
611 case .planning, .propertyDrawer, .clock, .footnoteDefinition:
612 return nil
613 default:
614 throw Unsupported(reason: "\(node.kind)")
615 }
616 }
617
618 /// Whether `nodes` hold an element the export keeps.
619 private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
620 nodes.indices.contains { index in
621 let node = nodes[index]
622 switch node.kind {
623 case .comment: return false
624 case .affiliatedKeyword:
625 // Org parses affiliated keywords with no element right after them as keywords.
626 var last = index
627 while last + 1 < nodes.count, nodes[last + 1].kind == .affiliatedKeyword,
628 nodes[last].range.upperBound == nodes[last + 1].range.lowerBound { last += 1 }
629 return last + 1 == nodes.count || nodes[last].range.upperBound != nodes[last + 1].range.lowerBound
630 case .block:
631 let type = blockType(node)
632 if type == "comment" { return false }
633 if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
634 return !isResults(node)
635 default: return !pruned(node)
636 }
637 }
638 }
639
640 private func keyword(_ node: SyntaxNode, context: Context) throws -> String? {
641 guard let m = node.text.firstMatch(of: /^[ \t]*#\+([^:\s]+):[ \t]*(.*?)[ \t]*\n?$/) else { return nil }
642 let value = String(m.2)
643 switch m.1.uppercased() {
644 case "ASCII":
645 return Self.justifyBlock(value, context: context)
646 case "TOC":
647 guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else {
648 throw Unsupported(reason: "#+TOC: \(value)")
649 }
650 if value.range(of: "\\blocal\\b|:target", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: \(value)") }
651 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) }
652 return Self.justifyBlock(try tableOfContents(depth: depth, width: context.width, keyword: true), context: context)
653 default:
654 return nil
655 }
656 }
657
658 // MARK: Paragraphs
659
660 private func paragraph(_ node: SyntaxNode, context: Context, ignoreFirst: Bool, prefix: String = "") throws -> String {
661 let items = LaTeXRenderer.normalizeIndentation(inlineItems(node), ignoreFirst: ignoreFirst)
662 // `org-remove-blank-lines`, whose newline isn't a hard one.
663 let contents = (prefix + (try transcode(items))).replacing(#/\x{1}?\n(?:[ \t]*\x{1}?\n)+/#, with: "\n")
664 return Self.fill(contents.replacingOccurrences(of: Self.hardNewline, with: ASCIIText.hardNewline), context: context)
665 }
666
667 /// `org-ascii--fill-string` with the context's justification.
668 static func fill(_ s: String, context: Context) -> String {
669 let filled = ASCIIText.fill(s, width: context.width)
670 return justifyLines(filled, width: context.width, context.justify, tabs: true)
671 }
672
673 // MARK: Lists
674
675 private func list(_ node: SyntaxNode, context: Context) throws -> String {
676 let items = node.children.filter { $0.kind == .item }
677 guard let first = items.first else { return "" }
678 let firstBullet = (first.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
679 let ordered = firstBullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
680 let descriptive = !ordered && first.firstChild(.itemTag) != nil
681 var out = ""
682 var number = 0
683 for (index, item) in items.enumerated() {
684 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
685 let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
686 let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text.uppercased() {
687 case "[X]"?: utf8 ? "☑ " : "[X] "
688 case "[ ]"?: utf8 ? "☐ " : "[ ] "
689 case "[-]"?: utf8 ? "☒ " : "[-] "
690 default: ""
691 }
692 let bullet: String
693 if descriptive {
694 let tag = try item.firstChild(.itemTag).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
695 bullet = checkbox + tag
696 } else if ordered {
697 if let counter = item.tokens.first(where: { $0.kind == .counter })?.text {
698 guard let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) else { throw Unsupported(reason: "Alphabetical counters") }
699 number = n
700 } else {
701 number += 1
702 }
703 bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " "
704 } else {
705 bullet = utf8 ? (["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " ") : bulletText + " "
706 }
707 let indentation = descriptive ? Self.quoteMargin : bullet.count
708 let inner = Context(width: context.width - (descriptive ? Self.quoteMargin : bullet.count + checkbox.count), justify: context.justify)
709 let children = item.children.filter { $0.kind != .itemTag }
710 let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
711 // Each child alone, to find the first that writes something.
712 var contents = ""
713 var firstWriter: SyntaxNode?
714 for (i, child) in children.enumerated() {
715 let childEnd = i + 1 < children.count ? children[i + 1].range.lowerBound : item.range.upperBound
716 let text = try elements([child], end: childEnd, context: inner) { paragraph in
717 i == 0 && paragraph.range.lowerBound < NSMaxRange(bulletLine)
718 }
719 if firstWriter == nil, child.kind != .affiliatedKeyword, text.contains(where: { !$0.isWhitespace }) { firstWriter = child }
720 contents += text
721 }
722 if children.contains(where: { $0.kind == .affiliatedKeyword || $0.kind == .comment }) { throw Unsupported(reason: "Affiliated keywords and comments in list items") }
723 let indented = ASCIIText.indent(children.isEmpty ? "" : Self.normalize(contents), indentation)
724 var text = bullet + checkbox
725 if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstWriter?.kind == .paragraph {
726 text += LaTeXRenderer.trim(indented)
727 } else {
728 text += "\n" + indented
729 }
730 out += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
731 }
732 return out
733 }
734
735 // MARK: Tables
736
737 private func table(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String {
738 let rows = node.children.filter { $0.kind == .tableRow }
739 // Each row's cells, nil for a rule.
740 let raw: [[SyntaxNode]?] = rows.map { row in
741 let cells = row.children.filter { $0.kind == .tableCell }
742 return cells.isEmpty ? nil : cells
743 }
744 let cookie = /^<[lrc]?[0-9]*>$/
745 func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: CharacterSet(charactersIn: " |\n")) }
746 // Rows of only alignment cookies and empty cells.
747 let special = raw.map { cells -> Bool in
748 guard let cells else { return false }
749 let values = cells.map(value)
750 return values.contains { $0.wholeMatch(of: cookie) != nil } && values.allSatisfy { $0.isEmpty || $0.wholeMatch(of: cookie) != nil }
751 }
752 for cells in raw.compactMap({ $0 }) {
753 let first = value(cells[0])
754 if first == "/" || ["#", "!", "$", "*", "_", "^"].contains(first) { throw Unsupported(reason: "Tables with special columns or column groups") }
755 }
756 // Transcoded cells.
757 var data: [[String]?] = []
758 for (r, cells) in raw.enumerated() {
759 guard let cells, !special[r] else { data.append(nil); continue }
760 data.append(try cells.map { try LaTeXRenderer.trim(transcode(inlineItems($0, trimmed: true))) })
761 }
762 let columns = raw.compactMap { $0?.count }.max() ?? 0
763 var widths = Array(repeating: 0, count: columns)
764 var cookieWidth = Array(repeating: Int?.none, count: columns)
765 var cookieAlign = Array(repeating: String?.none, count: columns)
766 for (r, cells) in raw.enumerated() where special[r] {
767 for (c, cell) in cells!.enumerated() {
768 guard let m = value(cell).wholeMatch(of: /<([lrc])?([0-9]+)?>/) else { continue }
769 if let w = m.2.flatMap({ Int($0) }), cookieWidth[c] == nil { cookieWidth[c] = w }
770 if let a = m.1 { cookieAlign[c] = String(a) }
771 }
772 }
773 for row in data.compactMap({ $0 }) { for (c, cell) in row.enumerated() { widths[c] = max(widths[c], cell.count) } }
774 for c in 0..<columns { if let w = cookieWidth[c] { widths[c] = max(widths[c], w) } }
775 let number = LaTeXRenderer.numberPattern
776 let align: [Justify] = (0..<columns).map { c in
777 switch cookieAlign[c] {
778 case "l": return .left
779 case "r": return .right
780 case "c": return .center
781 default: break
782 }
783 var numbers = 0
784 var total = 0
785 var previousNumber = false
786 for (r, row) in data.enumerated() where raw[r] != nil && !special[r] {
787 let cell = c < row!.count ? row![c] : ""
788 total += 1
789 let isNumber = number.firstMatch(in: cell, range: NSRange(cell.startIndex..., in: cell)) != nil || (cell.isEmpty && previousNumber)
790 previousNumber = isNumber
791 if isNumber { numbers += 1 }
792 }
793 return total > 0 && Double(numbers) / Double(total) >= 0.5 ? .right : .left
794 }
795 let standard = data.indices.filter { data[$0] != nil }
796 var out = ""
797 for (position, r) in standard.enumerated() {
798 let row = data[r]!
799 let ruleAbove = raw[(position == 0 ? 0 : standard[position - 1] + 1)..<r].contains { $0 == nil }
800 let ruleBelow = raw[(r + 1)..<(position + 1 < standard.count ? standard[position + 1] : raw.count)].contains { $0 == nil }
801 func hline(_ char: String) -> String { row.indices.map { String(repeating: char, count: widths[$0] + 2) }.joined() + "\n" }
802 if position == 0, utf8 || ruleAbove {
803 out += hline(utf8 ? "━" : "-")
804 } else if position > 0, ruleAbove {
805 out += hline(utf8 ? "─" : "-")
806 }
807 out += row.enumerated().map { c, cell in
808 let pad = widths[c] - cell.count
809 let justified: String = switch align[c] {
810 case .left: cell + String(repeating: " ", count: pad)
811 case .right: String(repeating: " ", count: pad) + cell
812 case .center: String(repeating: " ", count: pad / 2) + cell + String(repeating: " ", count: pad - pad / 2)
813 }
814 return " " + justified + " "
815 }.joined() + "\n"
816 if position == standard.count - 1, utf8 || ruleBelow { out += hline(utf8 ? "━" : "-") }
817 }
818 let caption = try buildCaption(affiliated, type: "Table %d:", counter: &tableCount, context: context)
819 return Self.justifyBlock(out + (caption ?? ""), context: context)
820 }
821
822 private var tableCount = 0
823 private var listingCount = 0
824
825 /// `org-ascii--build-caption`.
826 private func buildCaption(_ affiliated: Affiliated, type: String, counter: inout Int, context: Context) throws -> String? {
827 guard !affiliated.caption.isEmpty else { return nil }
828 if affiliated.caption.count > 1 { throw Unsupported(reason: "Several captions") }
829 counter += 1
830 let saved = noting
831 noting = false
832 defer { noting = saved }
833 let text = try inlineString(affiliated.caption[0])
834 return ASCIIText.fill(translate(type).replacingOccurrences(of: "%d", with: String(counter)) + " " + text, width: context.width)
835 }
836
837 // MARK: Blocks
838
839 private func block(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
840 var lines = node.text.components(separatedBy: "\n")
841 if lines.last == "" { lines.removeLast() }
842 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
843 let type = m.1.lowercased()
844 let parameters = String(m.2)
845 let body = Array(lines.dropFirst().dropLast())
846 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
847 let text = unescaped.joined(separator: "\n")
848 switch type {
849 case "src", "example":
850 let code = try formatCode(lines)
851 var out = box(code)
852 if type == "src", let caption = try buildCaption(affiliated, type: "Listing %d:", counter: &listingCount, context: context) {
853 out += "\n" + caption
854 }
855 return Self.justifyBlock(out, context: context)
856 case "quote":
857 guard let contents = try blockContents(unescaped, context: Context(width: context.width - 2 * Self.quoteMargin, justify: context.justify)) else { return nil }
858 return ASCIIText.indent(contents, Self.quoteMargin)
859 case "center":
860 return try blockContents(unescaped, context: Context(width: context.width, justify: .center))
861 case "verse":
862 return ASCIIText.indent(Self.justifyBlock(try verse(unescaped), context: context), Self.quoteMargin)
863 case "export":
864 let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
865 guard backend == "ASCII" else { return nil }
866 return Self.justifyBlock(text + "\n", context: context)
867 case "comment":
868 return nil
869 default:
870 var inner = context
871 if m.1 == "JUSTIFYRIGHT" { inner.justify = .right }
872 if m.1 == "JUSTIFYLEFT" { inner.justify = .left }
873 return try blockContents(unescaped, context: inner)
874 }
875 }
876
877 /// A greater block's contents, parsed as elements; nil when it has none.
878 private func blockContents(_ lines: [String], context: Context) throws -> String? {
879 guard !lines.isEmpty else { return nil }
880 if lines[0].allSatisfy({ $0 == " " || $0 == "\t" }) { throw Unsupported(reason: "Blocks opening with a blank line") }
881 let text = lines.joined(separator: "\n") + "\n"
882 let tree = OrgParser.parse(text, defaults: settings)
883 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
884 if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
885 let saved = (currentSource, exportSource)
886 currentSource = text as NSString
887 exportSource = ExportSource(tree: tree, text: text)
888 defer { (currentSource, exportSource) = saved }
889 guard hasContents(nodes) else { return nil }
890 return Self.normalize(try elements(nodes, end: (text as NSString).length, context: context))
891 }
892
893 /// `org-export-format-code-default` for a src or example block's lines.
894 private func formatCode(_ lines: [String]) throws -> String {
895 guard let parsed = Coderef.block(lines) else { return "\n" }
896 let blockLoc = try blockLoc(lines, numbered: parsed.switches.numberLines != nil)
897 var value = parsed.body.joined(separator: "\n")
898 if !value.isEmpty { value += "\n" }
899 let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
900 var code = preserve ? value : try LaTeXRenderer.removeIndentation(value)
901 if code.hasSuffix("\n") { code.removeLast() }
902 let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
903 let loc = parsed.switches.numberLines == nil ? nil : blockLoc
904 guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
905 let width = loc.map { String($0 + lines.count).count } ?? 0
906 let numberWidth = loc == nil ? 0 : width + 2
907 let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
908 return lines.enumerated().map { index, line in
909 var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
910 out += line
911 if parsed.switches.retainLabels, let ref = refs[index + 1] {
912 out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
913 }
914 return out
915 }.joined(separator: "\n") + "\n"
916 }
917
918 /// The src and example blocks the export writes, in order, as their lines.
919 private lazy var exportedBlocks: [[String]] = {
920 let source = ExportSource(tree: tree, text: self.source as String)
921 return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
922 var lines = node.text.components(separatedBy: "\n")
923 if lines.last == "" { lines.removeLast() }
924 guard Coderef.block(lines) != nil, !excluded(node), !isResults(node) else { return nil }
925 if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
926 return lines
927 }
928 }()
929
930 /// Whether `node` is the results of the src block before it, which the export removes.
931 private func isResults(_ node: SyntaxNode) -> Bool {
932 guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
933 let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
934 guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
935 let before = index - keywords.count - 1
936 return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
937 }
938
939 /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
940 private lazy var blockLocs: [String: [Int?]] = {
941 let blocks = exportedBlocks
942 var locs: [String: [Int?]] = [:]
943 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
944 locs[lines.joined(separator: "\n"), default: []].append(loc)
945 }
946 return locs
947 }()
948
949 /// `org-export-get-loc` of the block with `lines`, the next of those with the same text.
950 private func blockLoc(_ lines: [String], numbered: Bool) throws -> Int? {
951 let key = lines.joined(separator: "\n")
952 guard let queue = blockLocs[key], !queue.isEmpty else {
953 if numbered { throw Unsupported(reason: "Numbered blocks inside other blocks") }
954 return nil
955 }
956 blockLocs[key] = Array(queue.dropFirst())
957 return queue[0]
958 }
959
960 /// Whether `node` is under a section the export leaves out.
961 private func excluded(_ node: SyntaxNode) -> Bool {
962 var current: SyntaxNode? = node
963 while let n = current {
964 if n.kind == .section, let heading = n.firstChild(.heading),
965 HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .all { return true }
966 current = n.parent
967 }
968 return false
969 }
970
971 /// A verse block's objects, their common indentation removed.
972 private func verse(_ lines: [String]) throws -> String {
973 let text = lines.joined(separator: "\n") + "\n"
974 let tree = OrgParser.parse(text, defaults: settings)
975 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
976 guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
977 let ns = text as NSString
978 var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
979 for (index, node) in nodes.enumerated() {
980 raw += inlineItems(node)
981 let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
982 raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
983 }
984 return try transcode(LaTeXRenderer.normalizeIndentation(LaTeXRenderer.merge(raw), ignoreFirst: false))
985 }
986
987 // MARK: - Objects
988
989 /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
990 func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) -> [Inline] {
991 var items: [Inline] = []
992 var skipNewline = false
993 for element in node.elements {
994 switch element {
995 case .token(let token):
996 switch token.kind {
997 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
998 continue
999 default:
1000 var text = token.text
1001 if skipNewline {
1002 let rest = text.drop { $0 == " " || $0 == "\t" }
1003 if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1004 }
1005 if !text.isEmpty { items.append(.text(text)) }
1006 }
1007 case .node(let child):
1008 skipNewline = false
1009 switch child.kind {
1010 case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1011 items.append(.object(child, inlineItems(child)))
1012 case .link:
1013 items.append(.object(child, child.firstChild(.linkDescription).map { inlineItems($0) } ?? []))
1014 case .superscript, .subscript:
1015 let text = child.text
1016 let braced = text.dropFirst().hasPrefix("{")
1017 if options.scripts == .off || (options.scripts == .braces && !braced) {
1018 items.append(.text(text))
1019 } else if braced {
1020 items.append(.object(child, inlineItems(child)))
1021 } else {
1022 items.append(.object(child, [.text(String(text.dropFirst()))]))
1023 }
1024 case .lineBreak where trimmed:
1025 items.append(.text(child.text))
1026 case .lineBreak:
1027 items.append(.object(child, []))
1028 skipNewline = true
1029 default:
1030 items.append(.object(child, []))
1031 }
1032 }
1033 }
1034 if trimmed {
1035 if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1036 if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1037 }
1038 return LaTeXRenderer.merge(items)
1039 }
1040
1041 /// One line of Org text transcoded, for keywords and captions.
1042 func inlineString(_ text: String) throws -> String {
1043 let tree = OrgParser.parse(text, defaults: settings)
1044 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1045 if tree.root.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in keywords and captions") }
1046 let saved = exportSource
1047 exportSource = ExportSource(tree: tree, text: text)
1048 defer { exportSource = saved }
1049 return LaTeXRenderer.trim(try transcode(inlineItems(paragraph)))
1050 }
1051
1052 /// `org-export-data` over objects: objects that export nothing taking their blanks with
1053 /// them unless they are needed.
1054 func transcode(_ items: [Inline]) throws -> String {
1055 var out = ""
1056 var index = 0
1057 var dropBlanks = false
1058 var afterObject = false
1059 while index < items.count {
1060 let item = items[index]
1061 switch item {
1062 case .text(var t):
1063 if dropBlanks {
1064 t = String(t.drop { $0 == " " || $0 == "\t" })
1065 } else if afterObject {
1066 let blanks = t.prefix { $0 == " " || $0 == "\t" }
1067 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1068 }
1069 dropBlanks = false
1070 afterObject = false
1071 out += plainText(t)
1072 index += 1
1073 case .object(let node, let children):
1074 dropBlanks = false
1075 afterObject = true
1076 if let result = try object(node, children) {
1077 out += result
1078 } else {
1079 // `org-export--keep-spaces`: blanks after a dropped object stay only
1080 // between text that has none.
1081 let previousBlank: Bool
1082 if index == 0 {
1083 previousBlank = true
1084 } else if case .text(let t) = items[index - 1] {
1085 previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1086 } else {
1087 previousBlank = false
1088 }
1089 dropBlanks = previousBlank
1090 }
1091 index += 1
1092 }
1093 }
1094 return out
1095 }
1096
1097 private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1098 switch node.kind {
1099 case .bold: return "*\(try transcode(children))*"
1100 case .italic: return "/\(try transcode(children))/"
1101 case .underline: return "_\(try transcode(children))_"
1102 case .strikeThrough: return "+\(try transcode(children))+"
1103 case .verbatim, .code: return "`\(node.text.dropFirst().dropLast())'"
1104 case .link: return try link(node, children)
1105 case .linkDescription: return try transcode(children)
1106 case .timestamp: return plainText(ASCIIText.timestamp(node.text))
1107 case .footnoteReference: return try footnoteReference(node)
1108 case .entity:
1109 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1110 guard let entity = OrgEntities.text[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1111 return switch charset {
1112 case .ascii: entity.ascii
1113 case .latin1: entity.latin1
1114 case .utf8: entity.utf8
1115 }
1116 case .superscript: return node.text.dropFirst().hasPrefix("{") ? "^{\(try transcode(children))}" : "^\(try transcode(children))"
1117 case .subscript: return node.text.dropFirst().hasPrefix("{") ? "_{\(try transcode(children))}" : "_\(try transcode(children))"
1118 case .lineBreak: return Self.hardNewline
1119 case .latexFragment: return options.tex ? node.text : nil
1120 case .statisticsCookie: return node.text
1121 case .exportSnippet:
1122 let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1123 guard backend == "ascii" else { return nil }
1124 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1125 case .target:
1126 return nil
1127 case .macro:
1128 guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1129 return try value.map(inlineString)
1130 default:
1131 throw Unsupported(reason: "\(node.kind)")
1132 }
1133 }
1134
1135 /// `org-ascii-plain-text`.
1136 func plainText(_ text: String) -> String {
1137 guard options.specialStrings else { return text }
1138 let text = text.replacingOccurrences(of: "\\-", with: "")
1139 guard utf8 else { return text }
1140 return text.replacingOccurrences(of: "---", with: "—").replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…")
1141 }
1142
1143 // MARK: Links
1144
1145 /// A link written in notes mode: its footprint and how `org-ascii--describe-links`
1146 /// describes it, nil for none.
1147 private struct Noted {
1148 var footprint: String
1149 var note: String?
1150 }
1151
1152 /// Links written so far, for their section's notes.
1153 private var noted: [Noted] = []
1154 /// Whether links written now are noted: not in captions.
1155 private var noting = true
1156
1157 /// `org-ascii--describe-links` for the links noted since `start`, each once.
1158 private func describeLinks(from start: Int, width: Int) -> String {
1159 guard linksToNotes else { return "" }
1160 var seen: Set<String> = []
1161 var out = ""
1162 for link in noted[start...] where !seen.contains(link.footprint) {
1163 seen.insert(link.footprint)
1164 if let note = link.note { out += ASCIIText.fill(note, width: width) + "\n\n" }
1165 }
1166 noted.removeSubrange(start...)
1167 return out
1168 }
1169
1170 private static let externalTypes: Set<String> = ["attachment", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1171
1172 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1173 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1174 throw Unsupported(reason: "Links in link descriptions")
1175 }
1176 let pathToken = node.tokens.first { $0.kind == .linkPath }?.text
1177 var raw = pathToken ?? node.text
1178 if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) }
1179 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1180 if description?.contains(where: { !$0.isWhitespace }) != true { description = nil }
1181 let footprint = raw + "\u{0}" + (node.firstChild(.linkDescription)?.text ?? "").split(whereSeparator: { " \t\n\r".contains($0) }).joined(separator: " ")
1182 // Only the link types Org knows have a scheme; `foo:bar` is a fuzzy link.
1183 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 }
1184 if raw.hasPrefix("(") && raw.hasSuffix(")") {
1185 let path = String(raw.dropFirst().dropLast())
1186 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1187 var format = description ?? "%s"
1188 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1189 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1190 }
1191 let internalLink = raw.hasPrefix("#") || scheme == "id" || (scheme == nil && !raw.hasPrefix("/") && !raw.hasPrefix("./") && !raw.hasPrefix("../") && !raw.hasPrefix("~"))
1192 if internalLink {
1193 let type = raw.hasPrefix("#") ? "custom-id" : scheme == "id" ? "id" : "fuzzy"
1194 let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw
1195 if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) {
1196 throw Unsupported(reason: "Links to targets and named elements")
1197 }
1198 guard let heading = resolveHeading(type: type, path: path) else {
1199 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1200 }
1201 let datum = try describeHeading(heading)
1202 if let description {
1203 if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(datum.see)" : nil)) }
1204 return linksToNotes ? "[\(description)]" : "[\(description)] (\(datum.see))"
1205 }
1206 if noting { noted.append(Noted(footprint: footprint, note: nil)) }
1207 return datum.reference
1208 }
1209 if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) }
1210 return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>"
1211 }
1212
1213 /// A heading as a link without a description writes it, and as
1214 /// `org-ascii--describe-datum` does.
1215 private func describeHeading(_ heading: HeadingInfo) throws -> (reference: String, see: String) {
1216 let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".")
1217 let text: String
1218 if let number {
1219 text = number
1220 } else {
1221 guard let node = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }) else { return ("", "") }
1222 let saved = noting
1223 noting = false
1224 defer { noting = saved }
1225 text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? ""
1226 }
1227 return (text, translate("See section %s").replacingOccurrences(of: "%s", with: text))
1228 }
1229
1230 /// Whether a `<<target>>` has the name a fuzzy link gives.
1231 private func target(_ path: String) -> Bool {
1232 let search = LaTeXRenderer.words(path)
1233 return tree.root.descendants().contains { $0.kind == .target && LaTeXRenderer.words(String($0.text.dropFirst(2).dropLast(2))) == search }
1234 }
1235
1236 /// Whether an element has the `#+NAME` a fuzzy link gives.
1237 private func namedElement(_ path: String) -> Bool {
1238 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1239 return tree.root.descendants().contains { node in
1240 guard node.kind == .affiliatedKeyword, let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { return false }
1241 let words = String(m.1).split(whereSeparator: \.isWhitespace).map(String.init)
1242 return words == search || words == search.map { $0.uppercased() }
1243 }
1244 }
1245
1246 /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1247 private func resolveHeading(type: String, path: String) -> HeadingInfo? {
1248 let starts = Set(exported.map(\.start))
1249 let headings = model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1250 switch type {
1251 case "custom-id":
1252 return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1253 case "id":
1254 return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1255 default:
1256 let search = LaTeXRenderer.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1257 return headings.first { heading in
1258 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1259 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1260 return LaTeXRenderer.words(raw) == search
1261 }
1262 }
1263 }
1264
1265 // MARK: Footnotes
1266
1267 /// Footnote numbers by label, in the order of first references.
1268 private var footnoteNumbers: [String: Int] = [:]
1269 /// What each number's footnote says: a definition's label, or an inline definition.
1270 private var footnoteOrder: [(label: String?, inline: String?)] = []
1271 private var inFootnote = false
1272
1273 /// `org-ascii-footnote-reference`.
1274 private func footnoteReference(_ node: SyntaxNode) throws -> String {
1275 guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1276 if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1277 let label = String(m.1)
1278 if !label.isEmpty, let number = footnoteNumbers[label] { return "[\(number)]" }
1279 if m.2 == nil, label.isEmpty || definition(label) == nil { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1280 footnoteOrder.append((label.isEmpty ? nil : label, m.2.map(String.init)))
1281 if !label.isEmpty { footnoteNumbers[label] = footnoteOrder.count }
1282 return "[\(footnoteOrder.count)]"
1283 }
1284
1285 /// The definition of `label` and the text width where it is.
1286 private func definition(_ label: String) -> (text: String, width: Int)? {
1287 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
1288 guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/), m.1 == label else { continue }
1289 var width = Self.textWidth
1290 var current = node.parent
1291 while let n = current {
1292 if n.kind == .section, let heading = n.firstChild(.heading) {
1293 let level = self.level(heading)
1294 width -= level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin
1295 break
1296 }
1297 current = n.parent
1298 }
1299 if excluded(node) { return nil }
1300 return (String(node.text[m.range.upperBound...]), width)
1301 }
1302 return nil
1303 }
1304
1305 /// The footnote definitions, as `org-ascii-inner-template` writes them.
1306 private func footnotes() throws -> String {
1307 linksToNotes = false
1308 inFootnote = true
1309 defer {
1310 linksToNotes = true
1311 inFootnote = false
1312 }
1313 var parts: [String] = []
1314 for (index, footnote) in footnoteOrder.enumerated() {
1315 let id = "[\(index + 1)] "
1316 if let inline = footnote.inline {
1317 parts.append(LaTeXRenderer.trim(ASCIIText.fill(id + (try inlineObjects(inline)), width: Self.textWidth)))
1318 continue
1319 }
1320 guard let label = footnote.label, let (text, width) = definition(label) else { continue }
1321 let tree = OrgParser.parse(text, defaults: settings)
1322 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1323 let saved = (currentSource, exportSource)
1324 currentSource = text as NSString
1325 exportSource = ExportSource(tree: tree, text: text)
1326 defer { (currentSource, exportSource) = saved }
1327 let context = Context(width: width)
1328 if let first = nodes.first, first.kind == .paragraph {
1329 var out = Self.normalize(try paragraph(first, context: context, ignoreFirst: true, prefix: id))
1330 out += String(repeating: "\n", count: blankLines(from: first.range.lowerBound, to: nodes.count > 1 ? nodes[1].range.lowerBound : (text as NSString).length))
1331 out += try elements(Array(nodes.dropFirst()), end: (text as NSString).length, context: context)
1332 parts.append(LaTeXRenderer.trim(out))
1333 } else {
1334 parts.append(LaTeXRenderer.trim(id + "\n" + (try elements(nodes, end: (text as NSString).length, context: context))))
1335 }
1336 }
1337 return parts.joined(separator: "\n\n")
1338 }
1339
1340 /// An inline definition's objects transcoded.
1341 private func inlineObjects(_ text: String) throws -> String {
1342 let tree = OrgParser.parse(text, defaults: settings)
1343 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1344 return try transcode(inlineItems(paragraph))
1345 }
1346}
Sources/OrgCore/Export/ASCIIText.swift +42 −5
@@ -118,17 +118,54 @@ struct ASCIIText {
118118
119119 static let hardNewline = "\u{1}"
120120
121 /// `fill-context-prefix` with `adaptive-fill-regexp`: the second line's prefix when the
122 /// first has its characters, else what they share; for one line, its prefix, as spaces
123 /// unless it is blank.
124 static func fillPrefix(_ lines: [String]) -> String {
125 func adaptive(_ line: String) -> String { String(line.prefix { "-–!|#%;>*·•‣⁃◦ \t".contains($0) }) }
126 let first = adaptive(lines[0])
127 guard lines.count >= 2 else {
128 return first.allSatisfy { $0 == " " || $0 == "\t" } ? first : String(repeating: " ", count: first.count)
129 }
130 let second = adaptive(lines[1])
131 var rest = Substring(first)
132 let inOrder = second.split(whereSeparator: { $0 == " " || $0 == "\t" }).allSatisfy { chunk in
133 guard let range = rest.range(of: chunk) else { return false }
134 rest = rest[range.upperBound...]
135 return true
136 }
137 if inOrder { return second }
138 return String(zip(first, second).prefix { $0 == $1 }.map(\.0))
139 }
140
141 /// The length of what `fill-delete-prefix` takes from the start of `line`: blanks, `prefix`
142 /// with any blanks in it, blanks.
143 static func deletedPrefix(_ line: String, _ prefix: String) -> Int {
144 let chars = Array(line)
145 var i = 0
146 func blanks() { while i < chars.count, chars[i] == " " || chars[i] == "\t" { i += 1 } }
147 blanks()
148 let core = prefix.split(whereSeparator: { $0 == " " || $0 == "\t" })
149 guard !core.isEmpty else { return i }
150 let start = i
151 for (n, chunk) in core.enumerated() {
152 if n > 0 { blanks() }
153 guard chars.count - i >= chunk.count, String(chars[i..<(i + chunk.count)]) == chunk else { i = start; break }
154 i += chunk.count
155 }
156 blanks()
157 return i
158 }
159
121160 static func fillParagraph(_ text: String, width: Int) -> String {
122161 var lines = text.components(separatedBy: "\n")
123162 while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() }
124163 guard !lines.isEmpty else { return "" }
125 func indentation(_ line: String) -> String { String(line.prefix { $0 == " " || $0 == "\t" }) }
126 let first = indentation(lines[0])
127 // `fill-context-prefix`: the second line's indentation when the first starts with it.
128 let prefix = lines.count >= 2 ? (lines[0].hasPrefix(indentation(lines[1])) ? indentation(lines[1]) : "") : first
164 let prefix = fillPrefix(lines)
165 let first = String(lines[0].prefix(deletedPrefix(lines[0], prefix)))
129166 var parts: [String] = []
130167 for (i, line) in lines.enumerated() {
131 var content = String(line.dropFirst(indentation(line).count))
168 var content = String(line.dropFirst(deletedPrefix(line, prefix)))
132169 while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() }
133170 // A sentence ending a line gets the second space it would have.
134171 if i < lines.count - 1, content.range(of: "[.?!…‽][]\"'”’)}»›]*$", options: .regularExpression) != nil { content += " " }
Sources/OrgCore/Export/ExportDictionary.swift +187 −1
@@ -4,7 +4,7 @@ import Foundation
44/// org-clock.el `org-clock-clocktable-language-setup`, Org 9.8.7), for `#+LANGUAGE` and
55/// `org-export-default-language`.
66public enum ExportDictionary {
7 public enum Encoding: String, Sendable { case html, ascii, utf8 = "utf-8", latex }
7 public enum Encoding: String, Sendable { case html, ascii, latin1, utf8 = "utf-8", latex }
88
99 /// `org-export-translate`: the encoding's translation, else the language's default, else `term`.
1010 public static func translate(_ term: String, language: String, encoding: Encoding) -> String {
@@ -110,6 +110,192 @@ public enum ExportDictionary {
110110 "zh-CN": ["html": "&#33050;&#27880;", "utf-8": "脚注"],
111111 "zh-TW": ["html": "&#33139;&#35387;", "utf-8": "腳註"],
112112 ],
113 "See section %s": [
114 "ar": ["default": "انظر قسم %s"],
115 "cs": ["default": "Viz sekce %s"],
116 "da": ["default": "jævnfør afsnit %s"],
117 "de": ["default": "Siehe Abschnitt %s"],
118 "es": ["ascii": "Vea seccion %s", "html": "Vea secci&oacute;n %s", "default": "Vea sección %s"],
119 "et": ["default": "Vaata peatükki %s", "html": "Vaata peat&#252;kki %s", "utf-8": "Vaata peatükki %s"],
120 "fa": ["default": "نمایش بخش %s"],
121 "fr": ["default": "cf. section %s"],
122 "it": ["default": "Vedi sezione %s"],
123 "ja": ["default": "セクション %s を参照"],
124 "nl": ["default": "Zie sectie %s", "html": "Zie sectie&nbsp;%s", "latex": "Zie sectie~%s"],
125 "nn": ["default": "Sjå del %s"],
126 "pl": ["default": "Patrz sekcja %s"],
127 "pt_BR": ["html": "Veja a se&ccedil;&atilde;o %s", "default": "Veja a seção %s", "ascii": "Veja a secao %s"],
128 "ro": ["default": "Vezi secțiunea %s"],
129 "ru": ["html": "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s", "utf-8": "См. раздел %s"],
130 "sl": ["default": "Glej poglavje %d"],
131 "sv": ["default": "Se avsnitt %s"],
132 "tr": ["default": "bkz. bölüm %s"],
133 "zh-CN": ["html": "&#21442;&#35265;&#31532;%s&#33410;", "utf-8": "参见第%s节"],
134 ],
135 "Table %d:": [
136 "ar": ["default": "جدول %d:"],
137 "cs": ["default": "Tabulka %d:"],
138 "da": ["default": "Tabel %d:"],
139 "de": ["default": "Tabelle %d:"],
140 "es": ["default": "Tabla %d:"],
141 "et": ["default": "Tabel %d:"],
142 "fa": ["default": "جدول %d:"],
143 "fr": ["default": "Tableau %d:"],
144 "is": ["default": "Tafla %d:"],
145 "it": ["default": "Tabella %d:"],
146 "ja": ["default": "表%d:", "html": "&#34920;%d:"],
147 "nl": ["default": "Tabel %d:", "html": "Tabel&nbsp;%d:"],
148 "no": ["default": "Tabell %d:"],
149 "nb": ["default": "Tabell %d:"],
150 "nn": ["default": "Tabell %d:"],
151 "pl": ["default": "Tabela %d:"],
152 "pt_BR": ["default": "Tabela %d:"],
153 "ro": ["default": "Tabel %d:"],
154 "ru": ["html": "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:", "utf-8": "Таблица %d.:"],
155 "sl": ["default": "Tabela %d:"],
156 "sv": ["default": "Tabell %d:"],
157 "tr": ["default": "Tablo %d:"],
158 "zh-CN": ["html": "&#34920;%d&nbsp;", "utf-8": "表%d "],
159 ],
160 "Listing %d:": [
161 "ar": ["default": "برنامج %d:"],
162 "cs": ["default": "Program %d:"],
163 "da": ["default": "Program %d:"],
164 "de": ["default": "Programmlisting %d:"],
165 "es": ["default": "Listado de programa %d:"],
166 "et": ["default": "Loend %d:"],
167 "fa": ["default": "برنامه‌ریزی %d:"],
168 "fr": ["default": "Programme %d:", "html": "Programme&nbsp;%d&nbsp;:"],
169 "it": ["default": "Listato %d:"],
170 "ja": ["default": "ソースコード%d:"],
171 "nl": ["default": "Programma %d:", "html": "Programma&nbsp;%d:"],
172 "nn": ["default": "Program %d:"],
173 "no": ["default": "Dataprogram %d:"],
174 "nb": ["default": "Dataprogram %d:"],
175 "ro": ["default": "Lista %d:"],
176 "pl": ["default": "Indeks %d:"],
177 "pt_BR": ["default": "Listagem %d:"],
178 "ru": ["html": "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:", "utf-8": "Распечатка %d.:"],
179 "sl": ["default": "Izpis programa %d:"],
180 "sv": ["default": "Programlistning %d:"],
181 "tr": ["default": "Program %d:"],
182 "zh-CN": ["html": "&#20195;&#30721;%d&nbsp;", "utf-8": "代码%d "],
183 ],
184 "List of Tables": [
185 "ar": ["default": "قائمة بالجداول"],
186 "cs": ["default": "Seznam tabulek"],
187 "da": ["default": "Tabeller"],
188 "de": ["default": "Tabellenverzeichnis"],
189 "es": ["ascii": "Indice de tablas", "html": "&Iacute;ndice de tablas", "default": "Índice de tablas"],
190 "et": ["default": "Tabelite nimekiri"],
191 "fa": ["default": "فهرست جدول‌ها"],
192 "fr": ["default": "Liste des tableaux"],
193 "is": ["default": "Töfluskrá", "html": "T&ouml;fluskr&aacute;"],
194 "it": ["default": "Indice delle tabelle"],
195 "ja": ["default": "表目次"],
196 "nl": ["default": "Lijst van tabellen"],
197 "no": ["default": "Tabeller"],
198 "nb": ["default": "Tabeller"],
199 "nn": ["default": "Tabeller"],
200 "pl": ["default": "Indeks tabel"],
201 "pt_BR": ["html": "&Iacute;ndice de Tabelas", "default": "Índice de Tabelas", "ascii": "Indice de Tabelas"],
202 "ro": ["default": "Tabele"],
203 "ru": ["html": "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;", "utf-8": "Список таблиц"],
204 "sl": ["default": "Seznam tabel"],
205 "sv": ["default": "Tabeller"],
206 "tr": ["default": "Tablo Listesi"],
207 "zh-CN": ["html": "&#34920;&#26684;&#30446;&#24405;", "utf-8": "表格目录"],
208 ],
209 "List of Listings": [
210 "ar": ["default": "قائمة بالبرامج"],
211 "cs": ["default": "Seznam programů"],
212 "da": ["default": "Programmer"],
213 "de": ["default": "Programmauflistungsverzeichnis"],
214 "es": ["ascii": "Indice de Listados de programas", "html": "&Iacute;ndice de Listados de programas", "default": "Índice de Listados de programas"],
215 "et": ["default": "Loendite nimekiri"],
216 "fa": ["default": "فهرست برنامه‌ریزی‌ها"],
217 "fr": ["default": "Liste des programmes"],
218 "ja": ["default": "ソースコード目次"],
219 "nl": ["default": "Lijst van programma's"],
220 "nn": ["default": "Programliste"],
221 "no": ["default": "Dataprogrammer"],
222 "nb": ["default": "Dataprogrammer"],
223 "pl": ["default": "Indeks"],
224 "pt_BR": ["html": "&Iacute;ndice de Listagens", "default": "Índice de Listagens", "ascii": "Indice de Listagens"],
225 "ru": ["html": "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;", "utf-8": "Список распечаток"],
226 "sl": ["default": "Seznam programskih izpisov"],
227 "sv": ["default": "Programlistningar"],
228 "tr": ["default": "Program Listesi"],
229 "zh-CN": ["html": "&#20195;&#30721;&#30446;&#24405;", "utf-8": "代码目录"],
230 ],
231 "Unknown reference": [
232 "ar": ["default": "مرجع غير معرّف"],
233 "da": ["default": "ukendt reference"],
234 "de": ["default": "Unbekannter Verweis"],
235 "es": ["default": "Referencia desconocida"],
236 "et": ["default": "Tundmatu viide"],
237 "fa": ["default": "منبع ناشناس"],
238 "fr": ["ascii": "Destination inconnue", "default": "Référence inconnue"],
239 "it": ["default": "Riferimento sconosciuto"],
240 "ja": ["default": "不明な参照先"],
241 "nl": ["default": "Onbekende verwijzing"],
242 "nn": ["default": "Ukjend kjelde"],
243 "pl": ["default": "Nieznane odwołanie"],
244 "pt_BR": ["html": "Refer&ecirc;ncia desconhecida", "default": "Referência desconhecida", "ascii": "Referencia desconhecida"],
245 "ro": ["default": "Referință necunoscută"],
246 "ru": ["html": "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;", "utf-8": "Неизвестная ссылка"],
247 "sl": ["default": "Neznana referenca"],
248 "sv": ["default": "Okänd referens"],
249 "tr": ["default": "Bilinmeyen referans"],
250 "zh-CN": ["html": "&#26410;&#30693;&#24341;&#29992;", "utf-8": "未知引用"],
251 ],
252 "See figure %s": [
253 "cs": ["default": "Viz obrázek %s"],
254 "et": ["default": "Vaata joonist %s"],
255 "de": ["default": "Siehe Abbildung %s"],
256 "fa": ["default": "نمایش شکل %s"],
257 "fr": ["default": "cf. figure %s", "html": "cf.&nbsp;figure&nbsp;%s", "latex": "cf.~figure~%s"],
258 "it": ["default": "Vedi figura %s"],
259 "nl": ["default": "Zie figuur %s", "html": "Zie figuur&nbsp;%s", "latex": "Zie figuur~%s"],
260 "nn": ["default": "Sjå figur %s"],
261 "pl": ["default": "Patrz obrazek %s"],
262 "pt_BR": ["default": "Veja a figura %s"],
263 "ro": ["default": "Vezi figura %s"],
264 "sl": ["default": "Glej sliko %s"],
265 "sv": ["default": "Se illustration %s"],
266 "tr": ["default": "bkz. şekil %s"],
267 ],
268 "See table %s": [
269 "cs": ["default": "Viz tabulka %s"],
270 "et": ["default": "Vaata tabelit %s"],
271 "de": ["default": "Siehe Tabelle %s"],
272 "fa": ["default": "نمایش جدول %s"],
273 "fr": ["default": "cf. tableau %s", "html": "cf.&nbsp;tableau&nbsp;%s", "latex": "cf.~tableau~%s"],
274 "it": ["default": "Vedi tabella %s"],
275 "nl": ["default": "Zie tabel %s", "html": "Zie tabel&nbsp;%s", "latex": "Zie tabel~%s"],
276 "nn": ["default": "Sjå tabell %s"],
277 "pl": ["default": "Patrz tabela %s"],
278 "pt_BR": ["default": "Veja a tabela %s"],
279 "ro": ["default": "Vezi tabelul %s"],
280 "sl": ["default": "Glej tabelo %s"],
281 "sv": ["default": "Se tabell %s"],
282 "tr": ["default": "bkz. tablo %s"],
283 ],
284 "See listing %s": [
285 "cs": ["default": "Viz program %s"],
286 "et": ["default": "Vaata loendit %s"],
287 "de": ["default": "Siehe Programmlisting %s"],
288 "fa": ["default": "نمایش برنامه‌ریزی %s"],
289 "fr": ["default": "cf. programme %s", "html": "cf.&nbsp;programme&nbsp;%s", "latex": "cf.~programme~%s"],
290 "nl": ["default": "Zie programma %s", "html": "Zie programma&nbsp;%s", "latex": "Zie programma~%s"],
291 "nn": ["default": "Sjå program %s"],
292 "pl": ["default": "Patrz indeks %s"],
293 "pt_BR": ["default": "Veja a listagem %s"],
294 "ro": ["default": "Vezi tabelul %s"],
295 "sl": ["default": "Glej izpis programa %s"],
296 "sv": ["default": "Se programlistning %s"],
297 "tr": ["default": "bkz. program %s"],
298 ],
113299 ]
114300
115301 static let clockTable: [String: [String]] = [
Sources/OrgCore/Export/LaTeXExport.swift +13 −8
@@ -44,6 +44,18 @@ public enum LaTeXExport {
4444 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
4545 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false
4646 ) throws -> String {
47 let text = try expanded(text, settings: settings, path: path, now: now)
48 let tree = OrgParser.parse(text, defaults: settings)
49 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
50 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
51 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
52 let body = try renderer.body()
53 let output = bodyOnly ? body : try renderer.template(body, author: author, now: now, timeZone: timeZone)
54 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
55 }
56
57 /// `text` with `#+INCLUDE`s and macros expanded, as `org-export-as` does before parsing.
58 static func expanded(_ text: String, settings: OrgSettings, path: String?, now: Date) throws -> String {
4759 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
4860 let included = ExportPreprocess.includes(text, directory: directory)
4961 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
@@ -63,14 +75,7 @@ public enum LaTeXExport {
6375 }
6476 literal = out + ns.substring(from: at)
6577 }
66 let text = ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{")
67 let tree = OrgParser.parse(text, defaults: settings)
68 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
69 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
70 let renderer = try LaTeXRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language)
71 let body = try renderer.body()
72 let output = bodyOnly ? body : try renderer.template(body, author: author, now: now, timeZone: timeZone)
73 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
78 return ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{")
7479 }
7580}
7681
Sources/OrgCore/Semantic/OrgEntities.swift +417
@@ -833,4 +833,421 @@ enum OrgEntities {
833833 "_ ": ("\\hspace*{9.5em}", false),
834834 "_ ": ("\\hspace*{10.0em}", false),
835835 ]
836
837 /// Entity name to its ASCII, Latin-1 and UTF-8 text (`org-entities`' fifth to seventh
838 /// fields), for plain text export. The first definition of a name wins; `setminus`, whose
839 /// Latin-1 field isn't a string in Org 9.8.7, is left out.
840 static let text: [String: (ascii: String, latin1: String, utf8: String)] = [
841 "Agrave": ("A", "À", "À"),
842 "agrave": ("a", "à", "à"),
843 "Aacute": ("A", "Á", "Á"),
844 "aacute": ("a", "á", "á"),
845 "Acirc": ("A", "Â", "Â"),
846 "acirc": ("a", "â", "â"),
847 "Amacr": ("A", "Ã", "Ã"),
848 "amacr": ("a", "ã", "ã"),
849 "Atilde": ("A", "Ã", "Ã"),
850 "atilde": ("a", "ã", "ã"),
851 "Auml": ("Ae", "Ä", "Ä"),
852 "auml": ("ae", "ä", "ä"),
853 "Aring": ("A", "Å", "Å"),
854 "AA": ("A", "Å", "Å"),
855 "aring": ("a", "å", "å"),
856 "AElig": ("AE", "Æ", "Æ"),
857 "aelig": ("ae", "æ", "æ"),
858 "Ccedil": ("C", "Ç", "Ç"),
859 "ccedil": ("c", "ç", "ç"),
860 "Egrave": ("E", "È", "È"),
861 "egrave": ("e", "è", "è"),
862 "Eacute": ("E", "É", "É"),
863 "eacute": ("e", "é", "é"),
864 "Ecirc": ("E", "Ê", "Ê"),
865 "ecirc": ("e", "ê", "ê"),
866 "Euml": ("E", "Ë", "Ë"),
867 "euml": ("e", "ë", "ë"),
868 "Igrave": ("I", "Ì", "Ì"),
869 "igrave": ("i", "ì", "ì"),
870 "Iacute": ("I", "Í", "Í"),
871 "iacute": ("i", "í", "í"),
872 "Idot": ("I", "İ", "İ"),
873 "inodot": ("i", "ı", "ı"),
874 "Icirc": ("I", "Î", "Î"),
875 "icirc": ("i", "î", "î"),
876 "Iuml": ("I", "Ï", "Ï"),
877 "iuml": ("i", "ï", "ï"),
878 "Ntilde": ("N", "Ñ", "Ñ"),
879 "ntilde": ("n", "ñ", "ñ"),
880 "Ograve": ("O", "Ò", "Ò"),
881 "ograve": ("o", "ò", "ò"),
882 "Oacute": ("O", "Ó", "Ó"),
883 "oacute": ("o", "ó", "ó"),
884 "Ocirc": ("O", "Ô", "Ô"),
885 "ocirc": ("o", "ô", "ô"),
886 "Otilde": ("O", "Õ", "Õ"),
887 "otilde": ("o", "õ", "õ"),
888 "Ouml": ("Oe", "Ö", "Ö"),
889 "ouml": ("oe", "ö", "ö"),
890 "Oslash": ("O", "Ø", "Ø"),
891 "oslash": ("o", "ø", "ø"),
892 "OElig": ("OE", "OE", "Œ"),
893 "oelig": ("oe", "oe", "œ"),
894 "Scaron": ("S", "S", "Š"),
895 "scaron": ("s", "s", "š"),
896 "szlig": ("ss", "ß", "ß"),
897 "Ugrave": ("U", "Ù", "Ù"),
898 "ugrave": ("u", "ù", "ù"),
899 "Uacute": ("U", "Ú", "Ú"),
900 "uacute": ("u", "ú", "ú"),
901 "Ucirc": ("U", "Û", "Û"),
902 "ucirc": ("u", "û", "û"),
903 "Uuml": ("Ue", "Ü", "Ü"),
904 "uuml": ("ue", "ü", "ü"),
905 "Yacute": ("Y", "Ý", "Ý"),
906 "yacute": ("y", "ý", "ý"),
907 "Yuml": ("Y", "Y", "Ÿ"),
908 "yuml": ("y", "ÿ", "ÿ"),
909 "fnof": ("f", "f", "ƒ"),
910 "real": ("R", "R", "ℜ"),
911 "image": ("I", "I", "ℑ"),
912 "weierp": ("P", "P", "℘"),
913 "ell": ("ell", "ell", "ℓ"),
914 "imath": ("[dotless i]", "dotless i", "ı"),
915 "jmath": ("[dotless j]", "dotless j", "ȷ"),
916 "Alpha": ("Alpha", "Alpha", "Α"),
917 "alpha": ("alpha", "alpha", "α"),
918 "Beta": ("Beta", "Beta", "Β"),
919 "beta": ("beta", "beta", "β"),
920 "Gamma": ("Gamma", "Gamma", "Γ"),
921 "gamma": ("gamma", "gamma", "γ"),
922 "Delta": ("Delta", "Delta", "Δ"),
923 "delta": ("delta", "delta", "δ"),
924 "Epsilon": ("Epsilon", "Epsilon", "Ε"),
925 "epsilon": ("epsilon", "epsilon", "ε"),
926 "varepsilon": ("varepsilon", "varepsilon", "ε"),
927 "Zeta": ("Zeta", "Zeta", "Ζ"),
928 "zeta": ("zeta", "zeta", "ζ"),
929 "Eta": ("Eta", "Eta", "Η"),
930 "eta": ("eta", "eta", "η"),
931 "Theta": ("Theta", "Theta", "Θ"),
932 "theta": ("theta", "theta", "θ"),
933 "thetasym": ("theta", "theta", "ϑ"),
934 "vartheta": ("theta", "theta", "ϑ"),
935 "Iota": ("Iota", "Iota", "Ι"),
936 "iota": ("iota", "iota", "ι"),
937 "Kappa": ("Kappa", "Kappa", "Κ"),
938 "kappa": ("kappa", "kappa", "κ"),
939 "Lambda": ("Lambda", "Lambda", "Λ"),
940 "lambda": ("lambda", "lambda", "λ"),
941 "Mu": ("Mu", "Mu", "Μ"),
942 "mu": ("mu", "mu", "μ"),
943 "nu": ("nu", "nu", "ν"),
944 "Nu": ("Nu", "Nu", "Ν"),
945 "Xi": ("Xi", "Xi", "Ξ"),
946 "xi": ("xi", "xi", "ξ"),
947 "Omicron": ("Omicron", "Omicron", "Ο"),
948 "omicron": ("omicron", "omicron", "ο"),
949 "Pi": ("Pi", "Pi", "Π"),
950 "pi": ("pi", "pi", "π"),
951 "Rho": ("Rho", "Rho", "Ρ"),
952 "rho": ("rho", "rho", "ρ"),
953 "Sigma": ("Sigma", "Sigma", "Σ"),
954 "sigma": ("sigma", "sigma", "σ"),
955 "sigmaf": ("sigmaf", "sigmaf", "ς"),
956 "varsigma": ("varsigma", "varsigma", "ς"),
957 "Tau": ("Tau", "Tau", "Τ"),
958 "Upsilon": ("Upsilon", "Upsilon", "Υ"),
959 "upsih": ("upsilon", "upsilon", "ϒ"),
960 "upsilon": ("upsilon", "upsilon", "υ"),
961 "Phi": ("Phi", "Phi", "Φ"),
962 "phi": ("phi", "phi", "ɸ"),
963 "varphi": ("varphi", "varphi", "φ"),
964 "Chi": ("Chi", "Chi", "Χ"),
965 "chi": ("chi", "chi", "χ"),
966 "acutex": ("'x", "'x", "𝑥́"),
967 "Psi": ("Psi", "Psi", "Ψ"),
968 "psi": ("psi", "psi", "ψ"),
969 "tau": ("tau", "tau", "τ"),
970 "Omega": ("Omega", "Omega", "Ω"),
971 "omega": ("omega", "omega", "ω"),
972 "piv": ("omega-pi", "omega-pi", "ϖ"),
973 "varpi": ("omega-pi", "omega-pi", "ϖ"),
974 "partial": ("[partial differential]", "[partial differential]", "∂"),
975 "alefsym": ("aleph", "aleph", "ℵ"),
976 "aleph": ("aleph", "aleph", "ℵ"),
977 "gimel": ("gimel", "gimel", "ℷ"),
978 "beth": ("beth", "beth", "ב"),
979 "dalet": ("dalet", "dalet", "ד"),
980 "ETH": ("D", "Ð", "Ð"),
981 "eth": ("dh", "ð", "ð"),
982 "THORN": ("TH", "Þ", "Þ"),
983 "thorn": ("th", "þ", "þ"),
984 "dots": ("...", "...", "…"),
985 "cdots": ("...", "...", "⋯"),
986 "hellip": ("...", "...", "…"),
987 "middot": (".", "·", "·"),
988 "iexcl": ("!", "¡", "¡"),
989 "iquest": ("?", "¿", "¿"),
990 "shy": ("", "", ""),
991 "ndash": ("-", "-", "–"),
992 "mdash": ("--", "--", "—"),
993 "quot": ("\"", "\"", "\""),
994 "acute": ("'", "´", "´"),
995 "ldquo": ("\"", "\"", "“"),
996 "rdquo": ("\"", "\"", "”"),
997 "bdquo": ("\"", "\"", "„"),
998 "lsquo": ("`", "`", "‘"),
999 "rsquo": ("'", "'", "’"),
1000 "sbquo": (",", ",", "‚"),
1001 "laquo": ("<<", "«", "«"),
1002 "raquo": (">>", "»", "»"),
1003 "lsaquo": ("<", "<", "‹"),
1004 "rsaquo": (">", ">", "›"),
1005 "circ": ("^", "^", "∘"),
1006 "vert": ("|", "|", "|"),
1007 "vbar": ("|", "|", "|"),
1008 "brvbar": ("|", "¦", "¦"),
1009 "S": ("section", "§", "§"),
1010 "sect": ("section", "§", "§"),
1011 "P": ("paragraph", "", ""),
1012 "para": ("paragraph", "", ""),
1013 "amp": ("&", "&", "&"),
1014 "lt": ("<", "<", "<"),
1015 "gt": (">", ">", ">"),
1016 "tilde": ("~", "~", "~"),
1017 "slash": ("/", "/", "/"),
1018 "plus": ("+", "+", "+"),
1019 "under": ("_", "_", "_"),
1020 "equal": ("=", "=", "="),
1021 "asciicirc": ("^", "^", "^"),
1022 "dagger": ("[dagger]", "[dagger]", "†"),
1023 "dag": ("[dagger]", "[dagger]", "†"),
1024 "Dagger": ("[doubledagger]", "[doubledagger]", "‡"),
1025 "ddag": ("[doubledagger]", "[doubledagger]", "‡"),
1026 "nbsp": (" ", " ", " "),
1027 "ensp": (" ", " ", " "),
1028 "emsp": (" ", " ", " "),
1029 "thinsp": (" ", " ", " "),
1030 "curren": ("curr.", "¤", "¤"),
1031 "cent": ("cent", "¢", "¢"),
1032 "pound": ("pound", "£", "£"),
1033 "yen": ("yen", "¥", "¥"),
1034 "euro": ("EUR", "EUR", "€"),
1035 "EUR": ("EUR", "EUR", "€"),
1036 "dollar": ("$", "$", "$"),
1037 "USD": ("$", "$", "$"),
1038 "copy": ("(c)", "©", "©"),
1039 "reg": ("(r)", "®", "®"),
1040 "trade": ("TM", "TM", "™"),
1041 "minus": ("-", "-", "−"),
1042 "pm": ("+-", "±", "±"),
1043 "plusmn": ("+-", "±", "±"),
1044 "times": ("*", "×", "×"),
1045 "frasl": ("/", "/", "⁄"),
1046 "colon": (":", ":", ":"),
1047 "div": ("/", "÷", "÷"),
1048 "frac12": ("1/2", "½", "½"),
1049 "frac14": ("1/4", "¼", "¼"),
1050 "frac34": ("3/4", "¾", "¾"),
1051 "permil": ("per thousand", "per thousand", "‰"),
1052 "sup1": ("^1", "¹", "¹"),
1053 "sup2": ("^2", "²", "²"),
1054 "sup3": ("^3", "³", "³"),
1055 "radic": ("[square root]", "[square root]", "√"),
1056 "sum": ("[sum]", "[sum]", "∑"),
1057 "prod": ("[product]", "[n-ary product]", "∏"),
1058 "micro": ("micro", "µ", "µ"),
1059 "macr": ("[macron]", "¯", "¯"),
1060 "deg": ("degree", "°", "°"),
1061 "prime": ("'", "'", "′"),
1062 "Prime": ("''", "''", "″"),
1063 "infin": ("[infinity]", "[infinity]", "∞"),
1064 "infty": ("[infinity]", "[infinity]", "∞"),
1065 "prop": ("[proportional to]", "[proportional to]", "∝"),
1066 "propto": ("[proportional to]", "[proportional to]", "∝"),
1067 "not": ("[angled dash]", "¬", "¬"),
1068 "neg": ("[angled dash]", "¬", "¬"),
1069 "land": ("[logical and]", "[logical and]", "∧"),
1070 "wedge": ("[logical and]", "[logical and]", "∧"),
1071 "lor": ("[logical or]", "[logical or]", "∨"),
1072 "vee": ("[logical or]", "[logical or]", "∨"),
1073 "cap": ("[intersection]", "[intersection]", "∩"),
1074 "cup": ("[union]", "[union]", "∪"),
1075 "smile": ("[cup product]", "[cup product]", "⌣"),
1076 "frown": ("[Cap product]", "[cap product]", "⌢"),
1077 "int": ("[integral]", "[integral]", "∫"),
1078 "therefore": ("[therefore]", "[therefore]", "∴"),
1079 "there4": ("[therefore]", "[therefore]", "∴"),
1080 "because": ("[because]", "[because]", "∵"),
1081 "sim": ("~", "~", "∼"),
1082 "cong": ("[approx. equal to]", "[approx. equal to]", "≅"),
1083 "simeq": ("[approx. equal to]", "[approx. equal to]", "≅"),
1084 "asymp": ("[almost equal to]", "[almost equal to]", "≈"),
1085 "approx": ("[almost equal to]", "[almost equal to]", "≈"),
1086 "ne": ("[not equal to]", "[not equal to]", "≠"),
1087 "neq": ("[not equal to]", "[not equal to]", "≠"),
1088 "equiv": ("[identical to]", "[identical to]", "≡"),
1089 "triangleq": ("[defined to]", "[defined to]", "≜"),
1090 "le": ("<=", "<=", "≤"),
1091 "leq": ("<=", "<=", "≤"),
1092 "ge": (">=", ">=", "≥"),
1093 "geq": (">=", ">=", "≥"),
1094 "lessgtr": ("[less than or greater than]", "[less than or greater than]", "≶"),
1095 "lesseqgtr": ("[less than or equal or greater than or equal]", "[less than or equal or greater than or equal]", "⋚"),
1096 "ll": ("<<", "<<", "≪"),
1097 "Ll": ("<<<", "<<<", "⋘"),
1098 "lll": ("<<<", "<<<", "⋘"),
1099 "gg": (">>", ">>", "≫"),
1100 "Gg": (">>>", ">>>", "⋙"),
1101 "ggg": (">>>", ">>>", "⋙"),
1102 "prec": ("[precedes]", "[precedes]", "≺"),
1103 "preceq": ("[precedes or equal]", "[precedes or equal]", "≼"),
1104 "preccurlyeq": ("[precedes or equal]", "[precedes or equal]", "≼"),
1105 "succ": ("[succeeds]", "[succeeds]", "≻"),
1106 "succeq": ("[succeeds or equal]", "[succeeds or equal]", "≽"),
1107 "succcurlyeq": ("[succeeds or equal]", "[succeeds or equal]", "≽"),
1108 "sub": ("[subset of]", "[subset of]", "⊂"),
1109 "subset": ("[subset of]", "[subset of]", "⊂"),
1110 "sup": ("[superset of]", "[superset of]", "⊃"),
1111 "supset": ("[superset of]", "[superset of]", "⊃"),
1112 "nsub": ("[not a subset of]", "[not a subset of", "⊄"),
1113 "sube": ("[subset of or equal to]", "[subset of or equal to]", "⊆"),
1114 "nsup": ("[not a superset of]", "[not a superset of]", "⊅"),
1115 "supe": ("[superset of or equal to]", "[superset of or equal to]", "⊇"),
1116 "forall": ("[for all]", "[for all]", "∀"),
1117 "exist": ("[there exists]", "[there exists]", "∃"),
1118 "exists": ("[there exists]", "[there exists]", "∃"),
1119 "nexist": ("[there does not exists]", "[there does not exists]", "∄"),
1120 "nexists": ("[there does not exists]", "[there does not exists]", "∄"),
1121 "empty": ("[empty set]", "[empty set]", "∅"),
1122 "emptyset": ("[empty set]", "[empty set]", "∅"),
1123 "isin": ("[element of]", "[element of]", "∈"),
1124 "in": ("[element of]", "[element of]", "∈"),
1125 "notin": ("[not an element of]", "[not an element of]", "∉"),
1126 "ni": ("[contains as member]", "[contains as member]", "∋"),
1127 "nabla": ("[nabla]", "[nabla]", "∇"),
1128 "ang": ("[angle]", "[angle]", "∠"),
1129 "angle": ("[angle]", "[angle]", "∠"),
1130 "perp": ("[up tack]", "[up tack]", "⊥"),
1131 "parallel": ("||", "||", "∥"),
1132 "sdot": ("[dot]", "[dot]", "⋅"),
1133 "cdot": ("[dot]", "[dot]", "⋅"),
1134 "lceil": ("[left ceiling]", "[left ceiling]", "⌈"),
1135 "rceil": ("[right ceiling]", "[right ceiling]", "⌉"),
1136 "lfloor": ("[left floor]", "[left floor]", "⌊"),
1137 "rfloor": ("[right floor]", "[right floor]", "⌋"),
1138 "lang": ("<", "<", "⟨"),
1139 "rang": (">", ">", "⟩"),
1140 "langle": ("<", "<", "⟨"),
1141 "rangle": (">", ">", "⟩"),
1142 "hbar": ("hbar", "hbar", "ℏ"),
1143 "mho": ("mho", "mho", "℧"),
1144 "larr": ("<-", "<-", "←"),
1145 "leftarrow": ("<-", "<-", "←"),
1146 "gets": ("<-", "<-", "←"),
1147 "lArr": ("<=", "<=", "⇐"),
1148 "Leftarrow": ("<=", "<=", "⇐"),
1149 "uarr": ("[uparrow]", "[uparrow]", "↑"),
1150 "uparrow": ("[uparrow]", "[uparrow]", "↑"),
1151 "uArr": ("[dbluparrow]", "[dbluparrow]", "⇑"),
1152 "Uparrow": ("[dbluparrow]", "[dbluparrow]", "⇑"),
1153 "rarr": ("->", "->", "→"),
1154 "to": ("->", "->", "→"),
1155 "rightarrow": ("->", "->", "→"),
1156 "rArr": ("=>", "=>", "⇒"),
1157 "Rightarrow": ("=>", "=>", "⇒"),
1158 "darr": ("[downarrow]", "[downarrow]", "↓"),
1159 "downarrow": ("[downarrow]", "[downarrow]", "↓"),
1160 "dArr": ("[dbldownarrow]", "[dbldownarrow]", "⇓"),
1161 "Downarrow": ("[dbldownarrow]", "[dbldownarrow]", "⇓"),
1162 "harr": ("<->", "<->", "↔"),
1163 "leftrightarrow": ("<->", "<->", "↔"),
1164 "hArr": ("<=>", "<=>", "⇔"),
1165 "Leftrightarrow": ("<=>", "<=>", "⇔"),
1166 "crarr": ("<-'", "<-'", "↵"),
1167 "hookleftarrow": ("<-'", "<-'", "↵"),
1168 "arccos": ("arccos", "arccos", "arccos"),
1169 "arcsin": ("arcsin", "arcsin", "arcsin"),
1170 "arctan": ("arctan", "arctan", "arctan"),
1171 "arg": ("arg", "arg", "arg"),
1172 "cos": ("cos", "cos", "cos"),
1173 "cosh": ("cosh", "cosh", "cosh"),
1174 "cot": ("cot", "cot", "cot"),
1175 "coth": ("coth", "coth", "coth"),
1176 "csc": ("csc", "csc", "csc"),
1177 "det": ("det", "det", "det"),
1178 "dim": ("dim", "dim", "dim"),
1179 "exp": ("exp", "exp", "exp"),
1180 "gcd": ("gcd", "gcd", "gcd"),
1181 "hom": ("hom", "hom", "hom"),
1182 "inf": ("inf", "inf", "inf"),
1183 "ker": ("ker", "ker", "ker"),
1184 "lg": ("lg", "lg", "lg"),
1185 "lim": ("lim", "lim", "lim"),
1186 "liminf": ("liminf", "liminf", "liminf"),
1187 "limsup": ("limsup", "limsup", "limsup"),
1188 "ln": ("ln", "ln", "ln"),
1189 "log": ("log", "log", "log"),
1190 "max": ("max", "max", "max"),
1191 "min": ("min", "min", "min"),
1192 "Pr": ("Pr", "Pr", "Pr"),
1193 "sec": ("sec", "sec", "sec"),
1194 "sin": ("sin", "sin", "sin"),
1195 "sinh": ("sinh", "sinh", "sinh"),
1196 "tan": ("tan", "tan", "tan"),
1197 "tanh": ("tanh", "tanh", "tanh"),
1198 "bull": ("*", "*", "•"),
1199 "bullet": ("*", "*", "•"),
1200 "star": ("*", "*", "⋆"),
1201 "lowast": ("*", "*", "∗"),
1202 "ast": ("*", "*", "*"),
1203 "odot": ("[circled dot]", "[circled dot]", "ʘ"),
1204 "oplus": ("[circled plus]", "[circled plus]", "⊕"),
1205 "otimes": ("[circled times]", "[circled times]", "⊗"),
1206 "check": ("[checkmark]", "[checkmark]", "✓"),
1207 "checkmark": ("[checkmark]", "[checkmark]", "✓"),
1208 "ordf": ("_a_", "ª", "ª"),
1209 "ordm": ("_o_", "º", "º"),
1210 "cedil": ("[cedilla]", "¸", "¸"),
1211 "oline": ("[overline]", "¯", "‾"),
1212 "uml": ("[diaeresis]", "¨", "¨"),
1213 "zwnj": ("", "", "‌"),
1214 "zwj": ("", "", "‍"),
1215 "lrm": ("", "", "‎"),
1216 "rlm": ("", "", "‏"),
1217 "smiley": (":-)", ":-)", "☺"),
1218 "blacksmile": (":-)", ":-)", "☻"),
1219 "sad": (":-(", ":-(", "☹"),
1220 "frowny": (":-(", ":-(", "☹"),
1221 "clubs": ("[clubs]", "[clubs]", "♣"),
1222 "clubsuit": ("[clubs]", "[clubs]", "♣"),
1223 "spades": ("[spades]", "[spades]", "♠"),
1224 "spadesuit": ("[spades]", "[spades]", "♠"),
1225 "hearts": ("[hearts]", "[hearts]", "♥"),
1226 "heartsuit": ("[hearts]", "[hearts]", "♥"),
1227 "diams": ("[diamonds]", "[diamonds]", "◆"),
1228 "diamondsuit": ("[diamonds]", "[diamonds]", "◆"),
1229 "diamond": ("[diamond]", "[diamond]", "◆"),
1230 "Diamond": ("[diamond]", "[diamond]", "◆"),
1231 "loz": ("[lozenge]", "[lozenge]", "⧫"),
1232 "_ ": (" ", " ", " "),
1233 "_ ": (" ", " ", "  "),
1234 "_ ": (" ", " ", "   "),
1235 "_ ": (" ", " ", "    "),
1236 "_ ": (" ", " ", "     "),
1237 "_ ": (" ", " ", "      "),
1238 "_ ": (" ", " ", "       "),
1239 "_ ": (" ", " ", "        "),
1240 "_ ": (" ", " ", "         "),
1241 "_ ": (" ", " ", "          "),
1242 "_ ": (" ", " ", "           "),
1243 "_ ": (" ", " ", "            "),
1244 "_ ": (" ", " ", "             "),
1245 "_ ": (" ", " ", "              "),
1246 "_ ": (" ", " ", "               "),
1247 "_ ": (" ", " ", "                "),
1248 "_ ": (" ", " ", "                 "),
1249 "_ ": (" ", " ", "                  "),
1250 "_ ": (" ", " ", "                   "),
1251 "_ ": (" ", " ", "                    "),
1252 ]
8361253}
Tests/OrgCoreTests/ASCIIExportTests.swift added +237
@@ -0,0 +1,237 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// ox-ascii under `emacs -Q`, for whole documents: each case is exported in its own file.
6enum ASCIIOracle {
7 static let author = "A. Writer"
8
9 struct Case {
10 var text: String
11 var charset = ASCIIExport.Charset.ascii
12 var bodyOnly = false
13 /// Emacs point to export the subtree at.
14 var subtree: Int?
15 }
16
17 /// Each case's `org-export-as 'ascii`, or `ERROR: message`.
18 static func export(_ cases: [Case]) throws -> [String] {
19 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-ascii-\(UUID().uuidString)")
20 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
21 defer { try? FileManager.default.removeItem(at: folder) }
22 var input: [[String]] = []
23 for (index, c) in cases.enumerated() {
24 let url = folder.appendingPathComponent("doc\(index).org")
25 try c.text.write(to: url, atomically: true, encoding: .utf8)
26 input.append([url.path, c.bodyOnly ? "1" : "0", c.subtree.map(String.init) ?? "0", c.charset.rawValue])
27 }
28 let inputURL = folder.appendingPathComponent("input.json")
29 let output = folder.appendingPathComponent("output.json")
30 try JSONEncoder().encode(input).write(to: inputURL)
31 let script = folder.appendingPathComponent("export.el")
32 try #"""
33 ;;; -*- lexical-binding: t -*-
34 (require 'org)
35 (require 'ox-ascii)
36 (require 'json)
37 (setq user-full-name "A. Writer")
38 (let ((results nil))
39 (seq-doseq (c (json-read-file (getenv "ORACLE_INPUT")))
40 (with-current-buffer (find-file-noselect (aref c 0))
41 (let ((point (string-to-number (aref c 2)))
42 (org-ascii-charset (intern (aref c 3))))
43 (push (condition-case e
44 (progn (when (> point 0) (goto-char point))
45 (org-export-as 'ascii (> point 0) nil (equal (aref c 1) "1")))
46 (error (concat "ERROR: " (error-message-string e))))
47 results))
48 (kill-buffer)))
49 (let ((coding-system-for-write 'utf-8-unix))
50 (with-temp-file (getenv "ORACLE_OUTPUT")
51 (insert (json-encode (vconcat (nreverse results)))))))
52 """#.write(to: script, atomically: true, encoding: .utf8)
53 let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": inputURL.path, "ORACLE_OUTPUT": output.path, "TZ": "UTC"])
54 guard let data = try? Data(contentsOf: output) else { throw EmacsOracle.EvaluateError(log: log) }
55 return try JSONDecoder().decode([String].self, from: data)
56 }
57
58 /// Ours for the same case, or `ERROR: reason`.
59 static func native(_ c: Case) -> String {
60 do {
61 var text = c.text
62 if let point = c.subtree {
63 guard let narrowed = ExportScope.subtree(text, at: EmacsOracle.offset(point, in: text)) else { return "ERROR: not in a subtree" }
64 text = narrowed
65 }
66 return try ASCIIExport.document(text, charset: c.charset, bodyOnly: c.bodyOnly, author: author)
67 } catch {
68 return "ERROR: \(error.localizedDescription)"
69 }
70 }
71}
72
73struct ASCIIExportTests {
74 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
75 static let folder = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Conformance")
76 static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "images", "tblfm"]
77
78 /// Snippets for what the corpus doesn't show.
79 static let snippets: [String] = [
80 "No title here.\n",
81 "#+TITLE: A /styled/ title\n#+SUBTITLE: and more\n#+AUTHOR: Someone & Co\n#+DATE: <2024-03-01 Fri>\n\nText.\n",
82 "#+TITLE: A rather long title that goes on and on until it has to be filled over lines\n#+AUTHOR: Me\nx\n",
83 "#+OPTIONS: toc:nil num:nil author:nil date:nil title:nil\n#+TITLE: T\n* One\n** Two\n*** Three\n**** Four\n***** Five\n",
84 "#+OPTIONS: toc:2 num:1 H:2\n* One\n** Two\n*** Three\nbody\n*** Four\n* Back\n",
85 "#+OPTIONS: H:5\n* One\n** Two\n*** Three\n**** Four\n***** Five\ntext\n",
86 "#+OPTIONS: author:nil\n#+DATE: today\nx\n",
87 "#+DATE: today\nx\n",
88 "#+AUTHOR:\nx\n",
89 "Special: \\- -- --- ... a\\\\b\nand *bold*[x] then.\n",
90 "Math \\(a+b\\) and $x^2$ and \\alpha \\to \\deg{}C \\copy \\nbsp{}here \\pi.\n",
91 "Scripts x^2 y_{i} a_b.\n",
92 "#+OPTIONS: ^:{}\nScripts x^2 y_{i} a_b.\n",
93 "#+OPTIONS: ^:nil tex:nil\nScripts x^2 y_{i} and \\(a\\) gone.\n",
94 "Markup *b* /i/ _u_ +s+ =v= ~c~ and *nested /italic/ bold*.\n",
95 "Snippets @@ascii:raw@@ and @@html:<br>@@ gone. Also @@html:x@@ @@html:y@@ end.\n@@html:z@@ start\n",
96 "Line one\\\\\nline two \\\\\nafter\n",
97 "Links: [[https://orgmode.org][Org & co]] <https://a.b/c_d> https://x.y/z [[mailto:me@x.org]] [[file:doc.pdf][the doc]] [[./rel/file.txt]] [[file:/abs/path.org]]\n",
98 "* Target section\nSee [[*Other]].\n* Other\nSee [[*Target section]] and [[Target section][named]] and [[#cid]].\n* Third\n:PROPERTIES:\n:CUSTOM_ID: cid\n:END:\nx\n",
99 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]] and [[*Head][desc]].\n",
100 "Footnotes[fn:1] twice[fn:1] and[fn:2][fn:3] and inline[fn::anon /x/] and[fn:named:inline def].\n\n[fn:1] First.\n\n[fn:2] Second\n with two lines.\n\n[fn:3] Third.\n",
101 "1. one\n2. [@5] five\n 1. nested\n 2. [@3] three\n3. after\n\n- [X] done\n- [-] half\n- [ ] todo\n\n- term :: def\n- [X] checked term :: def2\n",
102 "+ plus bullet\n+ second\n\n* not a heading\n",
103 "#+CAPTION: Scores\n#+NAME: tab:scores\n| Name | Score |\n|------+-------|\n| a | 1.5 |\n| b | |\n| c | 1e3 |\n",
104 "| *b* | =v= | [[https://x.y][l]] |\n|-----+-----+-----|\n| 1 | -2 | 3% |\n| x | | 4 |\n|-----+-----+-----|\n",
105 "|---+---|\n| a | b |\n|---+---|\n| c | d |\n|---+---|\n",
106 "| <l> | <r5> | <c> |\n| a | b | c |\n| long | x | yy |\n",
107 "#+NAME: code\n#+CAPTION: A listing\n#+begin_src python -n\nprint(1)\nprint(2)\n#+end_src\n\n#+begin_src emacs-lisp +n 10\n(a)\n#+end_src\n\n#+begin_example -r\nline (ref:x)\n#+end_example\n\n#+begin_src sh\n indented\n more\n#+end_src\n",
108 "#+begin_src c -n -k\nint x; (ref:decl)\nreturn x;\n#+end_src\n\nSee line [[(decl)]].\n",
109 "#+begin_quote\nQ /one/.\n\nQ two.\n#+end_quote\n\n#+begin_center\nC\n#+end_center\n#+begin_verse\n Roses are red,\n violets blue\n\nnext stanza\n#+end_verse\n",
110 "#+begin_warning\nW *b*.\n#+end_warning\n\n#+begin_export ascii\n raw\n#+end_export\n#+begin_export html\n<p>no</p>\n#+end_export\n#+begin_comment\nhidden\n#+end_comment\nafter\n",
111 "#+begin_JUSTIFYRIGHT\nRight.\n#+end_JUSTIFYRIGHT\n\n#+begin_center\nA table:\n| a | b |\n#+end_center\n",
112 "#+ASCII: raw line\n#+TOC: headlines 1\n: fixed\n: width\n\n-----\n\n#+ATTR_ASCII: :width 10\n-----\n* One\n** Two\n",
113 "\\begin{equation}\nx = 1\n\\end{equation}\n",
114 "Para one.\n# a comment\nPara two.\n\n# comment\n\nPara three.\n",
115 "* TODO [#B] Task :work:urgent_x:\nSCHEDULED: <2024-01-01 Mon>\n:PROPERTIES:\n:X: 1\n:END:\n:LOGBOOK:\n- note\n:END:\n:NOTES:\nDrawer *text*.\n:END:\nbody\n* Archived :ARCHIVE:\nhidden\n** child\n* Kept\n* Drop :noexport:\nx\n* COMMENT Gone\ny\n",
116 "#+OPTIONS: pri:t tags:nil todo:nil\n* TODO [#A] Title [1/2] [50%]\n- [X] a\n- [ ] b\n",
117 "#+OPTIONS: tags:not-in-toc\n* One :a:\n** Two :b:\n",
118 "#+SELECT_TAGS: pick\nPreamble text.\n* A\n* B :pick:\n** B1\n* C\n",
119 "Dates <2024-01-15 Mon 9:05> [2024-02-29 Thu 10:00-11:30] <2024-01-15 Mon +1w -2d> <2024-01-15 Mon>--<2024-01-17 Wed> end.\n",
120 "#+MACRO: greet Hello, $1!\n{{{greet(World)}}} and {{{title}}}.\n",
121 "#+begin_src emacs-lisp :exports code\n(+ 1 2)\n#+end_src\n\n#+RESULTS:\n: 3\n\nafter\n",
122 " Indented paragraph\n second line\n deeper\n\n- item first line\n continued\n more\n",
123 "* Low levels\n** two\n*** three\n**** four a\n**** four b\nbody\n***** five\n* next\n",
124 "#+EXCLUDE_TAGS: secret\n* A\n** B :secret:\n** C\n",
125 "#+OPTIONS: -:nil\nNo special... strings -- \\- here.\n",
126 "- a\n\n- b\n para two\n\n para three\n- c\n - d\n\n - e\nafter list\n",
127 "#+LANGUAGE: de\n* Teil\nText[fn:1] and [[https://x.y][link]].\n\n[fn:1] Note.\n",
128 "#+LANGUAGE: fr\n#+TOC: headlines\n* Un\n",
129 "A long paragraph that has to be filled because it runs on for well over the seventy-two columns of a line. Sentences end. Here.\n",
130 "* Heading with [[https://a.b][a link]] in it\nAnd [[https://c.d][another]] and [[https://a.b][a link]] again.\n** Sub\n[[https://e.f][third]]\n",
131 "#+TITLE: Title with [[https://a.b][link]]\nx\n",
132 "* A\n#+FOO: bar\n\n* B\n",
133 "#+TITLE: T\n\n* H\nx\n",
134 "| a |\n| 1 |\n",
135 "#+begin_example\n#+end_example\n\n#+begin_src sh\n#+end_src\n\nafter\n",
136 ]
137
138 static let extra: [String] = [
139 "#+OPTIONS: H:2 toc:3\n* A :x:\n** B\n*** C\n**** D\n***** E\n****** F\n* G\n",
140 "#+OPTIONS: num:2\n* A\n** B\n*** C\n**** D\n",
141 "* A\nText.[fn:1]\n** B\nMore.[fn:2]\n\n[fn:1] A note under A that is long enough to be filled at a width shorter than seventy-two.\n\n[fn:2] Short.\n\n\nNot part of the note.\n",
142 "Refs[fn:1].\n\n[fn:1] A note in the preamble that is long enough to be filled at the full width of seventy-two.\n",
143 "Inline[fn:: an inline note that is long enough to be filled at the full width of seventy-two columns wide].\n",
144 "| a[fn:1] | b |\n\n- item[fn:2]\n\n[fn:1] One.\n\n[fn:2] Two.\n",
145 "* Heading\nSee [[https://a.b][A]] here.\n** Child\nx\n",
146 "* Heading [[https://a.b][A]]\n** Child\nx\n",
147 "- item [[https://a.b][A]]\n - nested [[https://c.d][C]]\n\n| [[https://e.f][E]] |\n",
148 "Same [[https://a.b][A]] and [[https://a.b][A]] and [[https://a.b][B]] and [[https://a.b]].\n",
149 "#+begin_src sh -n -r\necho a (ref:one)\necho b\n#+end_src\nLine [[(one)]] and [[(one)][here]].\n",
150 "#+begin_center\n- one\n- two\n\n#+begin_quote\nq\n#+end_quote\n#+end_center\n",
151 "#+begin_quote\n- a list in a quote that runs on long enough to need filling inside the narrower width\n-----\n#+end_quote\n",
152 "- term :: definition\n - nested :: inner definition that is long enough to be filled at the narrower width\n",
153 "1. a\n2. b\n3. c\n4. d\n5. e\n6. f\n7. g\n8. h\n9. i\n10. j that is long enough to be filled at a width shorter by the wider bullet here\n",
154 "1. [X] done and long enough to wrap because the checkbox narrows the width of the item text\n2) other\n",
155 "| <c> |\n| a |\n| long cell |\n\n| <6> | <l3> |\n| a | b |\n",
156 "| 1 | x |\n| | y |\n| 3 | z |\n",
157 "#+begin_verse\n /Roses/ are *red*,\n violets \\alpha blue\n#+end_verse\n",
158 "Entities \\eacute \\copy \\laquo \\nbsp \\mdash \\hellip \\Aring \\sup2 \\frac12 \\times.\n",
159 "* TODO [#A] A task with a title long enough to push the tags past the edge :tag:other:\n",
160 "* A\n:PROPERTIES:\n:CUSTOM_ID: a\n:END:\n* B\nSee [[#a][the A]] and [[#a]].\n",
161 "#+OPTIONS: num:nil toc:nil\n* A\n* B\nSee [[*A]] and [[*A][x]].\n",
162 "#+TITLE: T\n#+SUBTITLE: The subtitle is longer than the title\n#+AUTHOR: An author with a long name\n#+DATE: 2024\nx\n",
163 "#+TITLE: Ünïcödé — title\n#+AUTHOR: Ëm\nx\n",
164 "#+begin_example\n a\n b\n#+end_example\n\n#+begin_example -i\n a\n#+end_example\n",
165 ": a\n: b\n: c\n",
166 "Text\n\n#+begin_src emacs-lisp :exports none\n(x)\n#+end_src\n\nafter\n",
167 "* A\n** B :noexport:\n*** C\n** D\n",
168 "* COMMENT A\n* B\n",
169 "x\n\n* Footnotes\n[fn:1] in section\n* After\ny[fn:1]\n",
170 "A sentence ends here. Another one follows. And a third e.g. this one continues on for a while to wrap the line.\n",
171 "Word\nbroken\n across\n lines\n",
172 "*bold that is long enough* /italic that goes on/ _underline_ +strike+ =verbatim text= ~code text~ and more words to wrap the line around.\n",
173 "#+begin_center\nA centered paragraph that is long enough to be filled over more than one line of the text width.\n#+end_center\n",
174 "#+begin_JUSTIFYRIGHT\n| a | b |\n#+end_JUSTIFYRIGHT\n",
175 "#+begin_JUSTIFYLEFT\nleft\n#+end_JUSTIFYLEFT\n",
176 "#+ATTR_ASCII: :width 20\n-----\n",
177 "* A\n#+TOC: headlines 2\n** B\n** C\n",
178 ]
179
180 static var cases: [(String, ASCIIOracle.Case)] {
181 var cases: [(String, ASCIIOracle.Case)] = []
182 for charset in ASCIIExport.Charset.allCases {
183 for name in corpus {
184 let text = (try? String(contentsOf: folder.appendingPathComponent("\(name).org"), encoding: .utf8)) ?? ""
185 cases.append(("\(name) \(charset.rawValue)", ASCIIOracle.Case(text: text, charset: charset)))
186 }
187 for (index, snippet) in (snippets + extra).enumerated() {
188 cases.append(("snippet \(index) \(charset.rawValue)", ASCIIOracle.Case(text: snippet, charset: charset)))
189 }
190 }
191 return cases
192 }
193
194 @Test(.enabled(if: oracle))
195 func matchesEmacs() throws {
196 let all = Self.cases
197 try compare(all.map(\.1), names: all.map(\.0))
198 }
199
200 @Test(.enabled(if: oracle))
201 func bodyOnlyAndSubtreesMatchEmacs() throws {
202 let doc = "#+TITLE: Doc\n#+OPTIONS: toc:nil\nIntro.\n* One\nFirst.\n** Sub\n:PROPERTIES:\n:EXPORT_TITLE: Exported title\n:END:\nSub body *b*.\n*** Deeper\nx\n* Two\nSecond.\n"
203 let sub = (doc as NSString).range(of: "** Sub").location
204 let one = (doc as NSString).range(of: "First.").location
205 var cases: [ASCIIOracle.Case] = []
206 var names: [String] = []
207 for charset in ASCIIExport.Charset.allCases {
208 cases += [
209 ASCIIOracle.Case(text: doc, charset: charset, bodyOnly: true),
210 ASCIIOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("blocks.org"), encoding: .utf8), charset: charset, bodyOnly: true),
211 ASCIIOracle.Case(text: doc, charset: charset, subtree: EmacsOracle.point(sub, in: doc)),
212 ASCIIOracle.Case(text: doc, charset: charset, subtree: EmacsOracle.point(one, in: doc)),
213 ASCIIOracle.Case(text: doc, charset: charset, bodyOnly: true, subtree: EmacsOracle.point(sub, in: doc)),
214 ]
215 names += ["body", "blocks body", "subtree", "subtree from body", "subtree body"].map { "\($0) \(charset.rawValue)" }
216 }
217 try compare(cases, names: names)
218 }
219
220 private func compare(_ cases: [ASCIIOracle.Case], names: [String]) throws {
221 let emacs = try ASCIIOracle.export(cases)
222 for (index, c) in cases.enumerated() {
223 let ours = ASCIIOracle.native(c)
224 if ours.hasPrefix("ERROR: ") {
225 Issue.record("\(names[index]) unsupported: \(ours)\n--- org\n\(c.text)")
226 continue
227 }
228 if let dump = ProcessInfo.processInfo.environment["ASCII_DUMP"], ours != emacs[index] {
229 let name = names[index].replacingOccurrences(of: " ", with: "_")
230 try? ours.write(toFile: dump + "/" + name + ".ours", atomically: true, encoding: .utf8)
231 try? emacs[index].write(toFile: dump + "/" + name + ".emacs", atomically: true, encoding: .utf8)
232 try? c.text.write(toFile: dump + "/" + name + ".org", atomically: true, encoding: .utf8)
233 }
234 #expect(ours == emacs[index], "\(names[index])\n--- org\n\(c.text)\n--- ours\n\(ours)\n--- emacs\n\(emacs[index])")
235 }
236 }
237}