Native ASCII export matching ox-ascii !417

merged merged by cmc on 2026-11-20 22:48 UTC · krz/orgstar:parity-ascii into main

23 files changed, +2629 −73

Layout: unified · split

README.org +2 −2
@@ -36,8 +36,8 @@ Emacs tomorrow and nothing has been reformatted.
36- *Tables.* Aligned as you type, with =#+TBLFM= formulas. 36- *Tables.* Aligned as you type, with =#+TBLFM= formulas.
37- *Code blocks.* Run source blocks and tangle them into files, as =org-babel-tangle= 37- *Code blocks.* Run source blocks and tangle them into files, as =org-babel-tangle=
38 does. 38 does.
39- *Export.* HTML, Markdown, PDF, Word, RTF, ODT, iCalendar and LaTeX built in; PDF through 39- *Export.* HTML, Markdown, PDF, Word, RTF, ODT, iCalendar, LaTeX and ASCII built in; PDF
40 LaTeX and more through Emacs when it is installed (download version only). 40 through LaTeX and more through Emacs when it is installed (download version only).
41- *Search.* Across file names, headings and text, plus Spotlight and Quick Look 41- *Search.* Across file names, headings and text, plus Spotlight and Quick Look
42 previews of =.org= files. 42 previews of =.org= files.
43 43
Sources/OrgApp/AppStoreCommands.swift +1 −1
@@ -4,7 +4,7 @@ import Foundation
4/// Emacs, and attaching by link, which the sandbox doesn't allow. 4/// Emacs, and attaching by link, which the sandbox doesn't allow.
5public enum AppStoreCommands { 5public enum AppStoreCommands {
6 public static let hidden: Set<String> = [ 6 public static let hidden: Set<String> = [
7 "app.export.pdf", "app.export.text", 7 "app.export.pdf",
8 "app.attach.link", "app.attach.symlink", 8 "app.attach.link", "app.attach.symlink",
9 ] 9 ]
10 10
Sources/OrgApp/CommandTitles.swift +1 −1
@@ -94,7 +94,7 @@ enum CommandTitles {
94 String(localized: "Export to PDF", comment: "Command title"), 94 String(localized: "Export to PDF", comment: "Command title"),
95 String(localized: "Export to PDF with Emacs", comment: "Command title"), 95 String(localized: "Export to PDF with Emacs", comment: "Command title"),
96 String(localized: "Export to Plain Text", comment: "Command title"), 96 String(localized: "Export to Plain Text", comment: "Command title"),
97 String(localized: "Export to Plain Text with Emacs", comment: "Command title"), 97 String(localized: "Export to Plain Text (ASCII)", comment: "Command title"),
98 String(localized: "Export to RTF", comment: "Command title"), 98 String(localized: "Export to RTF", comment: "Command title"),
99 String(localized: "Export to Word", comment: "Command title"), 99 String(localized: "Export to Word", comment: "Command title"),
100 String(localized: "Export to iCalendar", comment: "Command title"), 100 String(localized: "Export to iCalendar", comment: "Command title"),
Sources/OrgApp/Publish.swift +3 −3
@@ -40,7 +40,7 @@ public struct PublishProject: Sendable, Equatable {
40 40
41 public init(name: String) { self.name = name } 41 public init(name: String) { self.name = name }
42 42
43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-odt-publish-to-odt", "org-publish-attachment"] 43 public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-odt-publish-to-odt", "org-ascii-publish-to-ascii", "org-publish-attachment"]
44} 44}
45 45
46public enum Publish { 46public enum Publish {
@@ -252,7 +252,7 @@ public enum Publish {
252 252
253 /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through 253 /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through
254 /// its publishing functions. A file whose output is newer than it is skipped unless `force`. 254 /// its publishing functions. A file whose output is newer than it is skipped unless `force`.
255 /// `export` turns an Org file's text into the HTML, Markdown or LaTeX to write. 255 /// `export` turns an Org file's text into the HTML, Markdown, LaTeX or plain text to write.
256 public static func publish( 256 public static func publish(
257 _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil, 257 _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil,
258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String 258 read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
@@ -290,7 +290,7 @@ public enum Publish {
290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil } 290 if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil }
291 return outputDirectory + (file as NSString).lastPathComponent 291 return outputDirectory + (file as NSString).lastPathComponent
292 } 292 }
293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt"][function] ?? "html" 293 let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt", "org-ascii-publish-to-ascii": "txt"][function] ?? "html"
294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") } 294 guard let text = read(file) else { throw Failure(description: "Can't read \(file)") }
295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent), 295 return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent),
296 name: ExportScope.fileName(text), extension: ext).path 296 name: ExportScope.fileName(text), extension: ext).path
Sources/OrgCore/Export/ASCIIExport.swift added +1429
@@ -0,0 +1,1429 @@
1import Foundation
2
3/// Plain text export as ox-ascii (Org 9.8.7) writes it under `emacs -Q`, in its `ascii`,
4/// `latin1` or `utf-8` charset: a centered title block, a table of contents, underlined and
5/// numbered headings, links described at the end of their section, footnotes at the end. What
6/// it can't write as Emacs would throws `Unsupported`, naming the construct, instead of writing
7/// something else.
8public enum ASCIIExport {
9 public typealias Unsupported = LaTeXExport.Unsupported
10
11 /// `org-ascii-charset`.
12 public enum Charset: String, Sendable, CaseIterable {
13 case ascii, latin1
14 case utf8 = "utf-8"
15 }
16
17 /// A `.txt` document, or with `bodyOnly` the text without the title block and contents.
18 /// `author` stands for `user-full-name`, `language` for `org-export-default-language`. `file`
19 /// adds the final newline `org-export-to-file` writes.
20 public static func document(
21 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), charset: Charset = .ascii,
22 bodyOnly: Bool = false, author: String = "", language: String = "en", file: Bool = false
23 ) throws -> String {
24 let text = try LaTeXExport.expanded(text, settings: settings, path: path, now: now)
25 let tree = OrgParser.parse(text, defaults: settings)
26 let keywords = settings.setupKeywords.split(separator: "\n").map(String.init)
27 + tree.root.descendants().filter { $0.kind == .keyword }.map { $0.text.trimmingCharacters(in: .newlines) }
28 let renderer = try ASCIIRenderer(tree: tree, text: text, settings: settings, keywords: keywords, language: language, charset: charset)
29 var output = try renderer.body()
30 if !bodyOnly { output = try renderer.template(output, author: author) }
31 output = output.replacingOccurrences(of: ASCIIRenderer.hardNewline, with: "\n")
32 return file && !output.isEmpty && !output.hasSuffix("\n") ? output + "\n" : output
33 }
34}
35
36final class ASCIIRenderer {
37 typealias Unsupported = LaTeXExport.Unsupported
38 typealias Inline = LaTeXRenderer.Inline
39
40 enum Justify { case left, center, right }
41
42 /// Where an element is: the text width `org-ascii--current-text-width` gives it and the
43 /// justification of the blocks around it.
44 struct Context {
45 var width: Int
46 var justify = Justify.left
47 }
48
49 /// `hard-newline`: a newline that ends a line when filling.
50 static let hardNewline = ASCIIText.hardNewline + "\n"
51
52 static let textWidth = 72
53 static let innerMargin = 2
54 static let quoteMargin = 6
55
56 let tree: OrgTree
57 let source: NSString
58 let settings: OrgSettings
59 let options: ExportOptions
60 /// Keyword values by name, in order.
61 let keywords: [String: [String]]
62 let language: String
63 let charset: ASCIIExport.Charset
64 var utf8: Bool { charset == .utf8 }
65 let numbered: Bool
66 let num: Int?
67 let withTOC: Bool
68 let toc: Int?
69 private var selected: Set<Int>?
70 /// Added to heading levels.
71 private var levelOffset = 0
72 private var exportSource: ExportSource
73 private let model: DocumentModel
74 /// Section numbers of the numbered headings the export writes, by heading start.
75 private var numbers: [Int: [Int]] = [:]
76 /// The headings the export writes, by start, with their relative level.
77 private var exported: [(start: Int, level: Int)] = []
78 /// `:ascii-links-to-notes`, off in the title block and footnotes.
79 private var linksToNotes = true
80
81 init(tree: OrgTree, text: String, settings: OrgSettings, keywords lines: [String], language: String, charset: ASCIIExport.Charset) throws {
82 self.tree = tree
83 source = text as NSString
84 self.settings = settings
85 self.charset = charset
86 exportSource = ExportSource(tree: tree, text: text)
87 model = DocumentModel(tree: tree)
88 var keywords: [String: [String]] = [:]
89 for line in lines {
90 guard let m = line.firstMatch(of: #/^[ \t]*#\+([^:\s]+):(?:[ \t]+(.*?))?[ \t]*$/#) else { continue }
91 keywords[m.1.uppercased(), default: []].append(m.2.map(String.init) ?? "")
92 }
93 self.keywords = keywords
94 options = ExportOptions.parse(lines.joined(separator: "\n"))
95 self.language = keywords["LANGUAGE"]?.last ?? language
96
97 // `#+OPTIONS` this export follows; any other item only at its default.
98 let defaults = ["\\n": "nil", ":": "t", "*": "t", "e": "t", "f": "t", "|": "t", "p": "nil", "c": "nil", "prop": "nil",
99 "stat": "t", "tasks": "t", "inline": "t", "arch": "headline", "email": "nil", "creator": "nil",
100 "broken-links": "nil", "'": "nil", "d": "(not \"LOGBOOK\")", "expand-links": "t"]
101 for (key, value) in options.items {
102 if let standard = defaults[key], standard != value { throw Unsupported(reason: "#+OPTIONS: \(key):\(value)") }
103 }
104 let items = options.items
105 func depth(_ key: String) throws -> (Bool, Int?) {
106 guard let v = items[key] else { return (true, nil) }
107 if v == "nil" { return (false, nil) }
108 if v == "t" { return (true, nil) }
109 guard let n = Int(v) else { throw Unsupported(reason: "#+OPTIONS: \(key):\(v)") }
110 return (true, n)
111 }
112 (numbered, num) = try depth("num")
113 (withTOC, toc) = try depth("toc")
114 if let tex = items["tex"], tex != "t", tex != "nil" { throw Unsupported(reason: "#+OPTIONS: tex:\(tex)") }
115 for key in ["CITE_EXPORT", "BIBLIOGRAPHY", "PRINT_BIBLIOGRAPHY", "CALL"] where keywords[key] != nil {
116 throw Unsupported(reason: "#+\(key)")
117 }
118 // Radio links: links that are only words.
119 if tree.root.descendants().contains(where: { $0.kind == .link && !$0.tokens.contains { $0.kind == .linkPath } && !$0.text.hasPrefix("<") && !$0.text.contains(":") }) {
120 throw Unsupported(reason: "Radio targets")
121 }
122 let kinds = Set(tree.root.descendants().map(\.kind))
123 for (kind, name) in [(SyntaxKind.radioTarget, "Radio targets"), (.citation, "Citations"), (.inlineTask, "Inline tasks"),
124 (.inlineSourceBlock, "Inline source blocks"), (.inlineBabelCall, "Inline calls"), (.tableEl, "table.el tables"),
125 (.diarySexp, "Diary sexps")] where kinds.contains(kind) {
126 throw Unsupported(reason: name)
127 }
128 // Emacs measures text in columns, where these take two or none.
129 if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
130 // Tabs fill and align by column; in code they are copied.
131 let code = tree.root.descendants().filter { $0.kind == .block && $0.text.firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b/) != nil }.map(\.range)
132 if Array(text.utf16).enumerated().contains(where: { offset, unit in unit == 9 && !code.contains { $0.contains(offset) } }) {
133 throw Unsupported(reason: "Tabs outside code")
134 }
135 // A definition goes on to the next one, a heading or two blank lines.
136 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
137 guard let parent = node.parent, let index = parent.children.firstIndex(where: { $0.range == node.range }), index + 1 < parent.children.count else { continue }
138 let next = parent.children[index + 1]
139 let gap = (text as NSString).substring(with: NSRange(location: node.range.lowerBound, length: next.range.lowerBound - node.range.lowerBound))
140 if next.kind != .footnoteDefinition, next.kind != .section, !gap.hasSuffix("\n\n\n") {
141 throw Unsupported(reason: "Footnote definitions of several paragraphs")
142 }
143 }
144 for heading in model.headings {
145 let keys = heading.properties.map { $0.key.uppercased() }
146 if keys.contains("UNNUMBERED") || keys.contains("ALT_TITLE") { throw Unsupported(reason: "UNNUMBERED and ALT_TITLE properties") }
147 }
148 selected = HTMLRenderer.selection(tree, tags: options.selectTags)
149 let options = options
150 let selected = selected
151 let top = tree.root.children.compactMap { $0.kind == .section ? $0.firstChild(.heading) : nil }
152 .filter { HTMLRenderer.sectionExport($0, options: options, selected: selected) != .nothing }
153 levelOffset = 1 - (top.compactMap { $0.tokens.first { $0.kind == .stars }?.text.count }.min() ?? 1)
154 collectHeadings(tree.root.children)
155 }
156
157 static func isWideOrZeroWidth(_ s: Unicode.Scalar) -> Bool { isWide(s) || isZeroWidth(s) }
158
159 static func isWide(_ s: Unicode.Scalar) -> Bool {
160 switch s.value {
161 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3,
162 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD:
163 return true
164 default:
165 return false
166 }
167 }
168
169 static func isZeroWidth(_ s: Unicode.Scalar) -> Bool {
170 switch s.value {
171 case 0x200B...0x200F, 0xFE00...0xFE0F: return true
172 default: return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark
173 }
174 }
175
176 /// `string-width`.
177 static func width(_ s: String) -> Int {
178 s.unicodeScalars.reduce(0) { $0 + (isWide($1) ? 2 : isZeroWidth($1) ? 0 : 1) }
179 }
180
181 /// `org-export--collect-headline-numbering` over the headings the export writes.
182 private func collectHeadings(_ nodes: [SyntaxNode]) {
183 var counters: [Int] = []
184 func walk(_ nodes: [SyntaxNode]) {
185 for node in nodes where node.kind == .section {
186 guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { continue }
187 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
188 if export == .nothing { continue }
189 let level = self.level(heading)
190 exported.append((heading.range.lowerBound, level))
191 if isNumbered(level) {
192 while counters.count < level { counters.append(0) }
193 counters[level - 1] += 1
194 for deeper in level..<counters.count { counters[deeper] = 0 }
195 numbers[heading.range.lowerBound] = Array(counters.prefix(level))
196 }
197 if export == .all { walk(node.children) }
198 }
199 }
200 walk(nodes)
201 }
202
203 private func isFootnoteSection(_ heading: SyntaxNode) -> Bool { heading.firstChild(.title)?.text == "Footnotes" }
204
205 private func level(_ heading: SyntaxNode) -> Int {
206 (heading.tokens.first { $0.kind == .stars }?.text.count ?? 1) + levelOffset
207 }
208
209 private func isNumbered(_ level: Int) -> Bool { numbered && (num.map { level <= $0 } ?? true) }
210
211 // MARK: - Template
212
213 /// `org-ascii-template`: the title block and table of contents before `body`.
214 func template(_ body: String, author: String) throws -> String {
215 var out = try titleBlock(author: author)
216 if withTOC { out += try tableOfContents(depth: toc, width: Self.textWidth, keyword: false) + "\n\n\n" }
217 return out + body
218 }
219
220 /// `org-ascii-template--document-title`.
221 private func titleBlock(author defaultAuthor: String) throws -> String {
222 let width = Self.textWidth
223 linksToNotes = false
224 defer { linksToNotes = true }
225 let title = options.title ? try keywords["TITLE"].map(parsed) ?? "" : ""
226 let subtitle = options.title ? try keywords["SUBTITLE"].map(parsed) ?? "" : ""
227 var author: String?
228 if options.author { author = try keywords["AUTHOR"].map(parsed) ?? (defaultAuthor.isEmpty ? nil : try inlineString(defaultAuthor)) }
229 let date = options.date ? try keywords["DATE"].map(parsed) : nil
230 func nw(_ s: String?) -> String? { s.flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil } }
231 if title.isEmpty {
232 switch (nw(date), nw(author)) {
233 case (let date?, let author?):
234 return author + String(repeating: " ", count: max(0, width - date.count - author.count)) + date + "\n\n\n"
235 case (let date?, nil):
236 return Self.justifyLines(date, width: width, .right) + "\n\n\n"
237 case (nil, let author?):
238 return author + "\n\n\n"
239 default:
240 return ""
241 }
242 }
243 let titleLength = min((title + "\n" + subtitle).components(separatedBy: "\n").map(\.count).max() ?? 0, 2 * width / 3)
244 let formattedTitle = ASCIIText.fill(title, width: titleLength)
245 let formattedSubtitle = nw(subtitle).map { ASCIIText.fill($0, width: titleLength) }
246 let line = String(repeating: utf8 ? "━" : "_", count: min(max(titleLength, author?.count ?? 0) + 2, width))
247 var block = line + "\n" + (utf8 ? "" : "\n") + formattedTitle.uppercased()
248 if let formattedSubtitle { block += "\n" + formattedSubtitle }
249 if let author = nw(author) { block += "\n\n" + author }
250 block += "\n" + line
251 if let date = nw(date) { block += "\n\n\n" + date }
252 return Self.justifyLines(block + "\n\n\n", width: width, .center)
253 }
254
255 /// A keyword parsed as Org text, its lines joined with spaces.
256 private func parsed(_ values: [String]) throws -> String {
257 if values.count > 1, values.contains("") { throw Unsupported(reason: "Repeated keywords with an empty value") }
258 return try inlineString(values.joined(separator: " "))
259 }
260
261 /// `org-ascii--build-toc` over the whole document.
262 private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String {
263 let title = translate("Table of Contents")
264 var out = title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n"
265 let limit = min(depth ?? options.headlineLevels, options.headlineLevels)
266 var lines: [String] = []
267 for (start, level) in exported where level <= limit {
268 guard let heading = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == start }) else { continue }
269 let indent = (level - 1) * 3
270 let prefix = indent == 0 ? "" : String(repeating: ".", count: indent - 1) + " "
271 lines.append(prefix + (try buildTitle(heading, width: width - indent, underline: false, notags: !options.tags || !options.tagsInTOC, toc: true)))
272 }
273 out += lines.joined(separator: "\n")
274 _ = keyword
275 return out
276 }
277
278 // MARK: - Strings
279
280 /// `org-ascii--translate`.
281 func translate(_ term: String) -> String {
282 ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii)
283 }
284
285 /// A translation for text that is filled, which counts characters, not columns.
286 func translateFilled(_ term: String) throws -> String {
287 let text = translate(term)
288 if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
289 return text
290 }
291
292 /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs`
293 /// indents as `fill-region` does, with tabs where they fit.
294 static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String {
295 guard how != .left else { return s }
296 return s.components(separatedBy: "\n").map { line in
297 let trimmed = line.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
298 guard !trimmed.isEmpty else { return trimmed }
299 let room = width - trimmed.count
300 let indent = max(0, how == .center ? room / 2 : room)
301 return (tabs ? Self.indentation(indent) : String(repeating: " ", count: indent)) + trimmed
302 }.joined(separator: "\n")
303 }
304
305 /// `org-ascii--justify-element` for anything but a paragraph: the lines moved as a block
306 /// so the widest is centered or flushed right.
307 static func justifyBlock(_ s: String, context: Context) -> String {
308 guard context.justify != .left, s.contains(where: { !$0.isWhitespace }) else { return s }
309 let lines = s.components(separatedBy: "\n")
310 var widest = 0
311 for line in lines where line.contains(where: { $0 != " " && $0 != "\t" }) {
312 if line.count >= context.width { return s }
313 widest = max(widest, line.count)
314 }
315 let offset = (context.width - widest) / (context.justify == .right ? 1 : 2)
316 guard offset > 0 else { return s }
317 return lines.map { line in
318 line.contains(where: { $0 != " " && $0 != "\t" }) ? indentation(offset) + line : line
319 }.joined(separator: "\n")
320 }
321
322 /// `indent-to` from the line start with `indent-tabs-mode`.
323 static func indentation(_ columns: Int) -> String {
324 String(repeating: "\t", count: columns / 8) + String(repeating: " ", count: columns % 8)
325 }
326
327 /// `org-ascii--box-string`.
328 func box(_ s: String) -> String {
329 let body = s.replacing(#/\n[ \t]*\z/#, with: "")
330 let bar = utf8 ? "│ " : "| "
331 // `replace-regexp-in-string' finds no line start in the empty string.
332 let lines = body.isEmpty ? "" : body.components(separatedBy: "\n").map { bar + $0 }.joined(separator: "\n")
333 return utf8 ? "┌────\n" + lines + "\n└────" : ",----\n" + lines + "\n`----"
334 }
335
336 /// `org-element-normalize-string`.
337 static func normalize(_ s: String) -> String { LaTeXRenderer.normalize(s) }
338
339 /// The headline and section filter: whatever blank lines end `s`, two.
340 static func spaced(_ s: String) -> String {
341 var end = s.endIndex
342 var cut: String.Index?
343 while end > s.startIndex {
344 let before = s.index(before: end)
345 if s[before] == " " || s[before] == "\t" {
346 end = before
347 } else if s[before] == "\n" {
348 end = before
349 cut = before
350 } else {
351 break
352 }
353 }
354 guard let cut else { return s }
355 return String(s[..<cut]) + "\n\n\n"
356 }
357
358 // MARK: - Document
359
360 /// The transcoded document with its footnotes, `org-ascii-inner-template`.
361 func body() throws -> String {
362 var nodes = tree.root.children
363 // With a select tag, the text before the first heading isn't exported.
364 if selected != nil { nodes.removeAll { $0.kind == .zerothSection } }
365 var out = ""
366 for node in nodes {
367 if node.kind == .zerothSection {
368 out += try section(node.children, end: node.range.upperBound, heading: nil)
369 } else if node.kind == .section {
370 out += try headline(node) ?? ""
371 }
372 }
373 out = Self.normalize(out)
374 let notes = try footnotes()
375 if !notes.isEmpty {
376 let title = translate("Footnotes")
377 out += "\n\n\n" + title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n" + notes
378 }
379 return Self.normalize(out)
380 }
381
382 /// Blank lines at the end of `source[from..<to]`.
383 func blankLines(from: Int, to: Int) -> Int {
384 guard to > from else { return 0 }
385 let source = currentSource ?? self.source
386 let lines = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)).components(separatedBy: "\n").dropLast()
387 return lines.reversed().prefix { $0.allSatisfy { $0 == " " || $0 == "\t" } }.count
388 }
389
390 /// The text being transcoded when it isn't the document: a block's contents.
391 private var currentSource: NSString?
392
393 /// A section's elements as `org-ascii-section` writes them, the section filter applied: its
394 /// contents indented under a heading, then for the text before the first heading the
395 /// links it holds. `heading` is the relative level of the heading above, nil for none.
396 private func section(_ nodes: [SyntaxNode], end: Int, heading: Int?) throws -> String {
397 let low = heading.map { $0 > options.headlineLevels }
398 let width = Self.textWidth - (heading.map { $0 > options.headlineLevels ? ($0 - options.headlineLevels) * 2 : Self.innerMargin } ?? 0)
399 let linkStart = noted.count
400 var contents = try elements(nodes, end: end, context: Context(width: width))
401 if heading == nil {
402 let links = try describeLinks(from: linkStart, width: width)
403 if !links.isEmpty { contents = Self.normalize(contents) + "\n\n" + links }
404 }
405 if heading != nil, low == false { contents = ASCIIText.indent(contents, Self.innerMargin) }
406 return Self.spaced(Self.normalize(contents))
407 }
408
409 /// `org-ascii-headline`, the headline filter applied; nil when not exported.
410 private func headline(_ node: SyntaxNode) throws -> String? {
411 guard let heading = node.firstChild(.heading), !isFootnoteSection(heading) else { return nil }
412 let export = HTMLRenderer.sectionExport(heading, options: options, selected: selected)
413 if export == .nothing { return nil }
414 let level = self.level(heading)
415 let low = level > options.headlineLevels ? level - options.headlineLevels : nil
416 let width = Self.textWidth - (low.map { $0 * 2 } ?? 0)
417 let linkStart = noted.count
418 let title = try buildTitle(heading, width: width, underline: low == nil, notags: false, toc: false)
419 var body = ""
420 if export == .all {
421 let children = node.children.filter { $0.kind != .heading }
422 let elements = children.filter { $0.kind != .section }
423 let subsections = children.filter { $0.kind == .section }
424 var sectionText: String?
425 if !elements.isEmpty {
426 let end = subsections.first?.range.lowerBound ?? node.range.upperBound
427 sectionText = try section(elements, end: end, heading: level)
428 }
429 let links = try describeLinks(from: linkStart, width: width)
430 let sub = try subsections.compactMap { try headline($0) }.joined()
431 if links.isEmpty {
432 body = (sectionText ?? "") + sub
433 } else {
434 body = (sectionText.map { Self.normalize($0) + "\n\n" } ?? "") + links + sub
435 }
436 } else {
437 _ = try? describeLinks(from: linkStart, width: width)
438 }
439 let out: String
440 if let low {
441 let bullets: [Character] = switch charset {
442 case .ascii: ["*", "+", "-"]
443 case .latin1: ["§", ""]
444 case .utf8: ["◊"]
445 }
446 let bullet = "\(bullets[(low - 1) % bullets.count]) "
447 out = bullet + title + "\n\n" + ASCIIText.indent(body, bullet.count)
448 } else {
449 out = title + "\n\n" + body
450 }
451 return Self.spaced(Self.normalize(out))
452 }
453
454 /// `org-ascii--build-title` for a heading.
455 private func buildTitle(_ heading: SyntaxNode, width: Int, underline: Bool, notags: Bool, toc: Bool) throws -> String {
456 let tokens = heading.tokens
457 let level = self.level(heading)
458 var first = ""
459 if let number = numbers[heading.range.lowerBound] {
460 first += toc ? "\(number.last!). " : number.map(String.init).joined(separator: ".") + " "
461 }
462 if options.todo, let todo = tokens.first(where: { $0.kind == .todoKeyword })?.text { first += plainText(todo) + " " }
463 if options.priority, let priority = tokens.first(where: { $0.kind == .priority })?.text, let letter = priority.firstMatch(of: /\[#(.+)\]/)?.1 {
464 first += "(#\(letter)) "
465 }
466 let titleNode = heading.firstChild(.title)
467 if titleNode?.descendants().contains(where: { $0.kind == .footnoteReference }) == true { throw Unsupported(reason: "Footnotes in headings") }
468 first += try titleText(heading, toc: toc)
469 var out = first
470 if !notags, options.tags, let tags = tokens.first(where: { $0.kind == .tags })?.text {
471 let names = tags.split(separator: ":").map(String.init)
472 if !names.isEmpty {
473 let tagString = ":" + names.joined(separator: ":") + ":"
474 let column = max(width - (first.count + 1), tagString.count)
475 out += " " + String(repeating: " ", count: column - tagString.count) + tagString
476 }
477 }
478 let underlines: [Character] = switch charset {
479 case .ascii, .latin1: ["=", "~", "-"]
480 case .utf8: ["═", "─", "╌", "┄", "┈"]
481 }
482 if underline, level <= underlines.count {
483 out += "\n" + String(repeating: underlines[level - 1], count: first.count)
484 }
485 return out
486 }
487
488 /// A heading's title transcoded and trimmed, once: links in it are noted where it is first
489 /// written.
490 private func titleText(_ heading: SyntaxNode, toc: Bool) throws -> String {
491 if let cached = titles[heading.range.lowerBound] { return cached }
492 let text = try heading.firstChild(.title).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
493 titles[heading.range.lowerBound] = text
494 return text
495 }
496
497 private var titles: [Int: String] = [:]
498
499 // MARK: - Elements
500
501 /// Affiliated keywords of the element being transcoded.
502 typealias Affiliated = LaTeXRenderer.Affiliated
503
504 private func blockType(_ node: SyntaxNode) -> String {
505 node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/).map { $0.1.lowercased() } ?? ""
506 }
507
508 /// `elements`, each `org-element-normalize-string`'d and followed by its blank lines, as
509 /// `org-export-data` joins a greater element's contents.
510 /// `firstParagraph` says which paragraph's first line follows a bullet; `written` hears
511 /// what each element wrote.
512 func elements(
513 _ nodes: [SyntaxNode], end: Int, context: Context,
514 firstParagraph: ((SyntaxNode) -> Bool)? = nil, written: ((SyntaxNode, String) -> Void)? = nil
515 ) throws -> String {
516 var out = ""
517 var affiliated = Affiliated()
518 // The element before and its blank lines, which a comment after it may add to; they
519 // show only when it wrote something.
520 var pendingBlank = 0
521 var previous: SyntaxNode?
522 var previousWrote = false
523 var afterSrc = false
524 for (index, node) in nodes.enumerated() {
525 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
526 if node.kind == .affiliatedKeyword {
527 let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
528 guard let m = line.firstMatch(of: /^#\+([A-Za-z_]+)(\[[^\]]*\])?:[ \t]*(.*)$/) else { continue }
529 let key = m.1.uppercased()
530 if m.2 != nil, key != "CAPTION", key != "RESULTS" { throw Unsupported(reason: "#+\(key)[…]") }
531 switch key {
532 case "CAPTION":
533 if m.2 != nil { throw Unsupported(reason: "Short captions") }
534 affiliated.caption.append(String(m.3))
535 case "NAME": affiliated.name = String(m.3)
536 case "ATTR_ASCII": affiliated.attr.append(String(m.3))
537 case "RESULTS": affiliated.results = String(m.3)
538 default: break
539 }
540 continue
541 }
542 defer { affiliated = Affiliated() }
543 // `org-babel-exp-process-buffer`: a src block's results go, and with `:exports none`
544 // the block too, as if they had never been there.
545 if node.kind == .block, blockType(node) == "src" {
546 let exports = exportSource.exports(at: node.range.lowerBound) ?? "code"
547 if exports != "code", exports != "none" { throw Unsupported(reason: ":exports \(exports)") }
548 afterSrc = true
549 if exports == "none" { continue }
550 } else if let results = affiliated.results {
551 if afterSrc {
552 afterSrc = false
553 continue
554 }
555 if results.isEmpty { throw Unsupported(reason: "#+RESULTS without a source block") }
556 if affiliated.name == nil { affiliated.name = results }
557 } else {
558 afterSrc = false
559 }
560 if node.kind == .comment || (node.kind == .block && blockType(node) == "comment") {
561 // `org-export--skip-p`: the element before keeps at least one blank line.
562 if previous != nil {
563 let blank = max(pendingBlank, blankLines(from: node.range.lowerBound, to: next), 1)
564 if previousWrote { out += String(repeating: "\n", count: blank - pendingBlank) }
565 pendingBlank = blank
566 }
567 continue
568 }
569 let result: String?
570 if node.kind == .paragraph, let firstParagraph {
571 result = try paragraph(node, context: context, ignoreFirst: firstParagraph(node))
572 } else {
573 result = try element(node, affiliated: affiliated, context: context)
574 }
575 guard let result else {
576 if !pruned(node) {
577 previous = node
578 previousWrote = false
579 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
580 }
581 continue
582 }
583 previous = node
584 previousWrote = true
585 pendingBlank = blankLines(from: node.range.lowerBound, to: next)
586 written?(node, result)
587 out += Self.normalize(result) + String(repeating: "\n", count: pendingBlank)
588 }
589 return out
590 }
591
592 /// Elements `org-export--prune-tree` takes out of the tree.
593 private func pruned(_ node: SyntaxNode) -> Bool {
594 switch node.kind {
595 case .planning, .propertyDrawer, .clock: return true
596 case .drawer: return drawerName(node).uppercased() == "LOGBOOK"
597 case .latexEnvironment: return !options.tex
598 default: return false
599 }
600 }
601
602 private func drawerName(_ node: SyntaxNode) -> String {
603 node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1) } ?? ""
604 }
605
606 /// One element's transcoding, nil for none.
607 private func element(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
608 switch node.kind {
609 case .paragraph:
610 return try paragraph(node, context: context, ignoreFirst: false)
611 case .plainList:
612 return try list(node, context: context)
613 case .table:
614 return try table(node, affiliated: affiliated, context: context)
615 case .block:
616 return try block(node, affiliated: affiliated, context: context)
617 case .fixedWidth:
618 let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in
619 let trimmed = line.drop { $0 == " " || $0 == "\t" }
620 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1))
621 }
622 return Self.justifyBlock(box(try LaTeXRenderer.removeIndentation(lines.joined(separator: "\n"))), context: context)
623 case .horizontalRule:
624 let width = affiliated.value("width").flatMap { $0.allSatisfy(\.isNumber) ? Int($0) : nil } ?? context.width
625 return Self.justifyLines(String(repeating: utf8 ? "―" : "-", count: width), width: context.width, .center)
626 case .drawer:
627 if drawerName(node).uppercased() == "LOGBOOK" { return nil }
628 guard hasContents(node.children) else { return nil }
629 return Self.normalize(try elements(node.children, end: node.range.upperBound, context: context))
630 case .dynamicBlock:
631 let lines = node.text.components(separatedBy: "\n")
632 return try blockContents(Array(lines.dropFirst().dropLast(2)), context: context)
633 case .latexEnvironment:
634 guard options.tex else { return nil }
635 return Self.justifyBlock(try LaTeXRenderer.removeIndentation(node.text), context: context)
636 case .keyword:
637 return try keyword(node, context: context)
638 case .planning, .propertyDrawer, .clock, .footnoteDefinition:
639 return nil
640 default:
641 throw Unsupported(reason: "\(node.kind)")
642 }
643 }
644
645 /// Whether `nodes` hold an element the export keeps.
646 private func hasContents(_ nodes: [SyntaxNode]) -> Bool {
647 nodes.indices.contains { index in
648 let node = nodes[index]
649 switch node.kind {
650 case .comment: return false
651 case .affiliatedKeyword:
652 // Org parses affiliated keywords with no element right after them as keywords.
653 var last = index
654 while last + 1 < nodes.count, nodes[last + 1].kind == .affiliatedKeyword,
655 nodes[last].range.upperBound == nodes[last + 1].range.lowerBound { last += 1 }
656 return last + 1 == nodes.count || nodes[last].range.upperBound != nodes[last + 1].range.lowerBound
657 case .block:
658 let type = blockType(node)
659 if type == "comment" { return false }
660 if type == "src", exportSource.exports(at: node.range.lowerBound) == "none" { return false }
661 return !isResults(node)
662 default: return !pruned(node)
663 }
664 }
665 }
666
667 private func keyword(_ node: SyntaxNode, context: Context) throws -> String? {
668 guard let m = node.text.firstMatch(of: /^[ \t]*#\+([^:\s]+):[ \t]*(.*?)[ \t]*\n?$/) else { return nil }
669 let value = String(m.2)
670 switch m.1.uppercased() {
671 case "ASCII":
672 return Self.justifyBlock(value, context: context)
673 case "TOC":
674 guard value.range(of: "\\bheadlines\\b", options: [.regularExpression, .caseInsensitive]) != nil else {
675 throw Unsupported(reason: "#+TOC: \(value)")
676 }
677 if value.range(of: "\\blocal\\b|:target", options: [.regularExpression, .caseInsensitive]) != nil { throw Unsupported(reason: "#+TOC: \(value)") }
678 let depth = value.firstMatch(of: /\b([0-9]+)\b/).flatMap { Int($0.1) }
679 return Self.justifyBlock(try tableOfContents(depth: depth, width: context.width, keyword: true), context: context)
680 default:
681 return nil
682 }
683 }
684
685 // MARK: Paragraphs
686
687 private func paragraph(_ node: SyntaxNode, context: Context, ignoreFirst: Bool, prefix: String = "") throws -> String {
688 // `:with-timestamps` decides on timestamps alone in a paragraph.
689 isolatedTimestamps = ASCIIText.isolatedTimestamps(node)
690 defer { isolatedTimestamps = false }
691 let items = LaTeXRenderer.normalizeIndentation(inlineItems(node), ignoreFirst: ignoreFirst)
692 // `org-remove-blank-lines`, whose newline isn't a hard one.
693 let contents = (prefix + (try transcode(items))).replacing(#/\x{1}?\n(?:[ \t]*\x{1}?\n)+/#, with: "\n")
694 guard contents.contains(where: { !$0.isWhitespace && $0 != "\u{1}" }) else { return contents }
695 return Self.fill(contents.replacingOccurrences(of: Self.hardNewline, with: ASCIIText.hardNewline), context: context)
696 }
697
698 /// `org-ascii--fill-string` with the context's justification.
699 static func fill(_ s: String, context: Context) -> String {
700 let filled = ASCIIText.fill(s, width: context.width)
701 return justifyLines(filled, width: context.width, context.justify, tabs: true)
702 }
703
704 // MARK: Lists
705
706 private func list(_ node: SyntaxNode, context: Context) throws -> String {
707 let items = node.children.filter { $0.kind == .item }
708 guard let first = items.first else { return "" }
709 let firstBullet = (first.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
710 let ordered = firstBullet.first.map { $0.isASCII && ($0.isLetter || $0.isNumber) } ?? false
711 let descriptive = !ordered && first.firstChild(.itemTag) != nil
712 var out = ""
713 var number = 0
714 for (index, item) in items.enumerated() {
715 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : node.range.upperBound
716 let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
717 let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text.uppercased() {
718 case "[X]"?: utf8 ? "☑ " : "[X] "
719 case "[ ]"?: utf8 ? "☐ " : "[ ] "
720 case "[-]"?: utf8 ? "☒ " : "[-] "
721 default: ""
722 }
723 let bullet: String
724 if descriptive {
725 let tag = try item.firstChild(.itemTag).map { LaTeXRenderer.trim(try transcode(inlineItems($0))) } ?? ""
726 bullet = checkbox + tag
727 } else if ordered {
728 if let counter = item.tokens.first(where: { $0.kind == .counter })?.text {
729 guard let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) else { throw Unsupported(reason: "Alphabetical counters") }
730 number = n
731 } else {
732 number += 1
733 }
734 bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " "
735 } else {
736 bullet = utf8 ? (["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " ") : bulletText + " "
737 }
738 let indentation = descriptive ? Self.quoteMargin : bullet.count
739 let inner = Context(width: context.width - (descriptive ? Self.quoteMargin : bullet.count + checkbox.count), justify: context.justify)
740 let children = item.children.filter { $0.kind != .itemTag }
741 if children.isEmpty { throw Unsupported(reason: "Empty list items") }
742 let bulletLine = source.lineRange(for: NSRange(location: item.range.lowerBound, length: 0))
743 var firstWriter: SyntaxNode?
744 let contents = try elements(children, end: item.range.upperBound, context: inner, firstParagraph: { paragraph in
745 paragraph.range == children[0].range && paragraph.range.lowerBound < NSMaxRange(bulletLine)
746 }, written: { node, text in
747 if firstWriter == nil, text.contains(where: { !$0.isWhitespace }) { firstWriter = node }
748 })
749 if children.contains(where: { $0.kind == .affiliatedKeyword }) { throw Unsupported(reason: "Affiliated keywords in list items") }
750 let indented = ASCIIText.indent(children.isEmpty ? "" : Self.normalize(contents), indentation)
751 var text = bullet + checkbox
752 if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstWriter?.kind == .paragraph {
753 text += LaTeXRenderer.trim(indented)
754 } else {
755 text += "\n" + indented
756 }
757 out += Self.normalize(text) + String(repeating: "\n", count: blankLines(from: item.range.lowerBound, to: next))
758 }
759 return out
760 }
761
762 // MARK: Tables
763
764 private func table(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String {
765 let rows = node.children.filter { $0.kind == .tableRow }
766 // Each row's cells, nil for a rule.
767 let raw: [[SyntaxNode]?] = rows.map { row in
768 let cells = row.children.filter { $0.kind == .tableCell }
769 return cells.isEmpty ? nil : cells
770 }
771 let cookie = /^<[lrc]?[0-9]*>$/
772 func value(_ cell: SyntaxNode) -> String { cell.text.trimmingCharacters(in: CharacterSet(charactersIn: " |\n")) }
773 // Rows of only alignment cookies and empty cells.
774 let special = raw.map { cells -> Bool in
775 guard let cells else { return false }
776 let values = cells.map(value)
777 return values.contains { $0.wholeMatch(of: cookie) != nil } && values.allSatisfy { $0.isEmpty || $0.wholeMatch(of: cookie) != nil }
778 }
779 for cells in raw.compactMap({ $0 }) {
780 let first = value(cells[0])
781 if first == "/" || ["#", "!", "$", "*", "_", "^"].contains(first) { throw Unsupported(reason: "Tables with special columns or column groups") }
782 }
783 // Transcoded cells.
784 var data: [[String]?] = []
785 for (r, cells) in raw.enumerated() {
786 guard let cells, !special[r] else { data.append(nil); continue }
787 data.append(try cells.map { try LaTeXRenderer.trim(transcode(inlineItems($0, trimmed: true))) })
788 }
789 let columns = raw.compactMap { $0?.count }.max() ?? 0
790 var widths = Array(repeating: 0, count: columns)
791 var cookieWidth = Array(repeating: Int?.none, count: columns)
792 var cookieAlign = Array(repeating: String?.none, count: columns)
793 for (r, cells) in raw.enumerated() where special[r] {
794 for (c, cell) in cells!.enumerated() {
795 guard let m = value(cell).wholeMatch(of: /<([lrc])?([0-9]+)?>/) else { continue }
796 if let w = m.2.flatMap({ Int($0) }), cookieWidth[c] == nil { cookieWidth[c] = w }
797 if let a = m.1 { cookieAlign[c] = String(a) }
798 }
799 }
800 for row in data.compactMap({ $0 }) { for (c, cell) in row.enumerated() { widths[c] = max(widths[c], cell.count) } }
801 for c in 0..<columns { if let w = cookieWidth[c] { widths[c] = max(widths[c], w) } }
802 let number = LaTeXRenderer.numberPattern
803 let align: [Justify] = (0..<columns).map { c in
804 switch cookieAlign[c] {
805 case "l": return .left
806 case "r": return .right
807 case "c": return .center
808 default: break
809 }
810 var numbers = 0
811 var total = 0
812 var previousNumber = false
813 for (r, row) in data.enumerated() where raw[r] != nil && !special[r] {
814 let cell = c < row!.count ? row![c] : ""
815 total += 1
816 let isNumber = number.firstMatch(in: cell, range: NSRange(cell.startIndex..., in: cell)) != nil || (cell.isEmpty && previousNumber)
817 previousNumber = isNumber
818 if isNumber { numbers += 1 }
819 }
820 return total > 0 && Double(numbers) / Double(total) >= 0.5 ? .right : .left
821 }
822 let standard = data.indices.filter { data[$0] != nil }
823 var out = ""
824 for (position, r) in standard.enumerated() {
825 let row = data[r]!
826 let ruleAbove = raw[(position == 0 ? 0 : standard[position - 1] + 1)..<r].contains { $0 == nil }
827 let ruleBelow = raw[(r + 1)..<(position + 1 < standard.count ? standard[position + 1] : raw.count)].contains { $0 == nil }
828 func hline(_ char: String) -> String { row.indices.map { String(repeating: char, count: widths[$0] + 2) }.joined() + "\n" }
829 if position == 0, utf8 || ruleAbove {
830 out += hline(utf8 ? "━" : "-")
831 } else if position > 0, ruleAbove {
832 out += hline(utf8 ? "─" : "-")
833 }
834 out += row.enumerated().map { c, cell in
835 let pad = widths[c] - cell.count
836 let justified: String = switch align[c] {
837 case .left: cell + String(repeating: " ", count: pad)
838 case .right: String(repeating: " ", count: pad) + cell
839 case .center: String(repeating: " ", count: pad / 2) + cell + String(repeating: " ", count: pad - pad / 2)
840 }
841 return " " + justified + " "
842 }.joined() + "\n"
843 if position == standard.count - 1, utf8 || ruleBelow { out += hline(utf8 ? "━" : "-") }
844 }
845 let caption = try buildCaption(affiliated, type: "Table %d:", counter: &tableCount, context: context)
846 return Self.justifyBlock(out + (caption ?? ""), context: context)
847 }
848
849 private var isolatedTimestamps = false
850 private var tableCount = 0
851 private var listingCount = 0
852
853 /// `org-ascii--build-caption`.
854 private func buildCaption(_ affiliated: Affiliated, type: String, counter: inout Int, context: Context) throws -> String? {
855 guard !affiliated.caption.isEmpty else { return nil }
856 if affiliated.caption.count > 1 { throw Unsupported(reason: "Several captions") }
857 counter += 1
858 let saved = noting
859 noting = false
860 defer { noting = saved }
861 let text = try inlineString(affiliated.caption[0])
862 return ASCIIText.fill(try translateFilled(type).replacingOccurrences(of: "%d", with: String(counter)) + " " + text, width: context.width)
863 }
864
865 // MARK: Blocks
866
867 private func block(_ node: SyntaxNode, affiliated: Affiliated, context: Context) throws -> String? {
868 var lines = node.text.components(separatedBy: "\n")
869 if lines.last == "" { lines.removeLast() }
870 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
871 let type = m.1.lowercased()
872 let parameters = String(m.2)
873 let body = Array(lines.dropFirst().dropLast())
874 let unescaped = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
875 let text = unescaped.joined(separator: "\n")
876 switch type {
877 case "src", "example":
878 let code = try formatCode(lines)
879 var out = box(code)
880 if type == "src", let caption = try buildCaption(affiliated, type: "Listing %d:", counter: &listingCount, context: context) {
881 out += "\n" + caption
882 }
883 return Self.justifyBlock(out, context: context)
884 case "quote":
885 guard let contents = try blockContents(unescaped, context: Context(width: context.width - 2 * Self.quoteMargin, justify: context.justify)) else { return nil }
886 return ASCIIText.indent(contents, Self.quoteMargin)
887 case "center":
888 return try blockContents(unescaped, context: Context(width: context.width, justify: .center))
889 case "verse":
890 return ASCIIText.indent(Self.justifyBlock(try verse(unescaped), context: context), Self.quoteMargin)
891 case "export":
892 let backend = parameters.split(separator: " ").first.map { $0.uppercased() } ?? ""
893 guard backend == "ASCII" else { return nil }
894 return Self.justifyBlock(text + "\n", context: context)
895 case "comment":
896 return nil
897 default:
898 var inner = context
899 if m.1 == "JUSTIFYRIGHT" { inner.justify = .right }
900 if m.1 == "JUSTIFYLEFT" { inner.justify = .left }
901 return try blockContents(unescaped, context: inner)
902 }
903 }
904
905 /// A greater block's contents, parsed as elements; nil when it has none.
906 private func blockContents(_ lines: [String], context: Context) throws -> String? {
907 guard !lines.isEmpty else { return nil }
908 if lines[0].allSatisfy({ $0 == " " || $0 == "\t" }) { throw Unsupported(reason: "Blocks opening with a blank line") }
909 let text = lines.joined(separator: "\n") + "\n"
910 let tree = OrgParser.parse(text, defaults: settings)
911 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
912 if nodes.contains(where: { $0.kind == .section }) { throw Unsupported(reason: "Headings inside blocks") }
913 let saved = (currentSource, exportSource)
914 currentSource = text as NSString
915 exportSource = ExportSource(tree: tree, text: text)
916 defer { (currentSource, exportSource) = saved }
917 guard hasContents(nodes) else { return nil }
918 return Self.normalize(try elements(nodes, end: (text as NSString).length, context: context))
919 }
920
921 /// `org-export-format-code-default` for a src or example block's lines.
922 private func formatCode(_ lines: [String]) throws -> String {
923 guard let parsed = Coderef.block(lines) else { return "\n" }
924 let blockLoc = try blockLoc(lines, numbered: parsed.switches.numberLines != nil)
925 var value = parsed.body.joined(separator: "\n")
926 if !value.isEmpty { value += "\n" }
927 let preserve = lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_(?:src|example))\b.*\s-i\b/) != nil
928 var code = preserve ? value : try LaTeXRenderer.removeIndentation(value)
929 // Emacs writes a src block's leading tabs as spaces.
930 if !preserve, lines[0].firstMatch(of: /^[ \t]*#\+(?i:begin_src)\b/) != nil {
931 code = code.components(separatedBy: "\n").map { line in
932 var column = 0
933 let indentation = line.prefix { $0 == " " || $0 == "\t" }
934 for c in indentation { column = c == "\t" ? (column / 8 + 1) * 8 : column + 1 }
935 return String(repeating: " ", count: column) + line.dropFirst(indentation.count)
936 }.joined(separator: "\n")
937 }
938 if code.hasSuffix("\n") { code.removeLast() }
939 let (lines, refs) = Coderef.unravel(code.components(separatedBy: "\n"), format: parsed.switches.labelFormat)
940 let loc = parsed.switches.numberLines == nil ? nil : blockLoc
941 guard loc != nil || (parsed.switches.retainLabels && !refs.isEmpty) else { return lines.joined(separator: "\n") + "\n" }
942 let width = loc.map { String($0 + lines.count).count } ?? 0
943 let numberWidth = loc == nil ? 0 : width + 2
944 let maxWidth = (lines.map(\.count).max() ?? 0) + numberWidth
945 return lines.enumerated().map { index, line in
946 var out = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
947 out += line
948 if parsed.switches.retainLabels, let ref = refs[index + 1] {
949 out += String(repeating: " ", count: maxWidth + 6 - out.count) + "(\(ref))"
950 }
951 return out
952 }.joined(separator: "\n") + "\n"
953 }
954
955 /// The src and example blocks the export writes, in order, as their lines.
956 private lazy var exportedBlocks: [[String]] = {
957 let source = ExportSource(tree: tree, text: self.source as String)
958 return tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
959 var lines = node.text.components(separatedBy: "\n")
960 if lines.last == "" { lines.removeLast() }
961 guard Coderef.block(lines) != nil, !excluded(node), !isResults(node) else { return nil }
962 if blockType(node) == "src", source.exports(at: node.range.lowerBound) == "none" { return nil }
963 return lines
964 }
965 }()
966
967 /// Whether `node` is the results of the src block before it, which the export removes.
968 private func isResults(_ node: SyntaxNode) -> Bool {
969 guard let siblings = node.parent?.children, let index = siblings.firstIndex(where: { $0.range == node.range }) else { return false }
970 let keywords = siblings[..<index].reversed().prefix { $0.kind == .affiliatedKeyword }
971 guard keywords.contains(where: { $0.text.firstMatch(of: /^[ \t]*#\+(?i:results)[\[:]/) != nil }) else { return false }
972 let before = index - keywords.count - 1
973 return before >= 0 && siblings[before].kind == .block && blockType(siblings[before]) == "src"
974 }
975
976 /// Each src and example block's `org-export-get-loc`, by the block's text, in order.
977 private lazy var blockLocs: [String: [Int?]] = {
978 let blocks = exportedBlocks
979 var locs: [String: [Int?]] = [:]
980 for (lines, loc) in zip(blocks, Coderef.locs(blocks.compactMap(Coderef.block))) {
981 locs[lines.joined(separator: "\n"), default: []].append(loc)
982 }
983 return locs
984 }()
985
986 /// `org-export-get-loc` of the block with `lines`, the next of those with the same text.
987 private func blockLoc(_ lines: [String], numbered: Bool) throws -> Int? {
988 let key = lines.joined(separator: "\n")
989 guard let queue = blockLocs[key], !queue.isEmpty else {
990 if numbered { throw Unsupported(reason: "Numbered blocks inside other blocks") }
991 return nil
992 }
993 blockLocs[key] = Array(queue.dropFirst())
994 return queue[0]
995 }
996
997 /// Whether `node` is under a section the export leaves out.
998 private func excluded(_ node: SyntaxNode) -> Bool {
999 var current: SyntaxNode? = node
1000 while let n = current {
1001 if n.kind == .section, let heading = n.firstChild(.heading),
1002 HTMLRenderer.sectionExport(heading, options: options, selected: selected) != .all { return true }
1003 current = n.parent
1004 }
1005 return false
1006 }
1007
1008 /// A verse block's objects, their common indentation removed.
1009 private func verse(_ lines: [String]) throws -> String {
1010 let text = lines.joined(separator: "\n") + "\n"
1011 let tree = OrgParser.parse(text, defaults: settings)
1012 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1013 guard nodes.allSatisfy({ $0.kind == .paragraph }), let firstNode = nodes.first else { throw Unsupported(reason: "Verse blocks with more than text") }
1014 let ns = text as NSString
1015 var raw: [Inline] = [.text(ns.substring(to: firstNode.range.lowerBound))]
1016 for (index, node) in nodes.enumerated() {
1017 raw += inlineItems(node)
1018 let end = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : ns.length
1019 raw.append(.text(ns.substring(with: NSRange(location: node.range.upperBound, length: end - node.range.upperBound))))
1020 }
1021 return try transcode(LaTeXRenderer.normalizeIndentation(LaTeXRenderer.merge(raw), ignoreFirst: false))
1022 }
1023
1024 // MARK: - Objects
1025
1026 /// The contents of `node` as `Inline`s, markers left out, a line break's newline taken in.
1027 func inlineItems(_ node: SyntaxNode, trimmed: Bool = false) -> [Inline] {
1028 var items: [Inline] = []
1029 var skipNewline = false
1030 for element in node.elements {
1031 switch element {
1032 case .token(let token):
1033 switch token.kind {
1034 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter:
1035 continue
1036 default:
1037 var text = token.text
1038 if skipNewline {
1039 let rest = text.drop { $0 == " " || $0 == "\t" }
1040 if rest.hasPrefix("\n") { text = String(rest.dropFirst()); skipNewline = false } else if !rest.isEmpty { skipNewline = false } else { text = "" }
1041 }
1042 if !text.isEmpty { items.append(.text(text)) }
1043 }
1044 case .node(let child):
1045 skipNewline = false
1046 switch child.kind {
1047 case .bold, .italic, .underline, .strikeThrough, .linkDescription:
1048 items.append(.object(child, inlineItems(child)))
1049 case .link:
1050 items.append(.object(child, child.firstChild(.linkDescription).map { inlineItems($0) } ?? []))
1051 case .superscript, .subscript:
1052 let text = child.text
1053 let braced = text.dropFirst().hasPrefix("{")
1054 if options.scripts == .off || (options.scripts == .braces && !braced) {
1055 items.append(.text(text))
1056 } else if braced {
1057 items.append(.object(child, inlineItems(child)))
1058 } else {
1059 items.append(.object(child, [.text(String(text.dropFirst()))]))
1060 }
1061 case .lineBreak where trimmed:
1062 items.append(.text(child.text))
1063 case .lineBreak:
1064 items.append(.object(child, []))
1065 skipNewline = true
1066 default:
1067 items.append(.object(child, []))
1068 }
1069 }
1070 }
1071 if trimmed {
1072 if case .text(let t) = items.first { items[0] = .text(String(t.drop { $0 == " " || $0 == "\t" })) }
1073 if case .text(let t) = items.last { items[items.count - 1] = .text(String(t.reversed().drop { $0 == " " || $0 == "\t" }.reversed())) }
1074 }
1075 return LaTeXRenderer.merge(items)
1076 }
1077
1078 /// One line of Org text transcoded, for keywords and captions.
1079 func inlineString(_ text: String) throws -> String {
1080 let tree = OrgParser.parse(text, defaults: settings)
1081 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1082 if tree.root.descendants().contains(where: { $0.kind == .footnoteReference }) { throw Unsupported(reason: "Footnotes in keywords and captions") }
1083 let saved = exportSource
1084 exportSource = ExportSource(tree: tree, text: text)
1085 defer { exportSource = saved }
1086 return LaTeXRenderer.trim(try transcode(inlineItems(paragraph)))
1087 }
1088
1089 /// `org-export-data` over objects: objects that export nothing taking their blanks with
1090 /// them unless they are needed.
1091 func transcode(_ items: [Inline]) throws -> String {
1092 var out = ""
1093 var index = 0
1094 var dropBlanks = false
1095 var afterObject = false
1096 while index < items.count {
1097 let item = items[index]
1098 switch item {
1099 case .text(var t):
1100 if dropBlanks {
1101 t = String(t.drop { $0 == " " || $0 == "\t" })
1102 } else if afterObject {
1103 let blanks = t.prefix { $0 == " " || $0 == "\t" }
1104 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
1105 }
1106 dropBlanks = false
1107 afterObject = false
1108 out += try plainTextAndLinks(t)
1109 index += 1
1110 case .object(let node, let children):
1111 dropBlanks = false
1112 afterObject = true
1113 if let result = try object(node, children) {
1114 out += result
1115 } else {
1116 // `org-export--keep-spaces`: blanks after a dropped object stay only
1117 // between text that has none.
1118 let previousBlank: Bool
1119 if index == 0 {
1120 previousBlank = true
1121 } else if case .text(let t) = items[index - 1] {
1122 previousBlank = t.last.map { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ?? false
1123 } else {
1124 previousBlank = false
1125 }
1126 dropBlanks = previousBlank
1127 }
1128 index += 1
1129 }
1130 }
1131 return out
1132 }
1133
1134 private func object(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1135 switch node.kind {
1136 case .bold: return "*\(try transcode(children))*"
1137 case .italic: return "/\(try transcode(children))/"
1138 case .underline: return "_\(try transcode(children))_"
1139 case .strikeThrough: return "+\(try transcode(children))+"
1140 case .verbatim, .code: return "`\(node.text.dropFirst().dropLast())'"
1141 case .link: return try link(node, children)
1142 case .linkDescription: return try transcode(children)
1143 case .timestamp:
1144 if isolatedTimestamps, ICalendarExport.skipsTimestamp(node.text, with: options.timestamps ?? "t") { return nil }
1145 return plainText(ASCIIText.timestamp(node.text))
1146 case .footnoteReference: return try footnoteReference(node)
1147 case .entity:
1148 let name = String(node.text.dropFirst()).replacingOccurrences(of: "{}", with: "")
1149 guard let entity = OrgEntities.text[name] else { throw Unsupported(reason: "Unknown entity \(node.text)") }
1150 return switch charset {
1151 case .ascii: entity.ascii
1152 case .latin1: entity.latin1
1153 case .utf8: entity.utf8
1154 }
1155 case .superscript: return node.text.dropFirst().hasPrefix("{") ? "^{\(try transcode(children))}" : "^\(try transcode(children))"
1156 case .subscript: return node.text.dropFirst().hasPrefix("{") ? "_{\(try transcode(children))}" : "_\(try transcode(children))"
1157 case .lineBreak: return Self.hardNewline
1158 case .latexFragment: return options.tex ? node.text : nil
1159 case .statisticsCookie: return node.text
1160 case .exportSnippet:
1161 let backend = node.tokens.first?.text.dropFirst(2).dropLast() ?? ""
1162 guard backend == "ascii" else { return nil }
1163 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
1164 case .target:
1165 return nil
1166 case .macro:
1167 guard case .some(let value) = exportSource.resultsMacro(node) else { return nil }
1168 return try value.map(inlineString)
1169 default:
1170 throw Unsupported(reason: "\(node.kind)")
1171 }
1172 }
1173
1174 /// `org-ascii-plain-text`.
1175 func plainText(_ text: String) -> String {
1176 guard options.specialStrings else { return text }
1177 let text = text.replacingOccurrences(of: "\\-", with: "")
1178 guard utf8 else { return text }
1179 return text.replacingOccurrences(of: "---", with: "—").replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…")
1180 }
1181
1182 /// Text with the plain links the parser leaves in it, `FILE:x` and the like, written as Emacs does.
1183 private func plainTextAndLinks(_ t: String) throws -> String {
1184 let ns = t as NSString
1185 var out = ""
1186 var last = 0
1187 for m in Self.plainLink.matches(in: t, range: NSRange(location: 0, length: ns.length)) {
1188 let type = ns.substring(with: m.range(at: 1))
1189 guard ["http", "https", "mailto", "file"].contains(type.lowercased()) else { throw Unsupported(reason: "Plain links of type \(type)") }
1190 out += plainText(ns.substring(with: NSRange(location: last, length: m.range.location - last))) + "<" + ns.substring(with: m.range) + ">"
1191 last = NSMaxRange(m.range)
1192 }
1193 return out + plainText(ns.substring(from: last))
1194 }
1195
1196 // MARK: Links
1197
1198 /// A link written in notes mode: its footprint and how `org-ascii--describe-links`
1199 /// describes it, nil for none.
1200 private struct Noted {
1201 var footprint: String
1202 var note: String?
1203 }
1204
1205 /// Links written so far, for their section's notes.
1206 private var noted: [Noted] = []
1207 /// Whether links written now are noted: not in captions.
1208 private var noting = true
1209
1210 /// `org-ascii--describe-links` for the links noted since `start`, each once.
1211 private func describeLinks(from start: Int, width: Int) throws -> String {
1212 guard linksToNotes else { return "" }
1213 var seen: Set<String> = []
1214 var out = ""
1215 for link in noted[start...] where !seen.contains(link.footprint) {
1216 seen.insert(link.footprint)
1217 if let note = link.note {
1218 let filled = ASCIIText.fill(note, width: width)
1219 // Emacs fills by columns: the same unless wide characters take a line past them.
1220 if note.unicodeScalars.contains(where: Self.isZeroWidth) || filled.split(separator: "\n").contains(where: { Self.width(String($0)) > max(width, $0.count) }) {
1221 throw Unsupported(reason: "Wide or combining characters")
1222 }
1223 out += filled + "\n\n"
1224 }
1225 }
1226 noted.removeSubrange(start...)
1227 return out
1228 }
1229
1230 /// Link types Org registers in an Org buffer that this export doesn't write as Emacs does.
1231 private static let unrenderedTypes: Set<String> = ["attachment", "bbdb", "bibtex", "docview", "doi", "eww", "gnus", "info", "irc", "mhe", "rmail", "w3m"]
1232
1233 /// `org-link-plain-re`, in any case, for the plain links the parser leaves as text.
1234 private static let plainLink: NSRegularExpression = {
1235 let plain = #"[^\[\]\s()<>]"#
1236 let parens = #"[<(\[](?:\#(plain)|[<(\[]\#(plain)*[\])>])*[\])>]"#
1237 let types = "attachment|bbdb|bibtex|docview|doi|elisp|eww|file\\+emacs|file\\+sys|file|ftp|gnus|help|https?|id|info|irc|mailto|mhe|news|rmail|shell|shortdoc|w3m"
1238 return try! NSRegularExpression(pattern: #"(?i)(?<![\p{L}\p{N}_])("# + types + #"):(?:\#(plain)|\#(parens))+(?:[^\p{P}\p{S}\s]|[/-]|\#(parens))"#)
1239 }()
1240
1241 private static let externalTypes: Set<String> = ["file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1242
1243 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1244 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1245 throw Unsupported(reason: "Links in link descriptions")
1246 }
1247 let pathToken = node.tokens.first { $0.kind == .linkPath }?.text
1248 var raw = pathToken ?? node.text
1249 if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) }
1250 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1251 if description?.contains(where: { !$0.isWhitespace }) != true { description = nil }
1252 let linkType = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1) }
1253 if let linkType, Self.unrenderedTypes.contains(linkType) { throw Unsupported(reason: "Links of type \(linkType)") }
1254 let footprint = raw + "\u{0}" + (node.firstChild(.linkDescription)?.text ?? "").split(whereSeparator: { " \t\n\r".contains($0) }).joined(separator: " ")
1255 // Only the link types Org knows, in any case, have a scheme; `foo:bar` is a fuzzy link.
1256 // Only `id` in lower case is an ID link; `ID:x` and `DOI:x` are written as they are.
1257 let scheme = linkType.map { $0.lowercased() }.flatMap { Self.externalTypes.contains($0) || Self.unrenderedTypes.contains($0) || $0 == "id" ? $0 : nil }
1258 if raw.hasPrefix("(") && raw.hasSuffix(")") {
1259 let path = String(raw.dropFirst().dropLast())
1260 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
1261 var format = description ?? "%s"
1262 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1263 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1264 }
1265 let internalLink = raw.hasPrefix("#") || linkType == "id" || (scheme == nil && !raw.hasPrefix("/") && !raw.hasPrefix("./") && !raw.hasPrefix("../") && !raw.hasPrefix("~"))
1266 if internalLink {
1267 let type = raw.hasPrefix("#") ? "custom-id" : linkType == "id" ? "id" : "fuzzy"
1268 let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw
1269 if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) {
1270 throw Unsupported(reason: "Links to targets and named elements")
1271 }
1272 guard let heading = resolveHeading(type: type, path: path) else {
1273 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
1274 }
1275 let reference = try describeHeading(heading)
1276 if let description {
1277 let see = try seeSection(reference)
1278 if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(see)" : nil)) }
1279 return linksToNotes ? "[\(description)]" : "[\(description)] (\(see))"
1280 }
1281 if noting { noted.append(Noted(footprint: footprint, note: nil)) }
1282 return reference
1283 }
1284 if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) }
1285 return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>"
1286 }
1287
1288 /// A heading as a link without a description writes it: its number, else its title.
1289 private func describeHeading(_ heading: HeadingInfo) throws -> String {
1290 let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".")
1291 let text: String
1292 if let number {
1293 text = number
1294 } else {
1295 guard let node = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }) else { return "" }
1296 let saved = noting
1297 noting = false
1298 defer { noting = saved }
1299 text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? ""
1300 }
1301 return text
1302 }
1303
1304 /// `org-ascii--describe-datum` for a heading `reference` names.
1305 private func seeSection(_ reference: String) throws -> String {
1306 // In notes, `describeLinks` checks the width.
1307 let format = linksToNotes ? translate("See section %s") : try translateFilled("See section %s")
1308 // Emacs's `format` stops at `%d` given a string (Slovenian).
1309 if format.contains("%d") { throw Unsupported(reason: "Format specifier doesn't match argument type") }
1310 return format.replacingOccurrences(of: "%s", with: reference)
1311 }
1312
1313 /// Whether a `<<target>>` has the name a fuzzy link gives.
1314 private func target(_ path: String) -> Bool {
1315 let search = LaTeXRenderer.words(path)
1316 return tree.root.descendants().contains { $0.kind == .target && LaTeXRenderer.words(String($0.text.dropFirst(2).dropLast(2))) == search }
1317 }
1318
1319 /// Whether an element has the `#+NAME` a fuzzy link gives.
1320 private func namedElement(_ path: String) -> Bool {
1321 let search = path.split(whereSeparator: \.isWhitespace).map(String.init)
1322 return tree.root.descendants().contains { node in
1323 guard node.kind == .affiliatedKeyword, let m = node.text.firstMatch(of: /^[ \t]*#\+(?i:name):[ \t]*(.*?)[ \t]*\n?$/) else { return false }
1324 let words = String(m.1).split(whereSeparator: \.isWhitespace).map(String.init)
1325 return words == search || words == search.map { $0.uppercased() }
1326 }
1327 }
1328
1329 /// The exported heading a link goes to: by `CUSTOM_ID`, `ID` or title.
1330 private func resolveHeading(type: String, path: String) -> HeadingInfo? {
1331 let starts = Set(exported.map(\.start))
1332 let headings = model.headings.filter { starts.contains($0.headingRange.lowerBound) }
1333 switch type {
1334 case "custom-id":
1335 return headings.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == path } }
1336 case "id":
1337 return headings.first { $0.properties.contains { $0.key.uppercased() == "ID" && $0.value == path } }
1338 default:
1339 let search = LaTeXRenderer.words(path.hasPrefix("*") ? String(path.dropFirst()) : path)
1340 return headings.first { heading in
1341 let node = tree.root.descendants().first { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }
1342 let raw = (node?.firstChild(.title)?.text ?? "").replacing(#/\[[0-9]*(?:%|/[0-9]*)\]/#, with: " ")
1343 return LaTeXRenderer.words(raw) == search
1344 }
1345 }
1346 }
1347
1348 // MARK: Footnotes
1349
1350 /// Footnote numbers by label, in the order of first references.
1351 private var footnoteNumbers: [String: Int] = [:]
1352 /// What each number's footnote says: a definition's label, or an inline definition.
1353 private var footnoteOrder: [(label: String?, inline: String?)] = []
1354 private var inFootnote = false
1355
1356 /// `org-ascii-footnote-reference`.
1357 private func footnoteReference(_ node: SyntaxNode) throws -> String {
1358 guard let m = node.text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { throw Unsupported(reason: "Footnote \(node.text)") }
1359 if inFootnote { throw Unsupported(reason: "Footnotes inside footnotes") }
1360 let label = String(m.1)
1361 if !label.isEmpty, let number = footnoteNumbers[label] { return "[\(number)]" }
1362 if m.2 == nil, label.isEmpty || definition(label) == nil { throw Unsupported(reason: "Definition not found for footnote \(label)") }
1363 footnoteOrder.append((label.isEmpty ? nil : label, m.2.map(String.init)))
1364 if !label.isEmpty { footnoteNumbers[label] = footnoteOrder.count }
1365 return "[\(footnoteOrder.count)]"
1366 }
1367
1368 /// The definition of `label` and the text width where it is.
1369 private func definition(_ label: String) -> (text: String, width: Int)? {
1370 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
1371 guard let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/), m.1 == label else { continue }
1372 var width = Self.textWidth
1373 var current = node.parent
1374 while let n = current {
1375 if n.kind == .section, let heading = n.firstChild(.heading) {
1376 let level = self.level(heading)
1377 width -= level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin
1378 break
1379 }
1380 current = n.parent
1381 }
1382 if excluded(node) { return nil }
1383 return (String(node.text[m.range.upperBound...]), width)
1384 }
1385 return nil
1386 }
1387
1388 /// The footnote definitions, as `org-ascii-inner-template` writes them.
1389 private func footnotes() throws -> String {
1390 linksToNotes = false
1391 inFootnote = true
1392 defer {
1393 linksToNotes = true
1394 inFootnote = false
1395 }
1396 var parts: [String] = []
1397 for (index, footnote) in footnoteOrder.enumerated() {
1398 let id = "[\(index + 1)] "
1399 if let inline = footnote.inline {
1400 parts.append(LaTeXRenderer.trim(ASCIIText.fill(id + (try inlineObjects(inline)), width: Self.textWidth)))
1401 continue
1402 }
1403 guard let label = footnote.label, let (text, width) = definition(label) else { continue }
1404 let tree = OrgParser.parse(text, defaults: settings)
1405 let nodes = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
1406 let saved = (currentSource, exportSource)
1407 currentSource = text as NSString
1408 exportSource = ExportSource(tree: tree, text: text)
1409 defer { (currentSource, exportSource) = saved }
1410 let context = Context(width: width)
1411 if let first = nodes.first, first.kind == .paragraph {
1412 var out = Self.normalize(try paragraph(first, context: context, ignoreFirst: true, prefix: id))
1413 out += String(repeating: "\n", count: blankLines(from: first.range.lowerBound, to: nodes.count > 1 ? nodes[1].range.lowerBound : (text as NSString).length))
1414 out += try elements(Array(nodes.dropFirst()), end: (text as NSString).length, context: context)
1415 parts.append(LaTeXRenderer.trim(out))
1416 } else {
1417 parts.append(LaTeXRenderer.trim(id + "\n" + (try elements(nodes, end: (text as NSString).length, context: context))))
1418 }
1419 }
1420 return parts.joined(separator: "\n\n")
1421 }
1422
1423 /// An inline definition's objects transcoded.
1424 private func inlineObjects(_ text: String) throws -> String {
1425 let tree = OrgParser.parse(text, defaults: settings)
1426 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return plainText(text) }
1427 return try transcode(inlineItems(paragraph))
1428 }
1429}
Sources/OrgCore/Export/ASCIIText.swift +42 −5
@@ -118,17 +118,54 @@ struct ASCIIText {
118 118
119 static let hardNewline = "\u{1}" 119 static let hardNewline = "\u{1}"
120 120
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
121 static func fillParagraph(_ text: String, width: Int) -> String { 160 static func fillParagraph(_ text: String, width: Int) -> String {
122 var lines = text.components(separatedBy: "\n") 161 var lines = text.components(separatedBy: "\n")
123 while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() } 162 while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() }
124 guard !lines.isEmpty else { return "" } 163 guard !lines.isEmpty else { return "" }
125 func indentation(_ line: String) -> String { String(line.prefix { $0 == " " || $0 == "\t" }) } 164 let prefix = fillPrefix(lines)
126 let first = indentation(lines[0]) 165 let first = String(lines[0].prefix(deletedPrefix(lines[0], prefix)))
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
129 var parts: [String] = [] 166 var parts: [String] = []
130 for (i, line) in lines.enumerated() { 167 for (i, line) in lines.enumerated() {
131 var content = String(line.dropFirst(indentation(line).count)) 168 var content = String(line.dropFirst(deletedPrefix(line, prefix)))
132 while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() } 169 while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() }
133 // A sentence ending a line gets the second space it would have. 170 // A sentence ending a line gets the second space it would have.
134 if i < lines.count - 1, content.range(of: "[.?!…‽][]\"'”’)}»›]*$", options: .regularExpression) != nil { content += " " } 171 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
4/// org-clock.el `org-clock-clocktable-language-setup`, Org 9.8.7), for `#+LANGUAGE` and 4/// org-clock.el `org-clock-clocktable-language-setup`, Org 9.8.7), for `#+LANGUAGE` and
5/// `org-export-default-language`. 5/// `org-export-default-language`.
6public enum ExportDictionary { 6public 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 }
8 8
9 /// `org-export-translate`: the encoding's translation, else the language's default, else `term`. 9 /// `org-export-translate`: the encoding's translation, else the language's default, else `term`.
10 public static func translate(_ term: String, language: String, encoding: Encoding) -> String { 10 public static func translate(_ term: String, language: String, encoding: Encoding) -> String {
@@ -110,6 +110,192 @@ public enum ExportDictionary {
110 "zh-CN": ["html": "&#33050;&#27880;", "utf-8": "脚注"], 110 "zh-CN": ["html": "&#33050;&#27880;", "utf-8": "脚注"],
111 "zh-TW": ["html": "&#33139;&#35387;", "utf-8": "腳註"], 111 "zh-TW": ["html": "&#33139;&#35387;", "utf-8": "腳註"],
112 ], 112 ],
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 ],
113 ] 299 ]
114 300
115 static let clockTable: [String: [String]] = [ 301 static let clockTable: [String: [String]] = [
Sources/OrgCore/Export/LaTeXExport.swift +13 −8
@@ -44,6 +44,18 @@ public enum LaTeXExport {
44 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false, 44 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false,
45 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false 45 author: String = "", language: String = "en", timeZone: TimeZone = .current, file: Bool = false
46 ) throws -> String { 46 ) 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 {
47 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() } 59 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
48 let included = ExportPreprocess.includes(text, directory: directory) 60 let included = ExportPreprocess.includes(text, directory: directory)
49 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays. 61 // Org expands macro objects only: `{{{…}}}` in verbatim text and blocks stays.
@@ -63,14 +75,7 @@ public enum LaTeXExport {
63 } 75 }
64 literal = out + ns.substring(from: at) 76 literal = out + ns.substring(from: at)
65 } 77 }
66 let text = ExportPreprocess.macros(literal, path: path, now: now, setup: settings.setupKeywords).replacingOccurrences(of: marker, with: "{") 78 return 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
74 } 79 }
75} 80}
76 81
Sources/OrgCore/Parser/Inline.swift +3 −2
@@ -534,9 +534,10 @@ struct InlineScanner {
534 return hasPrefix("}}}", at: j, limit) ? j + 3 : nil 534 return hasPrefix("}}}", at: j, limit) ? j + 3 : nil
535 } 535 }
536 536
537 /// `\\` at the end of a line, before optional trailing blanks. The line break stays outside. 537 /// `\\` at the end of a line, before optional trailing blanks, not after another `\`. The
538 /// line break stays outside.
538 func lineBreak(_ i: Int, _ limit: Int) -> Int? { 539 func lineBreak(_ i: Int, _ limit: Int) -> Int? {
539 guard hasPrefix("\\\\", at: i, limit) else { return nil } 540 guard hasPrefix("\\\\", at: i, limit), i == 0 || chars[i - 1] != "\\" else { return nil }
540 var j = i + 2 541 var j = i + 2
541 while j < limit, chars[j] == " " || chars[j] == "\t" { j += 1 } 542 while j < limit, chars[j] == " " || chars[j] == "\t" { j += 1 }
542 if j + 1 < limit, chars[j] == "\r", chars[j + 1] == "\n" { return j } 543 if j + 1 < limit, chars[j] == "\r", chars[j + 1] == "\n" { return j }
Sources/OrgCore/Semantic/OrgEntities.swift +417
@@ -833,4 +833,421 @@ enum OrgEntities {
833 "_ ": ("\\hspace*{9.5em}", false), 833 "_ ": ("\\hspace*{9.5em}", false),
834 "_ ": ("\\hspace*{10.0em}", false), 834 "_ ": ("\\hspace*{10.0em}", false),
835 ] 835 ]
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 ]
836} 1253}
Sources/OrgEditorAppKit/EditorCommands.swift +1 −1
@@ -176,7 +176,7 @@ public enum EditorCommands {
176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app), 176 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
177 EditorCommand(id: "app.export.odt", title: "Export to ODT", action: .app), 177 EditorCommand(id: "app.export.odt", title: "Export to ODT", action: .app),
178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app), 178 EditorCommand(id: "app.export.latex", title: "Export to LaTeX", action: .app),
179 EditorCommand(id: "app.export.text", title: "Export to Plain Text with Emacs", action: .app), 179 EditorCommand(id: "app.export.text", title: "Export to Plain Text (ASCII)", action: .app),
180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app), 180 EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app),
181 EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app), 181 EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app),
182 EditorCommand(id: "app.export.icalendar-combined", title: "Combine Agenda Files into iCalendar", action: .app), 182 EditorCommand(id: "app.export.icalendar-combined", title: "Combine Agenda Files into iCalendar", action: .app),
Sources/Orgstar/ContentView.swift +23 −7
@@ -628,7 +628,13 @@ struct ContentView: View {
628 } catch { 628 } catch {
629 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)") 629 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
630 } 630 }
631 case "latex" where exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults): 631 case "latex" where exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
632 try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
633 }):
634 break
635 case "text" where exportNative("plain text", extension: "txt", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
636 try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
637 }):
632 break 638 break
633 case "odt": 639 case "odt":
634 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults) 640 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
@@ -705,21 +711,24 @@ struct ContentView: View {
705 } 711 }
706 } 712 }
707 713
708 /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs 714 /// Writes what `export` makes, as ox does for `format`. False when the native export can't
709 /// and Emacs is installed to export instead; otherwise the reason is shown. 715 /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
710 private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool { 716 private func exportNative(
717 _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, settings: OrgSettings,
718 export: () throws -> String
719 ) -> Bool {
711 let content: String 720 let content: String
712 do { 721 do {
713 content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true) 722 content = try export()
714 } catch { 723 } catch {
715 #if !APPSTORE 724 #if !APPSTORE
716 if EmacsRunner.executable() != nil { return false } 725 if EmacsRunner.executable() != nil { return false }
717 #endif 726 #endif
718 commands.show("Can't export to LaTeX: \(error.localizedDescription)") 727 commands.show("Can't export to \(format): \(error.localizedDescription)")
719 return true 728 return true
720 } 729 }
721 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings) 730 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
722 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true } 731 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
723 do { 732 do {
724 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) 733 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
725 try content.write(to: target, atomically: true, encoding: .utf8) 734 try content.write(to: target, atomically: true, encoding: .utf8)
@@ -1002,6 +1011,13 @@ struct ContentView: View {
1002 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)") 1011 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)")
1003 } 1012 }
1004 } 1013 }
1014 if function == "org-ascii-publish-to-ascii" {
1015 do {
1016 return try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
1017 } catch let error as ASCIIExport.Unsupported {
1018 throw ASCIIExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to plain text: \(error.reason)")
1019 }
1020 }
1005 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension 1021 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
1006 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage()) 1022 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
1007 } 1023 }
Sources/Orgstar/ExportSheet.swift +2 −2
@@ -25,13 +25,13 @@ struct ExportSheet: View {
25 static let formats: [(id: String, title: String, ext: String)] = [ 25 static let formats: [(id: String, title: String, ext: String)] = [
26 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), 26 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
27 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("odt", "ODT", "odt"), 27 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("odt", "ODT", "odt"),
28 ("icalendar", "iCalendar", "ics"), ("latex", "LaTeX", "tex"), 28 ("icalendar", "iCalendar", "ics"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII", "txt"),
29 ] 29 ]
30 #else 30 #else
31 static let formats: [(id: String, title: String, ext: String)] = [ 31 static let formats: [(id: String, title: String, ext: String)] = [
32 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), 32 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
33 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"), 33 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
34 ("odt", "ODT", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"), 34 ("odt", "ODT", "odt"), ("latex", "LaTeX", "tex"), ("text", "Plain text, ASCII", "txt"),
35 ("icalendar", "iCalendar", "ics"), 35 ("icalendar", "iCalendar", "ics"),
36 ] 36 ]
37 #endif 37 #endif
Sources/OrgstarMobile/ExportMenu.swift +20 −6
@@ -6,12 +6,12 @@ import OrgPresentation
6import SwiftUI 6import SwiftUI
7import UniformTypeIdentifiers 7import UniformTypeIdentifiers
8 8
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX, written 9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII,
10/// when the share sheet takes it. 10/// written when the share sheet takes it.
11struct OrgExport: Transferable { 11struct OrgExport: Transferable {
12 enum Format: CaseIterable { 12 enum Format: CaseIterable {
13 case html, markdown, pdf, docx, rtf, plainText, odt, icalendar 13 case html, markdown, pdf, docx, rtf, plainText, odt, icalendar
14 case latex 14 case latex, ascii
15 15
16 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked. 16 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
17 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked } 17 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
@@ -27,6 +27,7 @@ struct OrgExport: Transferable {
27 case .odt: "ODT" 27 case .odt: "ODT"
28 case .icalendar: "iCalendar" 28 case .icalendar: "iCalendar"
29 case .latex: "LaTeX" 29 case .latex: "LaTeX"
30 case .ascii: "Plain Text (ASCII)"
30 } 31 }
31 } 32 }
32 33
@@ -41,6 +42,7 @@ struct OrgExport: Transferable {
41 case .odt: "odt" 42 case .odt: "odt"
42 case .icalendar: "ics" 43 case .icalendar: "ics"
43 case .latex: "tex" 44 case .latex: "tex"
45 case .ascii: "txt"
44 } 46 }
45 } 47 }
46 } 48 }
@@ -62,8 +64,8 @@ struct OrgExport: Transferable {
62 .lastPathComponent 64 .lastPathComponent
63 } 65 }
64 66
65 /// Posted with the message, for the screen's message line, when the LaTeX export refuses 67 /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
66 /// the file: the share sheet shows no reason. 68 /// refuses the file: the share sheet shows no reason.
67 static let refused = Notification.Name("OrgExportRefused") 69 static let refused = Notification.Name("OrgExportRefused")
68 70
69 static var transferRepresentation: some TransferRepresentation { 71 static var transferRepresentation: some TransferRepresentation {
@@ -85,6 +87,8 @@ struct OrgExport: Transferable {
85 .exportingCondition { $0.format == .icalendar } 87 .exportingCondition { $0.format == .icalendar }
86 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() } 88 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
87 .exportingCondition { $0.format == .latex } 89 .exportingCondition { $0.format == .latex }
90 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
91 .exportingCondition { $0.format == .ascii }
88 } 92 }
89 93
90 private func write() async throws -> SentTransferredFile { 94 private func write() async throws -> SentTransferredFile {
@@ -110,6 +114,16 @@ struct OrgExport: Transferable {
110 throw error 114 throw error
111 } 115 }
112 try content.write(to: url, atomically: true, encoding: .utf8) 116 try content.write(to: url, atomically: true, encoding: .utf8)
117 case .ascii:
118 let content: String
119 do {
120 content = try ASCIIExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
121 } catch let error as ASCIIExport.Unsupported {
122 let message = "Can't export to plain text: \(error.reason)"
123 await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
124 throw error
125 }
126 try content.write(to: url, atomically: true, encoding: .utf8)
113 case .odt: 127 case .odt:
114 try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage()) 128 try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
115 .write(to: url, options: .atomic) 129 .write(to: url, options: .atomic)
@@ -133,7 +147,7 @@ struct OrgExport: Transferable {
133 } 147 }
134} 148}
135 149
136/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX: to another app, or saved with 150/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII: to another app, or saved with
137/// Save to Files; or copying it as rich text. 151/// Save to Files; or copying it as rich text.
138struct ExportMenu: View { 152struct ExportMenu: View {
139 let path: String 153 let path: String
Tests/OrgAppTests/PublishTests.swift +50
@@ -195,6 +195,56 @@ struct PublishTests {
195 } 195 }
196 } 196 }
197 197
198 /// `org-ascii-publish-to-ascii`: the same `.txt` files as Emacs writes.
199 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
200 func publishesASCIILikeOrg() throws {
201 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-txt-\(UUID().uuidString)").resolvingSymlinksInPath()
202 defer { try? FileManager.default.removeItem(at: folder) }
203 let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n| x | y |\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
204 for (path, text) in sources {
205 let url = folder.appendingPathComponent("src/" + path)
206 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
207 try text.write(to: url, atomically: true, encoding: .utf8)
208 }
209 let form = """
210 (progn
211 (require 'ox-publish) (require 'ox-ascii)
212 (setq user-full-name "A. Writer"
213 org-publish-timestamp-directory "\(folder.path)/ts/"
214 org-publish-project-alist '(("txt" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
215 :recursive t :publishing-function org-ascii-publish-to-ascii)))
216 (org-publish "txt" t))
217 """
218 let process = Process()
219 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
220 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
221 process.standardOutput = FileHandle.nullDevice
222 process.standardError = FileHandle.nullDevice
223 try process.run()
224 process.waitUntilExit()
225
226 let toml = """
227 [[publish]]
228 name = "txt"
229 base-directory = "\(folder.path)/src"
230 publishing-directory = "\(folder.path)/ours"
231 recursive = true
232 publishing-function = "org-ascii-publish-to-ascii"
233 """
234 let loaded = Publish.projects(fromConfig: toml, root: nil)
235 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
236 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
237 let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
238 try ASCIIExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
239 }
240 #expect(report.published.count == 2)
241 for path in ["a.txt", "sub/b.txt"] {
242 let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
243 let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
244 #expect(ours == theirs, "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
245 }
246 }
247
198 /// `org-odt-publish-to-odt` writes `.odt` files, which the export closure doesn't see. 248 /// `org-odt-publish-to-odt` writes `.odt` files, which the export closure doesn't see.
199 @Test func publishesODT() throws { 249 @Test func publishesODT() throws {
200 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)") 250 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)")
Tests/OrgCoreTests/ASCIIExportTests.swift added +392
@@ -0,0 +1,392 @@
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 "Quoted mail:\n> first line of the quote that goes on long enough to need a second line\n> second line\n",
179 "-- a dash opens this paragraph which goes on long enough to need a second line of text.\n",
180 "| a | b | c |\n| 1 |\n| 2 | 3 |\n",
181 "- [X] term :: with a checkbox\n- plain :: def\n",
182 "#+begin_quote\n#+begin_quote\nInner quote that goes on long enough to need filling at the narrower width.\n#+end_quote\n#+end_quote\n",
183 "- - nested first\n - second\n- after\n",
184 "- line one\\\\\n line two\n\n#+begin_quote\nq one\\\\\nq two\n#+end_quote\n",
185 "#+OPTIONS: H:1\n* A\n** B\n*** C\n**** D\n***** E\ntext under E that is long enough to be filled at the narrower width of it.\n",
186 "#+OPTIONS: num:nil\n* /Styled/ title\n* Other\nSee [[*/Styled/ title][it]] and [[*/Styled/ title]].\n",
187 "* A\n:PROPERTIES:\n:CUSTOM_ID: a\n:END:\n* B\nNote.[fn:1]\n\n[fn:1] See [[#a][A]] and [[https://x.y][X]].\n",
188 "#+OPTIONS: <:nil\n<2024-01-15 Mon>\n\nText <2024-01-15 Mon> kept.\n",
189 "#+OPTIONS: stat:t\n* Tasks [1/2]\n- [X] a\n- [ ] b\n",
190 "Averyveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongword and more.\n",
191 "\n",
192 "#+TITLE: Only a title\n",
193 "#+begin_center\n#+ASCII: raw\n\\begin{x}\ny\n\\end{x}\n#+end_center\n",
194 "#+begin_justifyright\nlower\n#+end_justifyright\n",
195 "* A\n- item\n [fn:1]\n\n#+begin_quote\nq[fn:2]\n#+end_quote\n\n[fn:1] One.\n\n[fn:2] Two.\n",
196 "#+OPTIONS: H:2\n* A\n** B\n*** C\n#+TOC: headlines\n",
197 "#+OPTIONS: toc:1\n* A\n** B\n* C [[https://a.b][link]]\n",
198 "- a\n # comment\n b\n- c\n\n # comment\n\n d\n- # only\n e\n",
199 "* Tasks [1/3] [33%]\n** DONE One\nCLOSED: [2024-01-01 Mon 10:00]\n** TODO Two\n** Three\n",
200 "Some *bold\ntext* across /lines of\nitalic/ text.\n",
201 "#+begin_src emacs-lisp\n(message \"hi\")\n#+end_src\n\n#+begin_src python :exports code\nprint(1)\n#+end_src\n",
202 "Para.\n\n\n\nAfter three blank lines.\n\n- item\n\n\n- item after two\n",
203 "* A\n\n\nBody after blanks.\n\n\n* B\n",
204 "1. one\n\n para\n\n #+begin_example\n ex\n #+end_example\n2. two\n",
205 "- a\n | x | y |\n |---+---|\n | 1 | 2 |\n- b\n",
206 "#+TITLE: T\n#+AUTHOR: A\n#+DATE: <2024-01-02 Tue>\n#+OPTIONS: toc:nil\nx\n",
207 "#+AUTHOR: Just an author\n#+DATE: 2024-01-02\nx\n",
208 "#+DATE: 2024-01-02\nx\n",
209 "#+begin_src makefile\nall: x\n\tcc -o x x.c\n#+end_src\n",
210 "#+begin_src makefile -n -r\nall: x\n \t\tcc\tx (ref:a)\n#+end_src\n\n#+begin_example\nall: x\n\tcc\n#+end_example\n",
211 "#+LANGUAGE: ja\n#+OPTIONS: toc:nil\n* A\nx[fn:1]\n\n[fn:1] n\n",
212 "#+LANGUAGE: zh-CN\n* A\nx\n",
213 "Types [[DOI:10.1/z][d]] [[Attachment:x.png]] [[ID:x]] [[INFO:emacs][i]] b_doi:10.1/x.\n",
214 "#+LANGUAGE: ja\n* A\nSee [[*B][b]].\n* B\ny\n",
215 "#+LANGUAGE: zh-CN\n* A\nSee [[*B][b]].\n* B\ny\n",
216 "#+LANGUAGE: ja\n* A\nSee [[*B][\(String(repeating: "b", count: 72))]].\n* B\ny\n",
217 "Text doi:- here, doi:a. and b.\n",
218 "x HTTPS://x.y/z and mailto:a@b.c and File:a.txt. FILE:foo-- \"q\" FILE:a(b) Mailto:a@b, y\n",
219 "a\\\\\\\\\nb\n\nc\\\\\\\\\\\\ \nd\n\ne\\\\\nf\n",
220 "#+OPTIONS: e:t\n\\alpha\\beta \\ast{} \\S \\para \\deg \\plusmn \\micro \\middot \\cedil \\ordf \\iexcl \\pound \\yen \\euro \\trade\n",
221 ]
222
223 static var cases: [(String, ASCIIOracle.Case)] {
224 var cases: [(String, ASCIIOracle.Case)] = []
225 for charset in ASCIIExport.Charset.allCases {
226 for name in corpus {
227 let text = (try? String(contentsOf: folder.appendingPathComponent("\(name).org"), encoding: .utf8)) ?? ""
228 cases.append(("\(name) \(charset.rawValue)", ASCIIOracle.Case(text: text, charset: charset)))
229 }
230 for (index, snippet) in (snippets + extra).enumerated() {
231 cases.append(("snippet \(index) \(charset.rawValue)", ASCIIOracle.Case(text: snippet, charset: charset)))
232 }
233 }
234 return cases
235 }
236
237 @Test(.enabled(if: oracle))
238 func matchesEmacs() throws {
239 let all = Self.cases
240 try compare(all.map(\.1), names: all.map(\.0))
241 }
242
243 @Test(.enabled(if: oracle))
244 func bodyOnlyAndSubtreesMatchEmacs() throws {
245 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"
246 let sub = (doc as NSString).range(of: "** Sub").location
247 let one = (doc as NSString).range(of: "First.").location
248 var cases: [ASCIIOracle.Case] = []
249 var names: [String] = []
250 for charset in ASCIIExport.Charset.allCases {
251 cases += [
252 ASCIIOracle.Case(text: doc, charset: charset, bodyOnly: true),
253 ASCIIOracle.Case(text: try String(contentsOf: Self.folder.appendingPathComponent("blocks.org"), encoding: .utf8), charset: charset, bodyOnly: true),
254 ASCIIOracle.Case(text: doc, charset: charset, subtree: EmacsOracle.point(sub, in: doc)),
255 ASCIIOracle.Case(text: doc, charset: charset, subtree: EmacsOracle.point(one, in: doc)),
256 ASCIIOracle.Case(text: doc, charset: charset, bodyOnly: true, subtree: EmacsOracle.point(sub, in: doc)),
257 ]
258 names += ["body", "blocks body", "subtree", "subtree from body", "subtree body"].map { "\($0) \(charset.rawValue)" }
259 }
260 try compare(cases, names: names)
261 }
262
263 /// A subtree's `EXPORT_*` properties replace the file's keywords.
264 @Test(.enabled(if: oracle))
265 func subtreePropertiesMatchEmacs() throws {
266 let doc = """
267 #+TITLE: Doc
268 #+SUBTITLE: File sub
269 #+AUTHOR: File author
270 #+LANGUAGE: fr
271 #+EXCLUDE_TAGS: drop
272 * Top
273 :PROPERTIES:
274 :EXPORT_SUBTITLE: Sub
275 :EXPORT_AUTHOR: Someone
276 :EXPORT_DATE: 2024-05-06
277 :EXPORT_LANGUAGE: de
278 :EXPORT_EXCLUDE_TAGS: gone
279 :EXPORT_OPTIONS: toc:nil
280 :END:
281 Body[fn:1].
282 ** Child
283 x
284 ** Dropped :gone:
285 z
286 ** Kept :drop:
287 w
288
289 [fn:1] Note.
290
291 """
292 let top = (doc as NSString).range(of: "Body").location
293 let cases = ASCIIExport.Charset.allCases.map { ASCIIOracle.Case(text: doc, charset: $0, subtree: EmacsOracle.point(top, in: doc)) }
294 try compare(cases, names: ASCIIExport.Charset.allCases.map { "subtree properties \($0.rawValue)" })
295 }
296
297 /// Links to what the export leaves out stop both exports.
298 @Test(.enabled(if: oracle))
299 func abortsWhereEmacsAborts() throws {
300 let docs = [
301 "* A :noexport:\n* B\nSee [[*A]].\n",
302 "* A :noexport:\n:PROPERTIES:\n:CUSTOM_ID: a\n:END:\n* B\nSee [[#a]].\n",
303 "* COMMENT A\n* B\nSee [[*A]].\n",
304 "See [[nowhere]].\n",
305 "See [[id:nowhere]].\n",
306 "#+OPTIONS: num:nil\n* /Styled/ title\nSee [[*Styled title]].\n",
307 ]
308 let emacs = try ASCIIOracle.export(docs.map { ASCIIOracle.Case(text: $0) })
309 for (doc, theirs) in zip(docs, emacs) {
310 let ours = ASCIIOracle.native(ASCIIOracle.Case(text: doc))
311 #expect(theirs.hasPrefix("ERROR: "), "\(doc)\n--- emacs\n\(theirs)")
312 #expect(ours.hasPrefix("ERROR: Unable to resolve link"), "\(doc)\n--- ours\n\(ours)")
313 }
314 }
315
316 /// Slovenian's "See section %d" stops Emacs's `format` when given a section.
317 @Test(.enabled(if: oracle))
318 func abortsOnSlovenianSectionReference() throws {
319 let cases = ASCIIExport.Charset.allCases.map { ASCIIOracle.Case(text: "#+LANGUAGE: sl\n* A\nSee [[*B][b]].\n* B\ny\n", charset: $0) }
320 for (c, theirs) in zip(cases, try ASCIIOracle.export(cases)) {
321 #expect(theirs == "ERROR: Format specifier doesn’t match argument type" || theirs == "ERROR: Format specifier doesn't match argument type", "\(theirs)")
322 #expect(ASCIIOracle.native(c) == "ERROR: Format specifier doesn't match argument type")
323 }
324 }
325
326 /// What Emacs exports differently or refuses is refused, naming it.
327 @Test func refusesWhatItCannotMatch() {
328 func reason(_ org: String) -> String? {
329 do {
330 _ = try ASCIIExport.document(org)
331 return nil
332 } catch let error as ASCIIExport.Unsupported {
333 return error.reason
334 } catch {
335 return "\(error)"
336 }
337 }
338 #expect(reason("Ref[fn:9].\n") == "Definition not found for footnote 9")
339 #expect(reason("#+OPTIONS: \\n:t\nx\n") == "#+OPTIONS: \\n:t")
340 #expect(reason("#+OPTIONS: tex:verbatim\nx\n") == "#+OPTIONS: tex:verbatim")
341 #expect(reason("#+begin_src sh :exports results\necho\n#+end_src\n") == ":exports results")
342 #expect(reason("[cite:@key]\n") == "Citations")
343 #expect(reason("src_sh{echo 1}\n") == "Inline source blocks")
344 #expect(reason("A <<here>> target.\nSee [[here]].\n") == "Links to targets and named elements")
345 #expect(reason("#+NAME: t\n| a |\nSee [[t]].\n") == "Links to targets and named elements")
346 #expect(reason("| / | < | > |\n| | a | b |\n") == "Tables with special columns or column groups")
347 #expect(reason("Text[fn:1].\n\n[fn:1] One.\n\nTwo.\n") == "Footnote definitions of several paragraphs")
348 #expect(reason("漢字\n") == "Wide or combining characters")
349 #expect(reason("a\tb\n") == "Tabs outside code")
350 #expect(reason("#+begin_src make\n\tcc\n#+end_src\n") == "Tabs in indented code")
351 #expect(reason("#+TOC: tables\n") == "#+TOC: tables")
352 #expect(reason("-\n- x\n") == "Empty list items")
353 #expect(reason("* A\n:PROPERTIES:\n:UNNUMBERED: t\n:END:\n") == "UNNUMBERED and ALT_TITLE properties")
354 #expect(reason("* A [fn:1]\n\n[fn:1] x\n") == "Footnotes in headings")
355 #expect(reason("#+begin_quote\n\nq\n#+end_quote\n") == "Blocks opening with a blank line")
356 #expect(reason("Plain doi:10.1/z here.\n") == "Plain links of type doi")
357 #expect(reason("Plain info:emacs#Top\n") == "Plain links of type info")
358 #expect(reason("Run shell:ls and elisp:foo.\n") == "Plain links of type shell")
359 #expect(reason("<irc:/irc.x/chan>\n") == "Plain links of type irc")
360 #expect(reason("| docview:a.pdf |\n") == "Plain links of type docview")
361 #expect(reason("[[doi:10.1/z][d]]\n") == "Links of type doi")
362 #expect(reason("[[attachment:x.png]]\n") == "Links of type attachment")
363 #expect(reason("<info:emacs#Top>\n") == "Links of type info")
364 #expect(reason("Case DOI:10.1/z.\n") == "Plain links of type DOI")
365 #expect(reason("#+LANGUAGE: ja\n#+CAPTION: c\n| a |\n") == "Wide or combining characters")
366 #expect(reason("#+LANGUAGE: ja\n* A\nSee [[*B][\(String(repeating: "b", count: 56))]].\n* B\n") == "Wide or combining characters")
367 #expect(reason("#+LANGUAGE: ja\nx[fn:1]\n* B\n\n[fn:1] See [[*B][b]].\n") == "Wide or combining characters")
368 #expect(reason("Text doi:- here.\n") == nil)
369 #expect(reason("Plain FILE:foo.txt and HTTPS://x.y here.\n") == nil)
370 #expect(reason("Plain FILE:foo.txt and SHELL:ls here.\n") == "Plain links of type SHELL")
371 #expect(reason("#+LANGUAGE: sl\n* A\nSee [[*B][b]].\n* B\n") == "Format specifier doesn't match argument type")
372 #expect(reason("#+LANGUAGE: sl\n* A\nSee [[*B]].\n* B\n") == nil)
373 }
374
375 private func compare(_ cases: [ASCIIOracle.Case], names: [String]) throws {
376 let emacs = try ASCIIOracle.export(cases)
377 for (index, c) in cases.enumerated() {
378 let ours = ASCIIOracle.native(c)
379 if ours.hasPrefix("ERROR: ") {
380 Issue.record("\(names[index]) unsupported: \(ours)\n--- org\n\(c.text)")
381 continue
382 }
383 if let dump = ProcessInfo.processInfo.environment["ASCII_DUMP"], ours != emacs[index] {
384 let name = names[index].replacingOccurrences(of: " ", with: "_")
385 try? ours.write(toFile: dump + "/" + name + ".ours", atomically: true, encoding: .utf8)
386 try? emacs[index].write(toFile: dump + "/" + name + ".emacs", atomically: true, encoding: .utf8)
387 try? c.text.write(toFile: dump + "/" + name + ".org", atomically: true, encoding: .utf8)
388 }
389 #expect(ours == emacs[index], "\(names[index])\n--- org\n\(c.text)\n--- ours\n\(ours)\n--- emacs\n\(emacs[index])")
390 }
391 }
392}
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift +6
@@ -15,6 +15,12 @@ struct AppStoreCommandsTests {
15 #expect(EditorCommands.all.first { $0.id == "app.export.latex" }?.title == "Export to LaTeX") 15 #expect(EditorCommands.all.first { $0.id == "app.export.latex" }?.title == "Export to LaTeX")
16 } 16 }
17 17
18 /// ASCII export is native, so the sandboxed build has it.
19 @Test func asciiExportIsShown() {
20 #expect(!AppStoreCommands.hidden.contains("app.export.text"))
21 #expect(EditorCommands.all.first { $0.id == "app.export.text" }?.title == "Export to Plain Text (ASCII)")
22 }
23
18 @Test func pdfKeysExportThroughWebKit() throws { 24 @Test func pdfKeysExportThroughWebKit() throws {
19 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf")) 25 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf"))
20 #expect(replacement == "app.export.print-pdf") 26 #expect(replacement == "app.export.print-pdf")
docs/manual/guide/03-keys.org +1 −1
@@ -996,7 +996,7 @@ When a key appears in several rows, it runs the command whose condition holds at
996| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). | 996| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). |
997| Export to LaTeX (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX without Emacs, as =org-latex-export-to-latex= does. | 997| Export to LaTeX (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX without Emacs, as =org-latex-export-to-latex= does. |
998| Export to ODT (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to OpenDocument text without Emacs, as =org-odt-export-to-odt= does. | 998| Export to ODT (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to OpenDocument text without Emacs, as =org-odt-export-to-odt= does. |
999| Export to Plain Text with Emacs (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text through Emacs (=org-ascii-export-to-ascii=). | 999| Export to Plain Text (ASCII) (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text without Emacs, as =org-ascii-export-to-ascii= does. |
1000| Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). | 1000| Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). |
1001| Export Agenda Files to iCalendar (=app.export.icalendar-agenda=) | =C-c C-e c a= | — | — | Writes an =.ics= beside each agenda file (=org-icalendar-export-agenda-files=). | 1001| Export Agenda Files to iCalendar (=app.export.icalendar-agenda=) | =C-c C-e c a= | — | — | Writes an =.ics= beside each agenda file (=org-icalendar-export-agenda-files=). |
1002| Combine Agenda Files into iCalendar (=app.export.icalendar-combined=) | =C-c C-e c c= | — | — | Writes the agenda files' entries to one calendar (=org-icalendar-combine-agenda-files=). | 1002| Combine Agenda Files into iCalendar (=app.export.icalendar-combined=) | =C-c C-e c c= | — | — | Writes the agenda files' entries to one calendar (=org-icalendar-combine-agenda-files=). |
docs/manual/guide/12-export.org +20 −17
@@ -1,6 +1,6 @@
1#+TITLE: Export 1#+TITLE: Export
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar and LaTeX, and to ASCII through Emacs; copying as rich text. 2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX and ASCII, and to PDF through LaTeX with Emacs; copying as rich text.
3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar and LaTeX itself, and the Mac download version hands ASCII and LaTeX-made PDF to Emacs. 3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX and ASCII itself, and the Mac download version hands LaTeX-made PDF to Emacs.
4 4
5* Exporting a file 5* Exporting a file
6 6
@@ -20,7 +20,7 @@ Export works on the file in the current editor, using its text as it is now, sav
20| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes | 20| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes |
21| LaTeX | Export to LaTeX | =C-c C-e l l= | =C-c C-e l l= | no | 21| LaTeX | Export to LaTeX | =C-c C-e l l= | =C-c C-e l l= | no |
22| ODT | Export to ODT | =C-c C-e o o= | =C-c C-e o o= | no | 22| ODT | Export to ODT | =C-c C-e o o= | =C-c C-e o o= | no |
23| ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes | 23| ASCII text | Export to Plain Text (ASCII) | =C-c C-e t u= | =C-c C-e t u= | no |
24| iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no | 24| iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no |
25| iCalendar, every agenda file | Export Agenda Files to iCalendar | =C-c C-e c a= | =C-c C-e c a= | no | 25| iCalendar, every agenda file | Export Agenda Files to iCalendar | =C-c C-e c a= | =C-c C-e c a= | no |
26| iCalendar, agenda files in one | Combine Agenda Files into iCalendar | =C-c C-e c c= | =C-c C-e c c= | no | 26| iCalendar, agenda files in one | Combine Agenda Files into iCalendar | =C-c C-e c c= | =C-c C-e c c= | no |
@@ -29,15 +29,15 @@ The keys follow Emacs's export dispatcher (=org-export-dispatch=). =C-c C-e= on
29 29
30All fourteen commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.docx=, =.rtf=, =.tex=, =.odt=, =.txt= or =.ics=. The two agenda-file commands are the exceptions; see [[*iCalendar export][iCalendar export]]. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/". 30All fourteen commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.docx=, =.rtf=, =.tex=, =.odt=, =.txt= or =.ics=. The two agenda-file commands are the exceptions; see [[*iCalendar export][iCalendar export]]. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/".
31 31
32The [[file:../install.org][Mac App Store version]] has the eleven commands that don't need Emacs; File ▸ Export, the export dialog and the command palette leave out the other three, and a key bound to Export to PDF with Emacs runs Export to PDF. When the export file, or an =#+INCLUDE:= or =#+SETUPFILE:=, is outside your folders, orgstar first asks for access to its folder; for the export file, Save Elsewhere… instead picks another place. See [[file:../install.org][Install]]. 32The [[file:../install.org][Mac App Store version]] has the thirteen commands that don't need Emacs; File ▸ Export, the export dialog and the command palette leave out Export to PDF with Emacs, and a key bound to it runs Export to PDF. When the export file, or an =#+INCLUDE:= or =#+SETUPFILE:=, is outside your folders, orgstar first asks for access to its folder; for the export file, Save Elsewhere… instead picks another place. See [[file:../install.org][Install]].
33 33
34** The export dialog 34** The export dialog
35 35
36*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has: 36*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has:
37 37
38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT, LaTeX, Plain text, ASCII (Emacs) or iCalendar. The App Store version lists LaTeX last. 38- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT, LaTeX, Plain text, ASCII or iCalendar. The App Store version lists LaTeX and Plain text, ASCII last.
39- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading. 39- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. iCalendar is the exception: there the subtree's heading is an entry like any other. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading.
40- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text, ODT and iCalendar. 40- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading; ASCII has no title block or table of contents. Not available for PDF, Word, RTF, plain text, ODT and iCalendar.
41- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension. 41- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension.
42- *Margins*, *Font* and *Page numbers*, for PDF: see /PDF export/. 42- *Margins*, *Font* and *Page numbers*, for PDF: see /PDF export/.
43- *Open after export*: opens the file in its default app when the export finishes. 43- *Open after export*: opens the file in its default app when the export finishes.
@@ -46,7 +46,7 @@ The dialog remembers the format and the *Open after export* setting. The PDF set
46 46
47** On iOS 47** On iOS
48 48
49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar and LaTeX, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac, except that LaTeX and ODT have no author unless the file has =#+AUTHOR:=. ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports. 49The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar, LaTeX and Plain Text (ASCII), and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac, except that LaTeX, ODT and ASCII have no author unless the file has =#+AUTHOR:=. PDF through LaTeX is not available on iOS, nor are the agenda-file iCalendar exports.
50 50
51* HTML export 51* HTML export
52 52
@@ -242,7 +242,7 @@ Export to Word, Export to RTF and Export to Plain Text make the HTML export into
242 242
243In Word files, the title has Word's Title style and headings have its Heading 1 to Heading 6 styles, so Word's navigation pane, outline view and contents fields find them. Images from =file:= links come through as pictures, as wide as their pixels at 96 to the inch, scaled to =#+ATTR_HTML: :width= when it is set, and no wider than the page. PNG, JPEG and GIF go in as they are; other formats the system can read, such as HEIC, WebP and TIFF, go in as PNG. SVG and images at web addresses are left out. RTF and plain text have no images. 243In Word files, the title has Word's Title style and headings have its Heading 1 to Heading 6 styles, so Word's navigation pane, outline view and contents fields find them. Images from =file:= links come through as pictures, as wide as their pixels at 96 to the inch, scaled to =#+ATTR_HTML: :width= when it is set, and no wider than the page. PNG, JPEG and GIF go in as they are; other formats the system can read, such as HEIC, WebP and TIFF, go in as PNG. SVG and images at web addresses are left out. RTF and plain text have no images.
244 244
245For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. 245For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text (ASCII); see /ASCII export/.
246 246
247** Copying as rich text 247** Copying as rich text
248 248
@@ -265,6 +265,14 @@ Export to ODT writes an OpenDocument text file (=.odt=) for LibreOffice, Pages o
265 265
266The export stops with a message, instead of writing something different from ox-odt, for: a link that leads nowhere, an image file that can't be read, inline tasks, table templates (=#+ATTR_ODT: :style=), a link without a description to a =<<target>>= or to a code line that isn't numbered, an inline source block exported as code, a table in a quote or other block inside a list, an annotation in a dated document, =#+TOC:= with =:target=, and these =#+OPTIONS= at other than their default: =p=, =c=, =prop=, =broken-links=, =:=, =*=, =stat=, =tasks=, =<=, =arch=, =email=, ='=, =tex= other than =t= or =nil=, and =d= with a list of drawers. ODT export is always the whole document: the export dialog's *Body only* doesn't apply. 266The export stops with a message, instead of writing something different from ox-odt, for: a link that leads nowhere, an image file that can't be read, inline tasks, table templates (=#+ATTR_ODT: :style=), a link without a description to a =<<target>>= or to a code line that isn't numbered, an inline source block exported as code, a table in a quote or other block inside a list, an annotation in a dated document, =#+TOC:= with =:target=, and these =#+OPTIONS= at other than their default: =p=, =c=, =prop=, =broken-links=, =:=, =*=, =stat=, =tasks=, =<=, =arch=, =email=, ='=, =tex= other than =t= or =nil=, and =d= with a list of drawers. ODT export is always the whole document: the export dialog's *Body only* doesn't apply.
267 267
268* ASCII export
269
270Export to Plain Text (ASCII) writes the =.txt= file that Emacs's =org-ascii-export-to-ascii= writes under =emacs -Q= (Org 9.8.7), without Emacs, on the Mac and iOS: a centered title block, a table of contents, numbered headings underlined by level, paragraphs filled to 72 columns, links listed at the end of their section, and footnotes at the end. It uses Org's default =ascii= charset (=org-ascii-charset=), so bullets, rules and table borders are plain ASCII characters. Without =#+AUTHOR:=, the author on the Mac is your account's full name, as =user-full-name= is in Emacs.
271
272=#+TITLE=, =#+SUBTITLE=, =#+AUTHOR=, =#+DATE=, =#+LANGUAGE=, =#+TOC: headlines=, =#+ASCII:= lines, =#+BEGIN_EXPORT ascii= blocks, =@@ascii:...@@= snippets, =#+ATTR_ASCII: :width= on horizontal rules, and the =center=, =justifyleft= and =justifyright= blocks work as in Emacs, as do the tags and =COMMENT= that leave headings out (see /Which headings are exported/). Body-only and subtree export are in the export dialog. In a subtree export, the heading's =EXPORT_TITLE=, =EXPORT_SUBTITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_LANGUAGE=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS= and =EXPORT_EXCLUDE_TAGS= properties replace the file's keywords. Leading tabs in a source block become spaces, as in Emacs.
273
274A file with something this export doesn't handle stops with "Can't export to plain text: " and what it was, rather than giving a =.txt= that differs from Emacs's: citations and =#+BIBLIOGRAPHY=, radio targets, inline tasks, table.el tables, diary sexps, inline source blocks and calls, =#+CALL=, source blocks exported with their results, =#+RESULTS= without a source block, wide or combining characters (such as CJK text, emoji and combining accents), also in the =#+LANGUAGE= words for captions, for section references in footnotes, and for a link's note when they take a line past the text width, tabs outside source and example blocks or in the indentation of an indented source block, footnote definitions of several paragraphs, footnotes in headings, keywords, captions or other footnotes, =UNNUMBERED= and =ALT_TITLE=, tables with special columns or column groups, empty list items, alphabetical counters, affiliated keywords in list items, blocks whose first line is blank, headings inside blocks, numbered source blocks inside other blocks, verse blocks with more than text, links inside link descriptions, =doi=, =info=, =irc=, =attachment=, =docview=, =bbdb=, =bibtex=, =gnus=, =rmail=, =mhe=, =w3m= and =eww= links, plain links other than =http=, =https=, =mailto= and =file= in any case, links to =<<targets>>= and named elements, short or repeated captions, unknown entities, a keyword such as =#+SUBTITLE= repeated with an empty value, =#+TOC:= other than =headlines= or with =local= or =:target=, and =#+OPTIONS= items other than =toc=, =num=, =H=, =tags=, =todo=, =pri=, =^=, =tex=, =title=, =author=, =date=, =-=, =<= and =timestamp= set to something other than Org's default. A link Emacs can't resolve stops the export in both, including a link to a heading the export leaves out, as does a described link to a heading with =#+LANGUAGE: sl=. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to plain text stops with the file's name in the message. In the download version, when Emacs is installed, such a file is exported by Emacs instead (see /Exporting through Emacs/).
275
268* Markdown export 276* Markdown export
269 277
270Markdown export writes GitHub-flavored Markdown: 278Markdown export writes GitHub-flavored Markdown:
@@ -308,7 +316,7 @@ Differences from Org: diary sexps (=%%(…)= lines and =<%%(…)>= timestamps) a
308 316
309* Publishing 317* Publishing
310 318
311Publishing (=org-publish=) exports a folder of Org files to a folder of HTML, Markdown, LaTeX or ODT files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs: 319Publishing (=org-publish=) exports a folder of Org files to a folder of HTML, Markdown, LaTeX, ODT or plain text files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs:
312 320
313#+BEGIN_SRC toml 321#+BEGIN_SRC toml
314[[publish]] 322[[publish]]
@@ -341,7 +349,7 @@ components = "notes static"
341| =recursive= | Files in subfolders too | =false= | 349| =recursive= | Files in subfolders too | =false= |
342| =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | | 350| =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | |
343| =include= | More files, relative to =base-directory=, separated by spaces | | 351| =include= | More files, relative to =base-directory=, separated by spaces | |
344| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md=, =org-latex-publish-to-latex=, =org-odt-publish-to-odt= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= | 352| =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md=, =org-latex-publish-to-latex=, =org-odt-publish-to-odt=, =org-ascii-publish-to-ascii= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= |
345| =body-only= | The export's body only | =false= | 353| =body-only= | The export's body only | =false= |
346| =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= | 354| =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= |
347| =sitemap-filename= | The sitemap's name | ="sitemap.org"= | 355| =sitemap-filename= | The sitemap's name | ="sitemap.org"= |
@@ -367,14 +375,9 @@ A file whose published copy is newer than it is skipped, as Org skips files that
367 375
368* Exporting through Emacs 376* Exporting through Emacs
369 377
370On the Mac, PDF and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses: 378On the Mac, PDF through LaTeX is done by Emacs, with =org-latex-export-to-pdf=, the function Emacs's dispatcher uses.
371
372| Format | Function |
373|------------+-----------------------------|
374| PDF | =org-latex-export-to-pdf= |
375| Plain text | =org-ascii-export-to-ascii= |
376 379
377LaTeX goes to Emacs (=org-latex-export-to-latex=) only for a file orgstar's own LaTeX export can't write as Emacs would; see /LaTeX export/. The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports. 380LaTeX and plain text go to Emacs (=org-latex-export-to-latex=, =org-ascii-export-to-ascii=) only for a file orgstar's own export can't write as Emacs would; see /LaTeX export/ and /ASCII export/. The [[file:../install.org][Mac App Store version]] doesn't run Emacs and has none of these exports.
378 381
379orgstar runs =emacs -Q --batch= in the Org file's folder. It opens the file, replaces its contents with the editor's current text without saving, and calls the function. Emacs writes the result beside the file, as it would itself; with a destination chosen in the export dialog, orgstar then moves it there. The message area shows "Exporting with Emacs…" and then "Exported to /name/". 382orgstar runs =emacs -Q --batch= in the Org file's folder. It opens the file, replaces its contents with the editor's current text without saving, and calls the function. Emacs writes the result beside the file, as it would itself; with a destination chosen in the export dialog, orgstar then moves it there. The message area shows "Exporting with Emacs…" and then "Exported to /name/".
380 383
docs/manual/guide/14-ios.org +3 −3
@@ -329,9 +329,9 @@ The app icon's badge counts the entries in the agenda's Overdue section that are
329 329
330* Export 330* Export
331 331
332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar and LaTeX, and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. For a file the LaTeX export can't write as Emacs would, the share sheet stops and "Can't export to LaTeX: " and the reason show at the bottom of the screen. 332Export (in the reader's toolbar and the editor's More menu) offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text, ODT, iCalendar, LaTeX and Plain Text (ASCII), and Copy as Rich Text. Each opens the share sheet with a file named after the org file, which you can send to another app or keep with Save to Files. The export reads the file's setup files and follows its export keywords, as the Mac's export does. For a file the LaTeX or ASCII export can't write as Emacs would, the share sheet stops and "Can't export to LaTeX: " or "Can't export to plain text: " and the reason show at the bottom of the screen.
333 333
334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. ASCII and PDF through LaTeX aren't available on iOS. See [[file:12-export.org][Export]]. 334PDF export follows =pdf-margin=, =pdf-font= and =pdf-page-numbers= in =config.toml=, and Word files get heading styles and the file's images, as on the Mac. PDF through LaTeX isn't available on iOS. See [[file:12-export.org][Export]].
335 335
336* Code blocks and tables 336* Code blocks and tables
337 337
@@ -436,7 +436,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
436* What the Mac has that iOS doesn't 436* What the Mac has that iOS doesn't
437 437
438- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs. 438- In the download version: running code blocks in languages other than Emacs Lisp and JavaScript, Emacs Lisp beyond orgstar's interpreter, JavaScript that needs node, and tables that need Emacs.
439- Publishing, and in the download version ASCII and LaTeX-made PDF export. 439- Publishing, and in the download version LaTeX-made PDF export.
440- Idle detection while a clock runs. 440- Idle detection while a clock runs.
441- Import from Emacs of agenda folders. 441- Import from Emacs of agenda folders.
442- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]). 442- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]).
docs/manual/guide/15-alongside-emacs.org +2 −2
@@ -120,9 +120,9 @@ Some features run Emacs in batch mode on the Mac. Everything else works without
120| Emacs Lisp source blocks (=emacs-lisp=, =elisp=) | The block, in =emacs -Q --batch= | 120| Emacs Lisp source blocks (=emacs-lisp=, =elisp=) | The block, in =emacs -Q --batch= |
121| Table formulas outside what orgstar computes itself | =org-table-recalculate= on a copy of the file; the table's new text replaces the old one if the table didn't change meanwhile | 121| Table formulas outside what orgstar computes itself | =org-table-recalculate= on a copy of the file; the table's new text replaces the old one if the table didn't change meanwhile |
122| Lisp table formulas that orgstar's Emacs Lisp interpreter can't evaluate | The same; orgstar first asks whether to run Lisp (yes, no, always) | 122| Lisp table formulas that orgstar's Emacs Lisp interpreter can't evaluate | The same; orgstar first asks whether to run Lisp (yes, no, always) |
123| Export to PDF and plain text, and LaTeX orgstar can't write itself | =org-latex-export-to-pdf=, =org-ascii-export-to-ascii= or =org-latex-export-to-latex= | 123| Export to PDF, and LaTeX and plain text orgstar can't write itself | =org-latex-export-to-pdf=, =org-latex-export-to-latex= or =org-ascii-export-to-ascii= |
124 124
125HTML, Markdown, ODT and LaTeX export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]]. 125HTML, Markdown, ODT, LaTeX and ASCII export don't use Emacs. See [[file:11-code-blocks.org][Code blocks]], [[file:10-tables.org][Tables]] and [[file:12-export.org][Export]].
126 126
127** How Emacs is found 127** How Emacs is found
128 128
docs/manual/install.org +5 −5
@@ -7,7 +7,7 @@
7- macOS 26 or later. 7- macOS 26 or later.
8- Optional, for the download version: GNU Emacs, for the features that hand work to it 8- Optional, for the download version: GNU Emacs, for the features that hand work to it
9 (Emacs Lisp code blocks that need full Emacs, Lisp table formulas the built-in 9 (Emacs Lisp code blocks that need full Emacs, Lisp table formulas the built-in
10 interpreter can't run, and export to PDF through LaTeX and ASCII). See 10 interpreter can't run, and export to PDF through LaTeX). See
11 [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]]. 11 [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]].
12 12
13* The Mac app 13* The Mac app
@@ -59,7 +59,7 @@ App Store version.
59| Tangling | Yes | Yes | 59| Tangling | Yes | Yes |
60| Table formulas | Those orgstar computes itself | The rest in Emacs as well | 60| Table formulas | Those orgstar computes itself | The rest in Emacs as well |
61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts | 61| Plots | Drawn with Swift Charts | gnuplot when installed, else Swift Charts |
62| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX; publishing | Also PDF through LaTeX and ASCII, in Emacs | 62| Export | HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX, ASCII; publishing | Also PDF through LaTeX, in Emacs |
63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= | 63| Settings | In the app's container, or a folder you choose | =~/.config/orgstar= |
64| Files outside your folders | After you grant access to their folder | Directly | 64| Files outside your folders | After you grant access to their folder | Directly |
65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked | 65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked |
@@ -73,9 +73,9 @@ reports "This block uses /name/, which runs only in node." A table whose formula
73the first formula that needs it, which the message names with the reason; the fields 73the first formula that needs it, which the message names with the reason; the fields
74before it stay and the rest are unchanged. The Emacs exports are 74before it stay and the rest are unchanged. The Emacs exports are
75not in the File ▸ Export menu, the export dialog or the command palette; a key bound to 75not in the File ▸ Export menu, the export dialog or the command palette; a key bound to
76Export to PDF with Emacs exports to PDF without LaTeX. LaTeX export is orgstar's own and is in 76Export to PDF with Emacs exports to PDF without LaTeX. LaTeX and ASCII export are orgstar's own
77both versions; a file it can't write as Emacs would reports "Can't export to LaTeX", with the 77and are in both versions; a file they can't write as Emacs would reports "Can't export to
78reason. 78LaTeX" or "Can't export to plain text", with the reason.
79 79
80** Folders and files 80** Folders and files
81 81
l10n/Localizable.xcstrings +6 −6
@@ -11854,37 +11854,37 @@
11854 } 11854 }
11855 } 11855 }
11856 }, 11856 },
11857 "Export to Plain Text with Emacs": { 11857 "Export to Plain Text (ASCII)": {
11858 "comment": "Command title", 11858 "comment": "Command title",
11859 "localizations": { 11859 "localizations": {
11860 "de": { 11860 "de": {
11861 "stringUnit": { 11861 "stringUnit": {
11862 "state": "translated", 11862 "state": "translated",
11863 "value": "Mit Emacs als reinen Text exportieren" 11863 "value": "Als reinen Text (ASCII) exportieren"
11864 } 11864 }
11865 }, 11865 },
11866 "es": { 11866 "es": {
11867 "stringUnit": { 11867 "stringUnit": {
11868 "state": "translated", 11868 "state": "translated",
11869 "value": "Exportar a texto sin formato con Emacs" 11869 "value": "Exportar a texto sin formato (ASCII)"
11870 } 11870 }
11871 }, 11871 },
11872 "fr": { 11872 "fr": {
11873 "stringUnit": { 11873 "stringUnit": {
11874 "state": "translated", 11874 "state": "translated",
11875 "value": "Exporter en texte brut avec Emacs" 11875 "value": "Exporter en texte brut (ASCII)"
11876 } 11876 }
11877 }, 11877 },
11878 "ja": { 11878 "ja": {
11879 "stringUnit": { 11879 "stringUnit": {
11880 "state": "translated", 11880 "state": "translated",
11881 "value": "Emacsでプレーンテキストに書き出す" 11881 "value": "プレーンテキスト(ASCII)に書き出す"
11882 } 11882 }
11883 }, 11883 },
11884 "pt-BR": { 11884 "pt-BR": {
11885 "stringUnit": { 11885 "stringUnit": {
11886 "state": "translated", 11886 "state": "translated",
11887 "value": "Exportar para Texto Simples com o Emacs" 11887 "value": "Exportar para Texto Simples (ASCII)"
11888 } 11888 }
11889 } 11889 }
11890 } 11890 }