Sources/OrgCore/Compute/BabelResults.swift

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