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