Sources/OrgCore/Compute/BabelResults.swift

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

519 lines · 24605 bytes

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