Sources/OrgCore/Compute/Babel.swift

62fdf490e1b4bd89900f188ea9cb58718e52d75b
orgstar/Sources/OrgCore/Compute/Babel.swift history · blame · raw

952 lines · 45088 bytes

  1import Foundation
  2
  3// Babel (ob-core.el, ob-shell.el, ob-python.el, ob-emacs-lisp.el, Org 9.8.7): executing a src
  4// block is planned here, run by the platform, and finished here. The plan resolves header
  5// arguments and refuses anything that would make the run differ from Emacs's; the finish turns
  6// the output into a result the way `org-babel-insert-result` writes it.
  7
  8/// A src block run for the platform to carry out.
  9public struct BabelJob: Sendable, Equatable {
 10    public enum Runner: Sendable, Equatable {
 11        /// An interpreter reading the program on standard input.
 12        case process(executable: String, arguments: [String])
 13        /// `emacs --batch` loading `input` as a script.
 14        case emacs
 15    }
 16
 17    public let language: String
 18    public let runner: Runner
 19    /// Standard input, or the Emacs script. `Babel.resultFileToken` stands for a file the runner
 20    /// creates; its contents come back as `BabelOutput.resultFile`.
 21    public let input: String
 22    /// `:dir`, relative to the file's folder; nil for the folder itself.
 23    public let directory: String?
 24    /// The block as it was planned, to find it again when the run ends.
 25    public let block: Range<Int>
 26    public let blockText: String
 27    /// Asks every time (`:eval query`) rather than trusting by content.
 28    public let alwaysAsk: Bool
 29    public let finish: Finish
 30
 31    public struct Finish: Sendable, Equatable {
 32        enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp }
 33        let kind: Kind
 34        var language = ""
 35        public let params: [String]
 36        let output: Bool
 37        let wrap: String?
 38        let name: String?
 39    }
 40}
 41
 42public struct BabelOutput: Sendable, Equatable {
 43    public var stdout: String
 44    public var resultFile: String?
 45    /// What the program wrote to standard error, and its exit status: Emacs shows them in
 46    /// `*Org-Babel Error Output*` and still inserts the results.
 47    public var stderr: String
 48    public var status: Int32
 49    public init(stdout: String, resultFile: String? = nil, stderr: String = "", status: Int32 = 0) {
 50        self.stdout = stdout
 51        self.resultFile = resultFile
 52        self.stderr = stderr
 53        self.status = status
 54    }
 55
 56    /// A line for the message area when the program failed or complained, else nil.
 57    public var problem: String? {
 58        let first = stderr.split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
 59        switch (status, first) {
 60        case (0, nil): return nil
 61        case (0, let line?): return line
 62        case (let code, nil): return "Exited with status \(code)"
 63        case (let code, let line?): return "Exited with status \(code): \(line)"
 64        }
 65    }
 66}
 67
 68public enum Babel {
 69    public static let resultFileToken = "__ORGSTAR_RESULT_FILE__"
 70    static let shells: Set<String> = ["sh", "bash", "zsh", "shell", "fish", "ksh", "dash", "ash", "csh", "mksh", "posh"]
 71    static let generic: [String: (String, [String])] = [
 72        "ruby": ("ruby", []), "js": ("node", []), "javascript": ("node", []), "R": ("Rscript", ["-"]),
 73        "awk": ("awk", ["-f", "/dev/stdin"]),
 74    ]
 75
 76    public struct Options: Sendable, Equatable {
 77        public var python = "python3"
 78        /// `shell-file-name`, for blocks in the `shell` language.
 79        public var shell = "/bin/sh"
 80        public init() {}
 81    }
 82
 83    // MARK: - Planning
 84
 85    /// The run for the src block at the caret, or why it can't run.
 86    public static func plan(_ context: EditContext, options: Options = Options()) -> Result<BabelJob, Failure> {
 87        let text = context.text
 88        let ns = text as NSString
 89        let model = DocumentModel(tree: context.tree)
 90        guard let block = model.srcBlocks.first(where: { $0.range.contains(context.caret) || $0.range.upperBound == context.caret }) else {
 91            return .failure(.message("Not in a source block"))
 92        }
 93        guard let language = block.language else { return .failure(.message("This block has no language")) }
 94        let params: Params
 95        do {
 96            params = try Params(block: block, model: model, text: ns)
 97        } catch let error as Failure {
 98            return .failure(error)
 99        } catch {
100            return .failure(.message("\(error)"))
101        }
102        let eval = params.single[":eval"]?.lowercased()
103        if eval == "never" || eval == "no" || eval == "never-export" || eval == "no-export" {
104            return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
105        }
106        for key in [":prologue", ":epilogue", ":file", ":post", ":stdin", ":cmdline", ":shebang"] where params.single[key] != nil {
107            return .failure(.message("\(key) isn't supported yet; nothing was run."))
108        }
109        if let session = params.single[":session"], session != "none" { return .failure(.message(":session isn't supported yet; nothing was run.")) }
110        if let noweb = params.single[":noweb"], !["no", "strip-export", "tangle"].contains(noweb) {
111            return .failure(.message(":noweb isn't supported yet; nothing was run."))
112        }
113        if params.single[":cache"] == "yes" { return .failure(.message(":cache isn't supported yet; nothing was run.")) }
114
115        let body = normalizedBody(block)
116        let output = params.results.contains("output")
117        let finishBase = { (kind: BabelJob.Finish.Kind) in
118            BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: block.name)
119        }
120        let vars: [(String, VarValue)]
121        do {
122            vars = try params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns)) }
123        } catch let error as Failure {
124            return .failure(error)
125        } catch {
126            return .failure(.message("\(error)"))
127        }
128        let blockText = ns.substring(with: NSRange(block.range))
129        let dir = params.single[":dir"]
130        let alwaysAsk = eval == "query"
131
132        if shells.contains(language) {
133            let valueIsExitStatus = params.results.contains("value")
134            var lines: [String] = []
135            for (name, value) in vars {
136                let s: String
137                switch value {
138                case .scalar(let v), .number(let v): s = v
139                default: return .failure(.message("Tables and lists in :var aren't supported for \(language) yet."))
140                }
141                lines.append("\(name)='" + s.replacingOccurrences(of: "'", with: "'\"'\"'") + "'")
142            }
143            let full = (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
144            let executable = language == "shell" ? options.shell : language
145            return .success(BabelJob(
146                language: language, runner: .process(executable: executable, arguments: []),
147                input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
148                block: block.range, blockText: blockText, alwaysAsk: alwaysAsk,
149                finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
150            ))
151        }
152        if language == "python" {
153            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
154            var full = (lines + [body]).joined(separator: "\n")
155            if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
156            let input: String
157            if output {
158                input = full + "\n"
159            } else {
160                input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
161                    + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
162            }
163            return .success(BabelJob(
164                language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
165                input: input, directory: dir, block: block.range, blockText: blockText, alwaysAsk: alwaysAsk,
166                finish: finishBase(.python)
167            ))
168        }
169        if language == "emacs-lisp" || language == "elisp" {
170            let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
171            let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n      ")))\n\(body)\n)"
172            let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
173            return .success(BabelJob(
174                language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
175                directory: dir, block: block.range, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
176            ))
177        }
178        if let (executable, arguments) = generic[language] {
179            guard vars.isEmpty else { return .failure(.message(":var isn't supported for \(language) yet.")) }
180            return .success(BabelJob(
181                language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
182                input: body + "\n", directory: dir, block: block.range, blockText: blockText, alwaysAsk: alwaysAsk,
183                finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: block.name)
184            ))
185        }
186        return .failure(.message("No way to run \(language) blocks yet."))
187    }
188
189    public enum Failure: Error, Equatable {
190        case message(String)
191    }
192
193    /// `org-babel--normalize-body`: without the final newline, and without the indentation
194    /// common to its lines unless `-i` keeps it.
195    static func normalizedBody(_ block: SrcBlockInfo) -> String {
196        var lines = block.body.components(separatedBy: "\n")
197        if lines.last == "" { lines.removeLast() }
198        // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
199        lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
200        if !block.switches.contains("-i") {
201            let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
202            let common = indents.min() ?? 0
203            lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
204        }
205        return lines.joined(separator: "\n")
206    }
207
208    // MARK: - Header arguments
209
210    struct Params {
211        var results: [String] = ["replace"]
212        var single: [String: String] = [:]
213        var vars: [(name: String, value: String)] = []
214        var wrap: String?
215
216        static let resultGroups: [Set<String>] = [
217            ["file", "list", "vector", "table", "scalar", "verbatim"],
218            ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
219            ["replace", "silent", "none", "discard", "append", "prepend"],
220            ["output", "value"],
221        ]
222
223        init(block: SrcBlockInfo, model: DocumentModel, text: NSString) throws {
224            var layers: [[(String, String)]] = []
225            let language = block.language ?? ""
226            func properties(_ entries: [Property]) {
227                for key in ["header-args", "header-args:\(language)"] {
228                    for entry in entries where entry.key.lowercased() == key {
229                        let pairs = Params.parse(entry.value)
230                        layers.append(pairs)
231                    }
232                }
233            }
234            properties(model.fileProperties)
235            if let heading = block.heading {
236                for index in model.ancestors(of: heading) + [heading] { properties(model.headings[index].properties) }
237            }
238            let firstLine = text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
239            if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
240                var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
241                while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
242                    rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
243                }
244                layers.append(Params.parse(rest))
245            }
246            // `#+HEADER:` lines above the block.
247            var headers: [String] = []
248            var location = block.range.lowerBound
249            while location > 0 {
250                let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
251                let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
252                guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
253                if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
254                location = previous.location
255            }
256            for header in headers { layers.append(Params.parse(header)) }
257
258            for layer in layers {
259                for (key, value) in layer {
260                    switch key {
261                    case ":results":
262                        for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
263                            if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
264                            results.removeAll { $0 == word }
265                            results.insert(word, at: 0)
266                        }
267                    case ":var":
268                        guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
269                        let name = value[..<eq].trimmingCharacters(in: .whitespaces)
270                        let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
271                        vars.removeAll { $0.name == name }
272                        vars.append((name, assigned))
273                    case ":wrap":
274                        wrap = value
275                    default:
276                        single[key] = value
277                    }
278                }
279            }
280        }
281
282        /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
283        /// parentheses.
284        static func parse(_ text: String) -> [(String, String)] {
285            var parts: [String] = []
286            var current = ""
287            var depth = 0
288            var quoted = false
289            var previous: Character = " "
290            for c in text {
291                if c == "\"" { quoted.toggle() }
292                if !quoted {
293                    if c == "(" { depth += 1 }
294                    if c == ")" { depth = max(0, depth - 1) }
295                }
296                if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
297                    parts.append(current)
298                    current = ""
299                }
300                current.append(c)
301                previous = c
302            }
303            parts.append(current)
304            var pairs: [(String, String)] = []
305            for part in parts {
306                let trimmed = part.trimmingCharacters(in: .whitespaces)
307                guard trimmed.hasPrefix(":") else { continue }
308                let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
309                var value = trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)
310                if key != ":var", value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") {
311                    value = String(value.dropFirst().dropLast())
312                }
313                pairs.append((key, value))
314            }
315            return pairs
316        }
317    }
318
319    // MARK: - Variables
320
321    enum VarValue: Equatable {
322        case scalar(String)
323        case number(String)
324        case table([[Cell]])
325        case list([Cell])
326    }
327
328    enum Cell: Equatable {
329        case text(String)
330        case number(String)
331    }
332
333    /// `org-babel--string-to-number`, keeping Emacs's printed form.
334    static func number(_ s: String) -> String? {
335        let t = s.trimmingCharacters(in: .whitespaces)
336        guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
337        if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
338            var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
339            let negative = digits.hasPrefix("-")
340            if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
341            digits = String(digits.drop { $0 == "0" })
342            if digits.isEmpty { return "0" }
343            return (negative ? "-" : "") + digits
344        }
345        guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil,
346              let d = Double(t) else { return nil }
347        return emacsFloat(d)
348    }
349
350    /// How Emacs prints a float.
351    static func emacsFloat(_ d: Double) -> String {
352        if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
353        return "\(d)"
354    }
355
356    static func cell(_ s: String) -> Cell {
357        var t = s
358        if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
359        return number(t).map(Cell.number) ?? .text(t)
360    }
361
362    /// `org-babel-ref-resolve` for literals and named tables and lists in the file.
363    static func resolve(_ value: String, model: DocumentModel, text: NSString) throws -> VarValue {
364        if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(String(value.dropFirst().dropLast())) }
365        if let n = number(value) { return .number(n) }
366        if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
367        // A named element: `#+NAME: value` above a table or list.
368        let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
369        guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
370            throw Failure.message("Can't find \(value) for :var.")
371        }
372        let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
373        var location = start
374        var rows: [[Cell]] = []
375        var items: [Cell] = []
376        while location < text.length {
377            let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
378            let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
379            let trimmed = line.trimmingCharacters(in: .whitespaces)
380            if trimmed.hasPrefix("|") {
381                if trimmed.hasPrefix("|-") { throw Failure.message("Tables with rules in :var aren't supported yet.") }
382                let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
383                rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
384            } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
385                items.append(cell(String(m.1)))
386            } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
387                if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
388                    throw Failure.message("Using a src block's result in :var isn't supported yet.")
389                }
390                break
391            } else {
392                break
393            }
394            location = NSMaxRange(lineRange)
395        }
396        if !rows.isEmpty { return .table(rows) }
397        if !items.isEmpty { return .list(items) }
398        throw Failure.message("\(value) isn't a table or list.")
399    }
400
401    /// `org-babel-python-var-to-python`.
402    static func pythonLiteral(_ value: VarValue) -> String {
403        func cell(_ c: Cell) -> String {
404            switch c {
405            case .number(let n): return n
406            case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
407            }
408        }
409        switch value {
410        case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
411        case .number(let n): return n
412        case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
413        case .table(let rows): return "[" + rows.map { "[" + $0.map(cell).joined(separator: ", ") + "]" }.joined(separator: ", ") + "]"
414        }
415    }
416
417    /// `prin1` of a string.
418    static func lispString(_ s: String, triple: Bool = false) -> String {
419        let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
420        return triple ? "\"\"" + quoted + "\"\"" : quoted
421    }
422
423    static func lispLiteral(_ value: VarValue) -> String {
424        func cell(_ c: Cell) -> String {
425            switch c {
426            case .number(let n): return n
427            case .text(let s): return lispString(s)
428            }
429        }
430        switch value {
431        case .scalar(let s): return lispString(s)
432        case .number(let n): return n
433        case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
434        case .table(let rows): return "(" + rows.map { "(" + $0.map(cell).joined(separator: " ") + ")" }.joined(separator: " ") + ")"
435        }
436    }
437
438    // MARK: - Python
439
440    /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
441    /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
442    /// otherwise `str`.
443    static let pythonFormatter = """
444    def __orgstar_format(value, path, params):
445        def rows(v):
446            if isinstance(v, dict):
447                return [(k, rows(x)) for k, x in v.items()]
448            if isinstance(v, (list, tuple)):
449                return [rows(x) for x in v]
450            return v
451        with open(path, 'w') as out:
452            if 'pp' in params:
453                import pprint
454                out.write(pprint.pformat(value))
455            elif 'list' in params and isinstance(value, dict):
456                out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
457            else:
458                if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
459                    value = rows(value)
460                out.write(str(value))
461
462    """
463
464    /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
465    static func shiftRight(_ body: String) -> String {
466        var inString: String?
467        var lines: [String] = []
468        for line in body.components(separatedBy: "\n") {
469            lines.append(inString == nil ? "    " + line : line)
470            var i = line.startIndex
471            while i < line.endIndex {
472                if let delimiter = inString {
473                    if line[i...].hasPrefix(delimiter) {
474                        inString = nil
475                        i = line.index(i, offsetBy: 3)
476                        continue
477                    }
478                } else if line[i] == "#" {
479                    break
480                } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
481                    inString = String(line[i...].prefix(3))
482                    i = line.index(i, offsetBy: 3)
483                    continue
484                } else if line[i] == "\"" || line[i] == "'" {
485                    let quote = line[i]
486                    i = line.index(after: i)
487                    while i < line.endIndex, line[i] != quote {
488                        if line[i] == "\\" { i = line.index(after: i) }
489                        if i < line.endIndex { i = line.index(after: i) }
490                    }
491                }
492                if i < line.endIndex { i = line.index(after: i) }
493            }
494        }
495        return lines.joined(separator: "\n")
496    }
497
498    // MARK: - Emacs Lisp
499
500    /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
501    /// when it is a table.
502    static func emacsScript(form: String, params: [String]) -> String {
503        """
504        ;;; -*- lexical-binding: t -*-
505        (require 'cl-lib)
506        (require 'json)
507        (let* ((result \(form))
508               (print-level nil)
509               (print-length nil)
510               (cell (lambda (c) (if (stringp c) c (format "%s" c))))
511               (tabulable (and (proper-list-p result)
512                               (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
513               (rows (and tabulable result
514                          (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
515                              (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
516                            (list (vconcat (mapcar cell result)))))))
517          (princ (json-encode `((s . ,(format "%s" result))
518                                (S . ,(format "%S" result))
519                                (string . ,(if (stringp result) t :json-false))
520                                (rows . ,(if rows (vconcat rows) :json-null))))))
521        """
522    }
523
524    // MARK: - Finishing
525
526    /// What the run produced, as Babel holds it before inserting.
527    enum Value: Equatable {
528        case none
529        case string(String)
530        /// Rows of cells; nil rows are rules.
531        case table([[String]?])
532    }
533
534    /// The edit that writes the run's result under the block, or why it can't.
535    public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
536        let ns = text as NSString
537        var blockRange = job.block
538        if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
539            let found = ns.range(of: job.blockText)
540            guard found.location != NSNotFound,
541                  ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
542                return .failure(.message("The block changed while it ran; the result wasn't written."))
543            }
544            blockRange = found.location..<NSMaxRange(found)
545        }
546        let value = Self.value(job.finish, output)
547        if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
548        let buffer = EmacsBuffer(text, point: 0, settings: settings)
549        insertResult(value, job.finish, block: blockRange, buffer: buffer)
550        return .success(TextEdit.between(text, buffer.text as String))
551    }
552
553    /// The language's result handling: `org-babel-result-cond` and the table import.
554    static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
555        let params = finish.params
556        let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
557            || params.contains("pp") || params.contains("file")
558            || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
559        switch finish.kind {
560        case .shell(let valueIsExitStatus):
561            var results = output.stdout
562            if valueIsExitStatus {
563                results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
564            }
565            if scalar { return .string(results) }
566            return importTable(results)
567        case .generic:
568            return .string(output.stdout)
569        case .python:
570            let raw = finish.output ? output.stdout : (output.resultFile ?? "")
571            if scalar { return .string(raw) }
572            return pythonValue(raw)
573        case .emacsLisp:
574            guard let data = output.stdout.data(using: .utf8),
575                  let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
576            if scalar {
577                return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
578            }
579            if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
580            if let rows = object["rows"] as? [Any] {
581                return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
582            }
583            let printed = object["S"] as? String ?? ""
584            return printed == "nil" ? .none : .string(printed)
585        }
586    }
587
588    /// `org-babel-import-elisp-from-file`.
589    static func importTable(_ results: String) -> Value {
590        guard !results.isEmpty else { return .none }
591        var lines = results.components(separatedBy: "\n")
592        if lines.last == "" { lines.removeLast() }
593        let nonEmpty = lines.filter { !$0.isEmpty }
594        let rows: [[String]]
595        if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
596            rows = lines.map { $0.components(separatedBy: "\t") }
597        } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
598            rows = lines.map(csvFields)
599        } else if lines.count == 1 {
600            rows = [[lines[0]]]
601        } else {
602            rows = lines.map { line in
603                let trimmed = line.drop { $0 == " " }
604                return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
605                    ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
606            }
607        }
608        let cells = rows.map { row in row.map { field -> String in
609            let trimmed = field.trimmingCharacters(in: .whitespaces)
610            switch cell(trimmed) {
611            case .number(let n): return n
612            case .text(let t): return t
613            }
614        } }
615        if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
616        return .table(cells)
617    }
618
619    static func csvFields(_ line: String) -> [String] {
620        var fields: [String] = []
621        var current = ""
622        var quoted = false
623        for c in line {
624            if c == "\"" {
625                quoted.toggle()
626            } else if c == ",", !quoted {
627                fields.append(current.trimmingCharacters(in: .whitespaces))
628                current = ""
629            } else {
630                current.append(c)
631            }
632        }
633        fields.append(current.trimmingCharacters(in: .whitespaces))
634        return fields
635    }
636
637    /// `org-babel-python-table-or-string`.
638    static func pythonValue(_ raw: String) -> Value {
639        guard let first = raw.first, let last = raw.last, raw.count >= 2,
640              (first == "[" && last == "]") || (first == "(" && last == ")") else {
641            if raw.isEmpty { return .string("") }
642            if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
643                return .string(String(raw.dropFirst().dropLast()))
644            }
645            if let n = number(raw) { return .string(n) }
646            return .string(raw)
647        }
648        var parser = PythonLiteral(Array(raw))
649        guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
650        func text(_ v: PythonLiteral.Node) -> String {
651            switch v {
652            case .atom(let s): return s
653            case .string(let s): return s
654            case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
655            }
656        }
657        if items.allSatisfy({ if case .list = $0 { return true }; if case .atom("None") = $0 { return true }; return false }) {
658            return .table(items.map { item -> [String]? in
659                if case .list(let cells) = item { return cells.map(text) }
660                return nil
661            })
662        }
663        return .table([items.map { if case .atom("None") = $0 { return "hline" }; return text($0) }])
664    }
665
666    struct PythonLiteral {
667        indirect enum Node: Equatable {
668            case atom(String)
669            case string(String)
670            case list([Node])
671        }
672
673        let chars: [Character]
674        var i = 0
675        init(_ chars: [Character]) { self.chars = chars }
676        var atEnd: Bool { mutating get { skip(); return i == chars.count } }
677
678        mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
679
680        mutating func parse() -> Node? {
681            skip()
682            guard i < chars.count else { return nil }
683            let c = chars[i]
684            if c == "[" || c == "(" {
685                let close: Character = c == "[" ? "]" : ")"
686                i += 1
687                var items: [Node] = []
688                skip()
689                if i < chars.count, chars[i] == close {
690                    i += 1
691                    return .list(items)
692                }
693                while true {
694                    guard let item = parse() else { return nil }
695                    items.append(item)
696                    skip()
697                    guard i < chars.count else { return nil }
698                    if chars[i] == "," {
699                        i += 1
700                        skip()
701                        if i < chars.count, chars[i] == close {
702                            i += 1
703                            return .list(items)
704                        }
705                        continue
706                    }
707                    if chars[i] == close {
708                        i += 1
709                        return .list(items)
710                    }
711                    return nil
712                }
713            }
714            if c == "'" || c == "\"" {
715                i += 1
716                var s = ""
717                while i < chars.count, chars[i] != c {
718                    if chars[i] == "\\", i + 1 < chars.count {
719                        i += 1
720                        switch chars[i] {
721                        case "n": s.append("\n")
722                        case "t": s.append("\t")
723                        default: s.append(chars[i])
724                        }
725                    } else {
726                        s.append(chars[i])
727                    }
728                    i += 1
729                }
730                guard i < chars.count else { return nil }
731                i += 1
732                return .string(s)
733            }
734            var s = ""
735            while i < chars.count, !",)] \n".contains(chars[i]) {
736                s.append(chars[i])
737                i += 1
738            }
739            guard !s.isEmpty else { return nil }
740            return .atom(number(s) ?? s)
741        }
742    }
743
744    // MARK: - Inserting
745
746    static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
747
748    /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
749    /// keyword, added when there is none.
750    static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
751        let ns = buffer.text
752        if let name = finish.name {
753            let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
754            let regex = try! NSRegularExpression(pattern: pattern)
755            for m in regex.matches(in: ns as String, range: NSRange(location: 0, length: ns.length)) {
756                // Not the name of another block.
757                return m.range.location
758            }
759        } else {
760            // The element after the block, past blank lines.
761            var location = block.upperBound
762            while location < ns.length {
763                let line = ns.lineRange(for: NSRange(location: location, length: 0))
764                let content = ns.substring(with: line)
765                if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
766                    location = NSMaxRange(line)
767                    continue
768                }
769                if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
770                    return line.location
771                }
772                break
773            }
774        }
775        // A new keyword after the block.
776        buffer.point = min(block.upperBound, buffer.length)
777        buffer.skipBackward([32, 9, 10, 13])
778        buffer.forwardLine(1)
779        if !buffer.bolp { buffer.insert("\n") }
780        let indent = buffer.saveExcursion { () -> String in
781            buffer.point = block.lowerBound
782            let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
783            return String(line.prefix { $0 == " " || $0 == "\t" })
784        }
785        buffer.insert("\n")
786        let keywordLine = buffer.point
787        buffer.insert(indent + "#+RESULTS:" + (finish.name.map { " " + $0 } ?? "") + "\n")
788        if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
789            buffer.saveExcursion { buffer.insert("\n") }
790        }
791        return keywordLine
792    }
793
794    /// `org-babel-result-end` with point at the start of the result.
795    static func resultEnd(_ buffer: EmacsBuffer) -> Int {
796        let start = buffer.point
797        let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
798        if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
799        if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
800            return min(buffer.length, buffer.lineEnd(start) + 1)
801        }
802        let tree = OrgParser.parse(buffer.text as String)
803        var node = tree.root
804        var found: SyntaxNode?
805        while let child = node.child(containing: start) {
806            if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
807                if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
808                    found = child
809                    break
810                }
811            }
812            node = child
813        }
814        guard let element = found else { return start }
815        var end = element.range.upperBound
816        while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
817        return min(buffer.length, buffer.lineEnd(end) + 1)
818    }
819
820    /// `org-babel-insert-result` for a src block.
821    static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
822        let params = finish.params
823        let keyword = resultsLine(finish, block: block, buffer: buffer)
824        buffer.point = keyword
825        let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
826        buffer.forwardLine(1)
827        if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
828        var beg = buffer.point
829        if params.contains("replace") {
830            buffer.deleteRegion(beg, resultEnd(buffer))
831            buffer.point = beg
832        } else if params.contains("append") {
833            buffer.point = resultEnd(buffer)
834            beg = buffer.point
835        }
836        var tabulated = false
837        switch value {
838        case .none:
839            break
840        case .string(var s) where params.contains("list"):
841            if s.last != "\n" { s += "\n" }
842            let items = s.split(separator: "\n", omittingEmptySubsequences: true)
843            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
844        case .table(let rows) where params.contains("list"):
845            let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
846            buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
847        case .table(let rows):
848            tabulated = true
849            let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
850            let start = buffer.point
851            buffer.insert(lines.joined(separator: "\n") + "\n")
852            buffer.point = start
853            buffer.tableAlign()
854            buffer.point = buffer.tableEnd()
855        case .string(var s):
856            if !s.isEmpty, s.last != "\n" { s += "\n" }
857            buffer.insert(s)
858        }
859        let end = buffer.marker(buffer.point, advances: true)
860        defer { buffer.release(end) }
861        func wrap(_ open: String, _ close: String, escape: Bool) {
862            buffer.point = end.position
863            buffer.insert(close + "\n")
864            buffer.point = beg
865            buffer.insert(open + "\n")
866            if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
867        }
868        if let wrapValue = finish.wrap {
869            let full = wrapValue.isEmpty ? "results" : wrapValue
870            let type = String(full.split(separator: " ").first ?? "results")
871            if type.lowercased() != "nil", type.lowercased() != "no" {
872                wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
873            }
874        } else if params.contains("html") {
875            wrap("#+begin_export html", "#+end_export", escape: true)
876        } else if params.contains("latex") {
877            wrap("#+begin_export latex", "#+end_export", escape: true)
878        } else if params.contains("org") {
879            wrap("#+begin_src org", "#+end_src", escape: true)
880        } else if params.contains("code") {
881            wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
882        } else if params.contains("raw") {
883            // As inserted.
884        } else if params.contains("drawer") {
885            wrap(":results:", ":end:", escape: false)
886        } else if !tabulated, !params.contains("list") {
887            examplify(buffer, beg, end.position)
888        }
889        if indent > 0, !(tabulated && params.contains("append")) {
890            buffer.point = beg
891            while buffer.point < end.position {
892                if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
893                if buffer.forwardLine(1) != 0 { break }
894            }
895        }
896    }
897
898    /// `org-escape-code-in-region`.
899    static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
900        buffer.point = start
901        let stop = buffer.marker(end)
902        defer { buffer.release(stop) }
903        while buffer.point < stop.position {
904            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
905            if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
906                buffer.point += line[..<m.1.startIndex].utf16.count
907                buffer.insert(",")
908            }
909            if buffer.forwardLine(1) != 0 { break }
910        }
911    }
912
913    /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
914    static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
915        let text = buffer.substring(beg, end)
916        var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0)
917        if text.isEmpty { size = 0 }
918        guard size > 0 else { return }
919        if size < 10 {
920            buffer.point = beg
921            for _ in 0..<size {
922                buffer.point = buffer.lineStart(buffer.point)
923                buffer.insert(": ")
924                buffer.forwardLine(1)
925            }
926            return
927        }
928        let endMarker = buffer.marker(end)
929        defer { buffer.release(endMarker) }
930        buffer.point = beg
931        buffer.insert("#+begin_example\n")
932        escapeCode(buffer, from: buffer.point, to: endMarker.position)
933        buffer.point = endMarker.position
934        if !buffer.bolp { buffer.insert("\n") }
935        buffer.insert("#+end_example")
936        if !buffer.eolp { buffer.insert("\n") }
937    }
938}
939
940/// C-c C-c in a src block: `org-babel-execute-src-block`.
941public struct ExecuteSrcBlock: OrgCommand {
942    public init() {}
943    public var id: String { "org.babel.execute" }
944    public var title: String { "Run Source Block" }
945    public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) }
946    public func run(in context: EditContext) -> CommandStep {
947        switch Babel.plan(context) {
948        case .success(let job): return .external(.babel(job))
949        case .failure(.message(let message)): return .failed(message)
950        }
951    }
952}