Sources/OrgCore/Compute/BabelResults.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Compute/BabelResults.swift history · blame · raw

567 lines · 27731 bytes

23 symbols in this file
  1import Foundation
  2
  3extension Babel {
  4    // MARK: - Finishing
  5
  6    /// What the run produced, as Babel holds it before inserting.
  7    enum Value: Equatable {
  8        case none
  9        case string(String)
 10        /// Rows of cells; nil rows are rules.
 11        case table([[String]?])
 12    }
 13
 14    /// The edit that writes the run's result under the block, or why it can't.
 15    public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
 16        let ns = text as NSString
 17        var blockRange = job.block
 18        if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
 19            let found = ns.range(of: job.blockText)
 20            guard found.location != NSNotFound,
 21                  ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
 22                return .failure(.message("The block changed while it ran; the result wasn't written."))
 23            }
 24            blockRange = found.location..<NSMaxRange(found)
 25        }
 26        if let failure = sqliteFailure(job.finish, output) { return .failure(.message(failure)) }
 27        let value = Self.value(job.finish, output)
 28        if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
 29        let buffer = EmacsBuffer(text, point: 0, settings: settings)
 30        if job.finish.inline {
 31            do {
 32                try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
 33            } catch let error as Failure {
 34                return .failure(error)
 35            } catch {
 36                return .failure(.message("\(error)"))
 37            }
 38            return .success(TextEdit.between(text, buffer.text as String))
 39        }
 40        insertResult(value, job.finish, block: blockRange, buffer: buffer)
 41        return .success(TextEdit.between(text, buffer.text as String))
 42    }
 43
 44    /// The language's result handling: `org-babel-result-cond` and the table import.
 45    static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
 46        // The value of `:post` goes in as it is; a list is a table of one row.
 47        if let post = finish.post, !finish.params.contains("file") {
 48            switch post {
 49            case .scalar(let s), .number(let s): return .string(s)
 50            case .list(let items): return .table([items.map(cellText)])
 51            case .table(let rows): return .table(rows.map { $0?.map(cellText) })
 52            }
 53        }
 54        let value = reassemble(rawValue(finish, output), finish)
 55        switch (finish.kind, value) {
 56        case (.calc, .string(let s)), (.sqlite, .string(let s)):
 57            // `org-babel-execute-src-block` makes a table of a value that isn't a list.
 58            if !finish.params.contains("output"), finish.params.contains("vector") || finish.params.contains("table") { return .table([[s]]) }
 59            return value
 60        default:
 61            return value
 62        }
 63    }
 64
 65    static func rawValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
 66        let params = finish.params
 67        if params.contains("file") {
 68            // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
 69            let path = finish.file ?? finish.post.map { shellString($0) } ?? rawResult(finish, output)
 70            var link = "[[file:" + path + "]"
 71            if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
 72            return .string(link + "]")
 73        }
 74        let scalar = resultCondScalar(params)
 75        switch finish.kind {
 76        case .calc:
 77            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
 78                return .string(output.stdout)
 79            }
 80            if let rows = object["rows"] as? [[String]] { return .table(rows) }
 81            return .string(object["value"] as? String ?? "")
 82        case .sqlite(let csv, let headers):
 83            return sqliteValue(output.stdout, csv: csv, headers: headers, scalar: scalar)
 84        case .shell(let valueIsExitStatus):
 85            var results = output.stdout
 86            if valueIsExitStatus {
 87                results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
 88            }
 89            if scalar { return .string(results) }
 90            return importTable(results)
 91        case .generic:
 92            return .string(output.stdout)
 93        case .python:
 94            let raw = finish.output ? output.stdout : (output.resultFile ?? "")
 95            if scalar { return .string(raw) }
 96            return pythonValue(raw)
 97        case .emacsLisp:
 98            guard let data = output.stdout.data(using: .utf8),
 99                  let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
100            if scalar {
101                return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
102            }
103            if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
104            if let rows = object["rows"] as? [Any] {
105                return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
106            }
107            let printed = object["S"] as? String ?? ""
108            return printed == "nil" ? .none : .string(printed)
109        case .compiled:
110            return compiledValue(finish, output, scalar: scalar)
111        case .script(let js, _):
112            let raw = rawResult(finish, output)
113            if scalar { return .string(raw) }
114            // `org-babel-ruby-table-or-string`, its nils rules.
115            return js ? jsValue(raw) : pythonValue(raw, none: "nil", braces: true)
116        }
117    }
118
119    /// The result as the program left it, before tables are read.
120    static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
121        switch finish.kind {
122        case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
123        case .emacsLisp:
124            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
125            return object["s"] as? String ?? ""
126        case .shell(let valueIsExitStatus):
127            return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
128        case .generic: return output.stdout
129        case .calc:
130            guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
131            return object["value"] as? String ?? ""
132        case .sqlite: return output.stdout
133        case .compiled: return compiledResult(finish, output)
134        case .script(let js, let session): return finish.output || (js && !session) ? output.stdout : (output.resultFile ?? "")
135        }
136    }
137
138    /// With `:results file` and `:file`, what to write there, relative to the run's folder;
139    /// nil when there's nothing to write or the program wrote it.
140    public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
141        guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
142        return (file, rawResult(job.finish, output))
143    }
144
145    /// `org-babel-import-elisp-from-file`.
146    static func importTable(_ results: String) -> Value {
147        guard !results.isEmpty else { return .none }
148        var lines = results.components(separatedBy: "\n")
149        if lines.last == "" { lines.removeLast() }
150        let nonEmpty = lines.filter { !$0.isEmpty }
151        let rows: [[String]]
152        if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
153            rows = lines.map { $0.components(separatedBy: "\t") }
154        } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
155            rows = lines.map(csvFields)
156        } else if lines.count == 1 {
157            rows = [[lines[0]]]
158        } else {
159            rows = lines.map { line in
160                let trimmed = line.drop { $0 == " " }
161                return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
162                    ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
163            }
164        }
165        let cells = rows.map { row in row.map { field -> String in
166            let trimmed = field.trimmingCharacters(in: .whitespaces)
167            switch cell(trimmed) {
168            case .number(let n): return n
169            case .text(let t): return t
170            }
171        } }
172        if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
173        return .table(cells)
174    }
175
176    static func csvFields(_ line: String) -> [String] {
177        var fields: [String] = []
178        var current = ""
179        var quoted = false
180        for c in line {
181            if c == "\"" {
182                quoted.toggle()
183            } else if c == ",", !quoted {
184                fields.append(current.trimmingCharacters(in: .whitespaces))
185                current = ""
186            } else {
187                current.append(c)
188            }
189        }
190        fields.append(current.trimmingCharacters(in: .whitespaces))
191        return fields
192    }
193
194    /// `org-babel-python-table-or-string`; with `none` "null" and `braces`,
195    /// `org-babel-java-table-or-string`, which reads `{…}` as a list too.
196    static func pythonValue(_ raw: String, none: String = "None", braces: Bool = false) -> Value {
197        guard let first = raw.first, let last = raw.last, raw.count >= 2,
198              (first == "[" && last == "]") || (first == "(" && last == ")") || (braces && first == "{" && last == "}") else {
199            if raw.isEmpty { return .string("") }
200            if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
201                return .string(String(raw.dropFirst().dropLast()))
202            }
203            if let n = number(raw) { return .string(n) }
204            return .string(raw)
205        }
206        var parser = PythonLiteral(Array(raw))
207        parser.braces = braces
208        guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
209        func text(_ v: PythonLiteral.Node) -> String {
210            switch v {
211            case .atom(let s): return s
212            case .string(let s): return s
213            case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
214            }
215        }
216        if items.allSatisfy({ if case .list = $0 { return true }; if case .atom(none) = $0 { return true }; return false }) {
217            return .table(items.map { item -> [String]? in
218                if case .list(let cells) = item { return cells.map(text) }
219                return nil
220            })
221        }
222        return .table([items.map { if case .atom(none) = $0 { return "hline" }; return text($0) }])
223    }
224
225    struct PythonLiteral {
226        indirect enum Node: Equatable {
227            case atom(String)
228            case string(String)
229            case list([Node])
230        }
231
232        let chars: [Character]
233        var i = 0
234        /// `{…}` is a list, as `org-babel-script-escape` reads it.
235        var braces = false
236        init(_ chars: [Character]) { self.chars = chars }
237        var atEnd: Bool { mutating get { skip(); return i == chars.count } }
238
239        mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
240
241        mutating func parse() -> Node? {
242            skip()
243            guard i < chars.count else { return nil }
244            let c = chars[i]
245            if c == "[" || c == "(" || (braces && c == "{") {
246                let close: Character = c == "[" ? "]" : c == "{" ? "}" : ")"
247                i += 1
248                var items: [Node] = []
249                skip()
250                if i < chars.count, chars[i] == close {
251                    i += 1
252                    return .list(items)
253                }
254                while true {
255                    guard let item = parse() else { return nil }
256                    items.append(item)
257                    skip()
258                    guard i < chars.count else { return nil }
259                    if chars[i] == "," {
260                        i += 1
261                        skip()
262                        if i < chars.count, chars[i] == close {
263                            i += 1
264                            return .list(items)
265                        }
266                        continue
267                    }
268                    if chars[i] == close {
269                        i += 1
270                        return .list(items)
271                    }
272                    return nil
273                }
274            }
275            if c == "'" || c == "\"" {
276                i += 1
277                var s = ""
278                while i < chars.count, chars[i] != c {
279                    if chars[i] == "\\", i + 1 < chars.count {
280                        i += 1
281                        switch chars[i] {
282                        case "n": s.append("\n")
283                        case "t": s.append("\t")
284                        default: s.append(chars[i])
285                        }
286                    } else {
287                        s.append(chars[i])
288                    }
289                    i += 1
290                }
291                guard i < chars.count else { return nil }
292                i += 1
293                return .string(s)
294            }
295            var s = ""
296            while i < chars.count, !",)] \n".contains(chars[i]), !(braces && chars[i] == "}") {
297                s.append(chars[i])
298                i += 1
299            }
300            guard !s.isEmpty else { return nil }
301            return .atom(number(s) ?? s)
302        }
303    }
304
305    // MARK: - Inserting
306
307    static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
308
309    /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
310    /// keyword, added when there is none.
311    /// The `#+RESULTS` line of a block's results (`org-babel-where-is-src-block-result`):
312    /// the one naming `name`, or for an unnamed block an empty one right after it.
313    static func existingResults(name: String?, block: Range<Int>, text ns: NSString) -> Int? {
314        if let name {
315            let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
316            let regex = try! NSRegularExpression(pattern: pattern)
317            return regex.firstMatch(in: ns as String, range: NSRange(location: 0, length: ns.length))?.range.location
318        }
319        // The element after the block, past blank lines.
320        var location = block.upperBound
321        while location < ns.length {
322            let line = ns.lineRange(for: NSRange(location: location, length: 0))
323            let content = ns.substring(with: line)
324            if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
325                location = NSMaxRange(line)
326                continue
327            }
328            if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
329                return line.location
330            }
331            break
332        }
333        return nil
334    }
335
336    /// The hash in the `#+RESULTS[…]:` line at `line` (`org-babel-result-regexp`).
337    static func resultsHash(at line: Int, text ns: NSString) -> String? {
338        let content = ns.substring(with: ns.lineRange(for: NSRange(location: line, length: 0)))
339        return content.firstMatch(of: #/(?i)^[ \t]*#\+results\[(?:\(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\) )?([0-9a-f]+)\]:/#).map { String($0.1) }
340    }
341
342    static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
343        if let line = existingResults(name: finish.name, block: block, text: buffer.text) {
344            // `org-babel--clear-results-maybe`: a different hash clears the results and
345            // rewrites the keyword.
346            if let hash = finish.hash, resultsHash(at: line, text: buffer.text) != hash {
347                buffer.point = line
348                let indent = String(buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == " " || $0 == "\t" })
349                buffer.forwardLine(1)
350                let contents = buffer.point
351                buffer.deleteRegion(contents, max(contents, resultEnd(buffer)))
352                buffer.deleteRegion(line, contents)
353                buffer.point = line
354                buffer.insert(indent + "#+RESULTS[\(hash)]:" + (finish.name.map { " " + $0 } ?? "") + "\n")
355                if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
356                    buffer.saveExcursion { buffer.insert("\n") }
357                }
358            }
359            return line
360        }
361        // A new keyword after the block.
362        buffer.point = min(block.upperBound, buffer.length)
363        buffer.skipBackward([32, 9, 10, 13])
364        buffer.forwardLine(1)
365        if !buffer.bolp { buffer.insert("\n") }
366        let indent = buffer.saveExcursion { () -> String in
367            buffer.point = block.lowerBound
368            let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
369            return String(line.prefix { $0 == " " || $0 == "\t" })
370        }
371        buffer.insert("\n")
372        let keywordLine = buffer.point
373        buffer.insert(indent + "#+RESULTS" + (finish.hash.map { "[\($0)]" } ?? "") + ":" + (finish.name.map { " " + $0 } ?? "") + "\n")
374        if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
375            buffer.saveExcursion { buffer.insert("\n") }
376        }
377        return keywordLine
378    }
379
380    /// `org-babel-result-end` with point at the start of the result.
381    static func resultEnd(_ buffer: EmacsBuffer) -> Int {
382        let start = buffer.point
383        let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
384        if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
385        if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
386            return min(buffer.length, buffer.lineEnd(start) + 1)
387        }
388        let tree = OrgParser.parse(buffer.text as String)
389        var node = tree.root
390        var found: SyntaxNode?
391        while let child = node.child(containing: start) {
392            if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
393                if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
394                    found = child
395                    break
396                }
397            }
398            node = child
399        }
400        guard let element = found else { return start }
401        var end = element.range.upperBound
402        while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
403        return min(buffer.length, buffer.lineEnd(end) + 1)
404    }
405
406    /// `org-babel-insert-result` for a src block.
407    /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
408    /// there; raw results go in as they are.
409    static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
410        var string: String
411        switch value {
412        case .none: string = ""
413        case .string(let s): string = s
414        case .table(let rows):
415            let cells = rows.compactMap { $0 }
416            guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
417            string = cells[0][0]
418        }
419        buffer.point = object.upperBound
420        if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
421            buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
422        }
423        if finish.params.contains("raw") {
424            buffer.insert(" " + string)
425            return
426        }
427        if string.hasSuffix("\n") { string.removeLast() }
428        guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
429        buffer.insert(" {{{results(=" + string + "=)}}}")
430    }
431
432    static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
433        let params = finish.params
434        let keyword = resultsLine(finish, block: block, buffer: buffer)
435        buffer.point = keyword
436        let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
437        buffer.forwardLine(1)
438        if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
439        var beg = buffer.point
440        if params.contains("replace") {
441            buffer.deleteRegion(beg, resultEnd(buffer))
442            buffer.point = beg
443        } else if params.contains("append") {
444            buffer.point = resultEnd(buffer)
445            beg = buffer.point
446        }
447        var tabulated = false
448        // A list made from a string is examplified, as a string result is.
449        var listed = false
450        switch value {
451        case .none:
452            break
453        case .string(let s) where params.contains("list") && finish.givesRows:
454            // `split-string` without empty lines, each an item; `org-trim` of the list.
455            var items = s.components(separatedBy: "\n").filter { !$0.isEmpty }.map { "- " + $0 }.joined(separator: "\n")
456            while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
457            if !items.isEmpty { buffer.insert(items + "\n") }
458        case .string(var s) where params.contains("list"):
459            if s.last != "\n" { s += "\n" }
460            let items = s.split(separator: "\n", omittingEmptySubsequences: true)
461            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
462        case .table(let rows) where params.contains("list") && finish.givesRows:
463            // Each row an item, its first cell the text and the others lines under it.
464            listed = true
465            var items = rows.map { row in
466                guard let row else { return "- hline\n" }
467                return "- " + (row.first ?? "") + "\n" + row.dropFirst().map { "  " + $0 + "\n" }.joined()
468            }.joined()
469            while let last = items.unicodeScalars.last, " \r\t\n".unicodeScalars.contains(last) { items.unicodeScalars.removeLast() }
470            buffer.insert(items + "\n")
471        case .table(let rows) where params.contains("list"):
472            listed = true
473            let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
474            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
475        case .table(let rows):
476            tabulated = true
477            let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
478            let start = buffer.point
479            buffer.insert(lines.joined(separator: "\n") + "\n")
480            buffer.point = start
481            buffer.tableAlign()
482            buffer.point = buffer.tableEnd()
483        case .string(var s):
484            // `org-string-nw-p`: a blank result gets no newline.
485            if s.unicodeScalars.contains(where: { !" \r\t\n".unicodeScalars.contains($0) }), s.unicodeScalars.last != "\n" { s += "\n" }
486            buffer.insert(s)
487        }
488        let end = buffer.marker(buffer.point, advances: true)
489        defer { buffer.release(end) }
490        func wrap(_ open: String, _ close: String, escape: Bool) {
491            buffer.point = end.position
492            buffer.insert(close + "\n")
493            buffer.point = beg
494            buffer.insert(open + "\n")
495            if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
496        }
497        if let wrapValue = finish.wrap {
498            let full = wrapValue.isEmpty ? "results" : wrapValue
499            let type = String(full.split(separator: " ").first ?? "results")
500            if type.lowercased() != "nil", type.lowercased() != "no" {
501                wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
502            }
503        } else if params.contains("html") {
504            wrap("#+begin_export html", "#+end_export", escape: true)
505        } else if params.contains("latex") {
506            wrap("#+begin_export latex", "#+end_export", escape: true)
507        } else if params.contains("org") {
508            wrap("#+begin_src org", "#+end_src", escape: true)
509        } else if params.contains("code") {
510            wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
511        } else if params.contains("raw") || params.contains("file") {
512            // As inserted.
513        } else if params.contains("drawer") {
514            wrap(":results:", ":end:", escape: false)
515        } else if !tabulated, !(params.contains("list") && listed) {
516            examplify(buffer, beg, end.position)
517        }
518        if indent > 0, !(tabulated && params.contains("append")) {
519            buffer.point = beg
520            while buffer.point < end.position {
521                if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
522                if buffer.forwardLine(1) != 0 { break }
523            }
524        }
525    }
526
527    /// `org-escape-code-in-region`.
528    static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
529        buffer.point = start
530        let stop = buffer.marker(end)
531        defer { buffer.release(stop) }
532        while buffer.point < stop.position {
533            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
534            if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
535                buffer.point += line[..<m.1.startIndex].utf16.count
536                buffer.insert(",")
537            }
538            if buffer.forwardLine(1) != 0 { break }
539        }
540    }
541
542    /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
543    static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
544        let text = buffer.substring(beg, end)
545        var size = text.components(separatedBy: "\n").count - (text.utf16.last == 10 ? 1 : 0)
546        if text.isEmpty { size = 0 }
547        guard size > 0 else { return }
548        if size < 10 {
549            buffer.point = beg
550            for _ in 0..<size {
551                buffer.point = buffer.lineStart(buffer.point)
552                buffer.insert(": ")
553                buffer.forwardLine(1)
554            }
555            return
556        }
557        let endMarker = buffer.marker(end)
558        defer { buffer.release(endMarker) }
559        buffer.point = beg
560        buffer.insert("#+begin_example\n")
561        escapeCode(buffer, from: buffer.point, to: endMarker.position)
562        buffer.point = endMarker.position
563        if !buffer.bolp { buffer.insert("\n") }
564        buffer.insert("#+end_example")
565        if !buffer.eolp { buffer.insert("\n") }
566    }
567}