Sources/OrgCore/Export/ASCIIText.swift
470 lines · 24107 bytes
1import Foundation
2
3/// What ox-ascii (Org 9.8.7) makes of a section's elements and a heading's title with
4/// `:ascii-charset utf-8` and links in place (`:ascii-links-to-notes nil`), as the iCalendar
5/// export writes summaries and descriptions: paragraphs filled to the text width, lists with
6/// `•` bullets, blocks in a partial box, tables drawn with box characters.
7struct ASCIIText {
8 let options: ExportOptions
9 /// Heading numbers by title, for fuzzy links without a description.
10 var headingNumbers: [String: String] = [:]
11
12 static let textWidth = 72
13 static let innerMargin = 2
14 static let quoteMargin = 6
15
16 /// The text width inside a section under a heading at `level` (`org-ascii--current-text-width`).
17 func width(level: Int?) -> Int {
18 guard let level else { return Self.textWidth }
19 return Self.textWidth - (level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin)
20 }
21
22 // MARK: - Elements
23
24 /// `nodes`, each followed by the blank lines after it in `source`, as `org-export-data`
25 /// joins elements. Elements the export leaves out add nothing.
26 func elements(_ nodes: [SyntaxNode], end: Int, source: NSString, width: Int) -> String {
27 var out = ""
28 for (index, node) in nodes.enumerated() {
29 guard let text = element(node, source: source, width: width), !text.isEmpty else { continue }
30 let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end
31 out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: node.range.upperBound, to: next))
32 }
33 return out
34 }
35
36 /// Blank lines between `from`, a line start, and `to`.
37 static func blankLines(_ source: NSString, from: Int, to: Int) -> Int {
38 guard to > from, from < source.length else { return 0 }
39 let gap = source.substring(with: NSRange(location: from, length: min(to, source.length) - from))
40 return gap.components(separatedBy: "\n").dropLast().count
41 }
42
43 /// `org-element-normalize-string`: one final newline.
44 static func normalized(_ s: String) -> String {
45 var s = s
46 while s.hasSuffix("\n") || s.hasSuffix(" ") || s.hasSuffix("\t") { s.removeLast() }
47 return s + "\n"
48 }
49
50 func element(_ node: SyntaxNode, source: NSString, width: Int) -> String? {
51 switch node.kind {
52 case .paragraph:
53 return paragraph(node, width: width)
54 case .plainList:
55 return list(node, source: source, width: width)
56 case .table:
57 return table(node)
58 case .tableEl:
59 return Self.removeIndentation(node.text.trimmingCharacters(in: .newlines))
60 case .block:
61 return block(node, width: width)
62 case .fixedWidth:
63 let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in
64 let trimmed = line.drop { $0 == " " || $0 == "\t" }
65 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1))
66 }
67 return Self.box(Self.removeIndentation(lines.joined(separator: "\n")))
68 case .horizontalRule:
69 return String(repeating: "―", count: width)
70 case .drawer:
71 let name = node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1).uppercased() } ?? ""
72 if name == "LOGBOOK" { return nil }
73 return elements(node.children, end: node.range.upperBound, source: source, width: width)
74 case .dynamicBlock:
75 return elements(node.children, end: node.range.upperBound, source: source, width: width)
76 case .latexEnvironment:
77 return options.tex ? Self.removeIndentation(node.text.trimmingCharacters(in: .newlines)) : nil
78 case .keyword:
79 guard let m = node.text.firstMatch(of: /(?i)^[ \t]*#\+ASCII:[ \t]*(.*?)[ \t]*\n?$/) else { return nil }
80 return String(m.1)
81 default:
82 // Planning, drawers of properties, clocks, comments, keywords and footnote
83 // definitions export nothing here.
84 return nil
85 }
86 }
87
88 // MARK: Paragraphs
89
90 func paragraph(_ node: SyntaxNode, width: Int) -> String {
91 var text = inline(node, skippingTimestamps: Self.isolatedTimestamps(node))
92 // `org-remove-blank-lines`.
93 text = text.replacing(#/\n[ \t]*\n(?:[ \t]*\n)*/#, with: "\n")
94 return Self.fill(text, width: width)
95 }
96
97 /// Whether the paragraph holds only timestamps and whitespace, whose timestamps
98 /// `:with-timestamps` decides.
99 static func isolatedTimestamps(_ node: SyntaxNode) -> Bool {
100 var any = false
101 for element in node.elements {
102 switch element {
103 case .token(let token):
104 if !token.text.allSatisfy(\.isWhitespace) { return false }
105 case .node(let child):
106 guard child.kind == .timestamp else { return false }
107 any = true
108 }
109 }
110 return any
111 }
112
113 /// `org-ascii--fill-string`: `fill-region` with `fill-column` `width`,
114 /// `sentence-end-double-space` and hard newlines from line breaks.
115 static func fill(_ text: String, width: Int) -> String {
116 text.components(separatedBy: hardNewline).map { fillParagraph($0, width: width) }.joined(separator: "\n")
117 }
118
119 static let hardNewline = "\u{1}"
120
121 static func fillParagraph(_ text: String, width: Int) -> String {
122 var lines = text.components(separatedBy: "\n")
123 while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() }
124 guard !lines.isEmpty else { return "" }
125 func indentation(_ line: String) -> String { String(line.prefix { $0 == " " || $0 == "\t" }) }
126 let first = indentation(lines[0])
127 // `fill-context-prefix`: the second line's indentation when the first starts with it.
128 let prefix = lines.count >= 2 ? (lines[0].hasPrefix(indentation(lines[1])) ? indentation(lines[1]) : "") : first
129 var parts: [String] = []
130 for (i, line) in lines.enumerated() {
131 var content = String(line.dropFirst(indentation(line).count))
132 while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() }
133 // 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 += " " }
135 parts.append(content)
136 }
137 let joined = parts.joined(separator: " ").replacingOccurrences(of: "\t", with: " ")
138 // Words and the spaces after them, with `canonically-space-region`'s spacing.
139 var words: [(word: String, spaces: Int)] = []
140 var index = joined.startIndex
141 while index < joined.endIndex {
142 let wordEnd = joined[index...].firstIndex(of: " ") ?? joined.endIndex
143 let word = String(joined[index..<wordEnd])
144 let spaceEnd = joined[wordEnd...].firstIndex { $0 != " " } ?? joined.endIndex
145 var spaces = joined.distance(from: wordEnd, to: spaceEnd)
146 if spaces >= 2 {
147 let closers = word.reversed().drop { "]})\"'".contains($0) }
148 spaces = closers.first.map { ".?!".contains($0) } == true ? 2 : 1
149 }
150 if !word.isEmpty { words.append((word, spaces)) } else if var last = words.popLast() {
151 last.spaces += spaces
152 words.append(last)
153 }
154 index = spaceEnd
155 }
156 guard !words.isEmpty else { return first }
157 /// `fill-nobreak-p`: not after a period followed by a single space.
158 func breakable(after i: Int) -> Bool { !(words[i].spaces == 1 && words[i].word.hasSuffix(".")) }
159 var out: [String] = []
160 var start = 0
161 while start < words.count {
162 let lead = out.isEmpty ? first : prefix
163 var length = lead.count + words[start].word.count
164 var end = start
165 var lastBreak: Int?
166 while end + 1 < words.count {
167 let next = length + words[end].spaces + words[end + 1].word.count
168 if next > width {
169 if breakable(after: end) {
170 lastBreak = end
171 break
172 }
173 if lastBreak != nil { break }
174 } else if breakable(after: end) {
175 lastBreak = end
176 }
177 length = next
178 end += 1
179 }
180 let stop = end + 1 < words.count ? (lastBreak ?? end) : end
181 var line = lead
182 for i in start...stop {
183 line += words[i].word
184 if i < stop { line += String(repeating: " ", count: words[i].spaces) }
185 }
186 out.append(line)
187 start = stop + 1
188 }
189 return out.joined(separator: "\n")
190 }
191
192 // MARK: Lists
193
194 func list(_ node: SyntaxNode, source: NSString, width: Int) -> String {
195 let items = node.children.filter { $0.kind == .item }
196 var out = ""
197 var number = 0
198 // The first item decides the list's type, as `org-list-get-list-type` does.
199 let firstBullet = (items.first?.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
200 let descriptive = items.first?.firstChild(.itemTag) != nil
201 let ordered = !descriptive && firstBullet.first.map { $0.isNumber || $0.isLetter } == true
202 for (index, item) in items.enumerated() {
203 let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces)
204 let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text {
205 case "[X]"?, "[x]"?: "☑ "
206 case "[ ]"?: "☐ "
207 case "[-]"?: "☒ "
208 default: ""
209 }
210 let tag = descriptive ? item.firstChild(.itemTag) : nil
211 let bullet: String
212 let indentation: Int
213 if descriptive {
214 bullet = checkbox + (tag.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "")
215 indentation = Self.quoteMargin
216 } else if ordered {
217 if let counter = item.tokens.first(where: { $0.kind == .counter })?.text,
218 let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) {
219 number = n
220 } else {
221 number += 1
222 }
223 bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " "
224 indentation = bullet.count
225 } else {
226 bullet = ["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " "
227 indentation = bullet.count
228 }
229 let children = item.children.filter { $0.kind != .itemTag }
230 let inner = descriptive ? width - Self.quoteMargin : width - indentation - checkbox.count
231 let contents = elements(children, end: item.range.upperBound, source: source, width: inner)
232 let indented = Self.indent(contents, indentation)
233 let firstIsParagraph = children.first { (element($0, source: source, width: inner) ?? "").contains(where: { !$0.isWhitespace }) }?.kind == .paragraph
234 var text = bullet + checkbox
235 if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstIsParagraph {
236 text += indented.trimmingCharacters(in: .whitespacesAndNewlines)
237 } else {
238 text += "\n" + indented
239 }
240 let next = index + 1 < items.count ? items[index + 1].range.lowerBound : item.range.upperBound
241 out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: item.range.upperBound, to: next))
242 }
243 return out
244 }
245
246 /// `org-ascii--indent-string`: `width` spaces before each line that isn't blank.
247 static func indent(_ s: String, _ width: Int) -> String {
248 let pad = String(repeating: " ", count: width)
249 return s.components(separatedBy: "\n").map { $0.contains(where: { !$0.isWhitespace }) ? pad + $0 : $0 }.joined(separator: "\n")
250 }
251
252 static func removeIndentation(_ s: String) -> String {
253 let lines = s.components(separatedBy: "\n")
254 let common = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }.min() ?? 0
255 return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n")
256 }
257
258 /// `org-ascii--box-string` in UTF-8.
259 static func box(_ s: String) -> String {
260 let body = s.replacing(#/\n[ \t]*\z/#, with: "")
261 return "┌────\n" + body.components(separatedBy: "\n").map { "│ " + $0 }.joined(separator: "\n") + "\n└────"
262 }
263
264 // MARK: Blocks
265
266 func block(_ node: SyntaxNode, width: Int) -> String? {
267 var lines = node.text.components(separatedBy: "\n")
268 if lines.last == "" { lines.removeLast() }
269 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil }
270 let type = m.1.lowercased()
271 var body = Array(lines.dropFirst().dropLast()).map {
272 $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression)
273 }
274 body = Self.removeIndentation(body.joined(separator: "\n")).components(separatedBy: "\n")
275 switch type {
276 case "src", "example":
277 let code = body.joined(separator: "\n")
278 return code.isEmpty ? "" : Self.box(code)
279 case "quote":
280 return Self.indent(nested(body.joined(separator: "\n"), width: width - 2 * Self.quoteMargin), Self.quoteMargin)
281 case "verse":
282 let tree = OrgParser.parse(body.joined(separator: "\n"))
283 let text = tree.root.descendants().filter { $0.kind == .paragraph }.map { inline($0) }.joined(separator: "\n\n")
284 return Self.indent(text, Self.quoteMargin)
285 case "export":
286 return m.2.lowercased().hasPrefix("ascii") ? body.joined(separator: "\n") : nil
287 case "comment":
288 return nil
289 default:
290 return nested(body.joined(separator: "\n"), width: width)
291 }
292 }
293
294 /// A block's contents, parsed as elements.
295 func nested(_ text: String, width: Int) -> String {
296 let tree = OrgParser.parse(text)
297 let ns = text as NSString
298 let children = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] }
299 return elements(children, end: ns.length, source: ns, width: width)
300 }
301
302 // MARK: Tables
303
304 func table(_ node: SyntaxNode) -> String {
305 let rows = node.children.filter { $0.kind == .tableRow }
306 let cells: [[String]?] = rows.map { row in
307 let cells = row.children.filter { $0.kind == .tableCell }
308 if cells.isEmpty { return nil }
309 return cells.map { inline($0).trimmingCharacters(in: .whitespaces) }
310 }
311 let data = cells.compactMap { $0 }
312 guard !data.isEmpty else { return "" }
313 let columns = data.map(\.count).max() ?? 0
314 let filled = data.map { $0 + Array(repeating: "", count: columns - $0.count) }
315 var widths = (0..<columns).map { c in filled.map { $0[c].count }.max() ?? 0 }
316 // Width cookies such as `<10>` widen the column, as `org-ascii-table-widen-columns`.
317 for row in filled where row.allSatisfy({ $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil }) {
318 for (c, cell) in row.enumerated() { if let n = Int(cell.filter(\.isNumber)) { widths[c] = max(widths[c], n) } }
319 }
320 let cookieRows = Set(filled.indices.filter { r in
321 filled[r].contains { !$0.isEmpty } && filled[r].allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil }
322 })
323 let right = (0..<columns).map { c -> Bool in
324 let values = filled.indices.filter { !cookieRows.contains($0) }.map { filled[$0][c] }.filter { !$0.isEmpty }
325 guard !values.isEmpty else { return false }
326 let numbers = values.filter { $0.range(of: "^([><]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[-+]?0[xX][0-9a-fA-F.]+|[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .regularExpression) != nil }
327 return Double(numbers.count) / Double(values.count) >= 0.5
328 }
329 func line(_ char: String) -> String { widths.map { String(repeating: char, count: $0 + 2) }.joined() }
330 var out = ""
331 var dataIndex = 0
332 let lastData = cells.lastIndex { $0 != nil }!
333 let firstData = cells.firstIndex { $0 != nil }!
334 for (r, row) in cells.enumerated() {
335 guard row != nil else { continue }
336 let rowIndex = dataIndex
337 dataIndex += 1
338 if cookieRows.contains(rowIndex) { continue }
339 if r == firstData {
340 out += line("━") + "\n"
341 } else if r > 0, cells[r - 1] == nil {
342 out += line("─") + "\n"
343 }
344 out += filled[rowIndex].enumerated().map { c, cell in
345 let pad = String(repeating: " ", count: max(0, widths[c] - cell.count))
346 return " " + (right[c] ? pad + cell : cell + pad) + " "
347 }.joined() + "\n"
348 if r == lastData { out += line("━") + "\n" }
349 }
350 return out
351 }
352
353 // MARK: - Objects
354
355 /// The objects in `node`, as ox-ascii writes them.
356 func inline(_ node: SyntaxNode, skippingTimestamps isolated: Bool = false) -> String {
357 var out = ""
358 for element in node.elements {
359 switch element {
360 case .token(let token):
361 switch token.kind {
362 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: continue
363 default: out += special(token.text)
364 }
365 case .node(let child):
366 if isolated, child.kind == .timestamp, ICalendarExport.skipsTimestamp(child.text, with: options.timestamps ?? "t") { continue }
367 out += object(child)
368 }
369 }
370 return out
371 }
372
373 /// `org-ascii-plain-text` with `:with-special-strings`.
374 func special(_ text: String) -> String {
375 guard options.specialStrings else { return text }
376 return text.replacingOccurrences(of: "\\-", with: "").replacingOccurrences(of: "---", with: "—")
377 .replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…")
378 }
379
380 /// The text between the markers.
381 static func value(_ node: SyntaxNode) -> String {
382 node.elements.compactMap { element -> String? in
383 guard case .token(let token) = element, token.kind != .marker else { return nil }
384 return token.text
385 }.joined()
386 }
387
388 func object(_ node: SyntaxNode) -> String {
389 switch node.kind {
390 case .bold: return "*\(inline(node))*"
391 case .italic: return "/\(inline(node))/"
392 case .underline: return "_\(inline(node))_"
393 case .strikeThrough: return "+\(inline(node))+"
394 case .verbatim, .code: return "`\(Self.value(node))'"
395 case .link: return link(node)
396 case .linkDescription: return inline(node)
397 case .timestamp: return special(Self.timestamp(node.text))
398 // The iCalendar backend leaves footnote references out.
399 case .footnoteReference: return ""
400 case .entity:
401 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
402 return OrgEntities.display[name] ?? node.text
403 case .radioTarget: return String(node.text.dropFirst(3).dropLast(3))
404 case .target: return ""
405 case .superscript, .subscript:
406 let body = node.text.dropFirst()
407 let braced = body.hasPrefix("{") && body.hasSuffix("}")
408 if options.scripts == .off || (options.scripts == .braces && !braced) { return special(node.text) }
409 let mark = node.text.hasPrefix("_") ? "_" : "^"
410 return braced ? mark + "{" + String(body.dropFirst().dropLast()) + "}" : mark + String(body)
411 case .lineBreak: return Self.hardNewline
412 case .latexFragment: return options.tex ? node.text : ""
413 case .inlineSourceBlock:
414 if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "`\(m.1)'" }
415 return node.text
416 case .exportSnippet:
417 guard node.tokens.first?.text.lowercased() == "@@ascii:" else { return "" }
418 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
419 case .statisticsCookie: return node.text
420 case .inlineBabelCall, .macro: return ""
421 default: return inline(node)
422 }
423 }
424
425 func link(_ node: SyntaxNode) -> String {
426 let description = node.firstChild(.linkDescription).map { inline($0) }
427 guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else {
428 var target = node.text
429 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
430 // A radio link is its text.
431 if !target.contains(":") { return target }
432 return "<\(target)>"
433 }
434 if path.hasPrefix("("), path.hasSuffix(")") { return description ?? String(path.dropFirst().dropLast()) }
435 let scheme = path.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1).lowercased() }
436 let isInternal = scheme == nil || scheme == "id" || path.hasPrefix("#") || path.hasPrefix("*")
437 if isInternal, !(scheme == nil && (path.hasPrefix("/") || path.hasPrefix("./") || path.hasPrefix("~"))) {
438 let title = path.hasPrefix("*") ? String(path.dropFirst()) : path
439 let number = headingNumbers[title]
440 if let description { return "[\(description)]" + (number.map { " (See section \($0))" } ?? "") }
441 return number ?? title
442 }
443 guard let description, description.contains(where: { !$0.isWhitespace }) else { return "<\(path)>" }
444 return "[\(description)] (<\(path)>)"
445 }
446
447 /// `org-timestamp-translate`: the timestamp as Org writes it, `9:00` as `09:00`.
448 static func timestamp(_ text: String) -> String {
449 guard let stamp = Timestamp.parse(text) else { return text }
450 let open = stamp.active ? "<" : "["
451 let close = stamp.active ? ">" : "]"
452 func day(_ p: Timestamp.Point) -> String {
453 let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][Days.weekday(Days.absolute(year: p.year, month: p.month, day: p.day))]
454 return String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name
455 }
456 func time(_ p: Timestamp.Point) -> String { p.hour.map { String(format: " %02d:%02d", $0, p.minute ?? 0) } ?? "" }
457 var suffix = ""
458 if let r = stamp.repeater {
459 suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)"
460 if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" }
461 }
462 if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" }
463 let start = stamp.start
464 guard let end = stamp.end else { return open + day(start) + time(start) + suffix + close }
465 if (end.year, end.month, end.day) == (start.year, start.month, start.day), start.hour != nil, end.hour != nil {
466 return open + day(start) + time(start) + "-" + String(time(end).dropFirst()) + suffix + close
467 }
468 return open + day(start) + time(start) + suffix + close + "--" + open + day(end) + time(end) + suffix + close
469 }
470}