Sources/OrgCore/Compute/Babel.swift

704 lines · 41198 bytes

  1import CryptoKit
  2import Foundation
  3
  4// Babel (ob-core.el, ob-shell.el, ob-python.el, ob-emacs-lisp.el, Org 9.8.7): executing a src
  5// block is planned here, run by the platform, and finished here. The plan resolves header
  6// arguments and refuses anything that would make the run differ from Emacs's; the finish turns
  7// the output into a result the way `org-babel-insert-result` writes it.
  8
  9/// A src block run for the platform to carry out.
 10public struct BabelJob: Sendable, Equatable {
 11    public enum Runner: Sendable, Equatable {
 12        /// An interpreter reading the program on standard input.
 13        case process(executable: String, arguments: [String])
 14        /// `emacs --batch` loading `input` as a script.
 15        case emacs
 16        /// A long-running interpreter named by `:session`: a shell gets `input` as commands, the
 17        /// others run `input` as a program where earlier ones left their variables.
 18        case session(name: String, executable: String, kind: SessionKind)
 19    }
 20
 21    public enum SessionKind: String, Sendable, Equatable {
 22        case shell, python, ruby, node, r
 23    }
 24
 25    public let language: String
 26    public let runner: Runner
 27    /// Standard input, or the Emacs script. `Babel.resultFileToken` stands for a file the runner
 28    /// creates; its contents come back as `BabelOutput.resultFile`.
 29    public let input: String
 30    /// `:dir`, relative to the file's folder; nil for the folder itself.
 31    public let directory: String?
 32    /// The block as it was planned, to find it again when the run ends.
 33    public let block: Range<Int>
 34    public let blockText: String
 35    /// Asks every time (`:eval query`) rather than trusting by content.
 36    public let alwaysAsk: Bool
 37    public let finish: Finish
 38    /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output.
 39    public var needs: [Need] = []
 40    /// With `needs`: the text of every block the run may execute, the one asked about and
 41    /// those its references reach. A later job for a block not among them is refused.
 42    public internal(set) var approved: [String] = []
 43    /// Values of the references resolved so far, and how to plan again.
 44    var resolved: [String: Babel.VarValue] = [:]
 45    var caret = 0
 46    var options = Babel.Options()
 47    /// A script for the runner to write to an executable file, for `Babel.scriptFileToken`.
 48    public internal(set) var script: String?
 49    /// Programs the run needs: for each list, one of them on PATH.
 50    public internal(set) var programs: [[String]] = []
 51    /// An Emacs Lisp block's form, for `Babel.evaluateNatively`.
 52    public internal(set) var lispForm: String?
 53    /// A Lisp header value couldn't be evaluated without the file's path: plan again with
 54    /// `Babel.replan` before running.
 55    public internal(set) var needsFile = false
 56    /// A calc block, for `Babel.evaluateCalc`.
 57    public internal(set) var calc: Babel.CalcBlock?
 58    /// An sqlite block's `sqlite3` command line, for `SQLiteBlocks`.
 59    public internal(set) var sqlite: Babel.SQLiteCommand?
 60    /// A dot or mermaid block's source, `:file` and `:cmdline`, for drawing it without the program.
 61    public internal(set) var diagram: Babel.Diagram?
 62    /// Files the runner writes, each where its key stands in `input`: `:var` tables as CSV.
 63    public internal(set) var dataFiles: [String: String] = [:]
 64
 65    public struct Need: Sendable, Equatable {
 66        /// The `:var` value, `name` or `name(args)`.
 67        public let reference: String
 68        public let job: BabelJob
 69    }
 70
 71    public struct Finish: Sendable, Equatable {
 72        /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`.
 73        /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from
 74        /// the result file for ruby and the output for js.
 75        /// `calc`: the value as JSON, `{"value": …}` or `{"rows": […]}`. `sqlite`: the output of
 76        /// `sqlite3`, read as CSV when `csv`, with a rule after the first row when `headers`.
 77        enum Kind: Sendable, Equatable {
 78            case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool, session: Bool = false), calc
 79            case sqlite(csv: Bool, headers: Bool)
 80
 81            /// ob-calc and ob-sqlite give a list of rows, never a flat list.
 82            var givesRows: Bool {
 83                switch self {
 84                case .calc, .sqlite: true
 85                default: false
 86                }
 87            }
 88        }
 89        let kind: Kind
 90        var language = ""
 91        public internal(set) var params: [String]
 92        public let output: Bool
 93        let wrap: String?
 94        let name: String?
 95        /// An inline block: the result goes after it, in `{{{results(…)}}}`.
 96        var inline = false
 97        /// `:file` (under `:output-dir`) with `:results file`, and `:file-desc`.
 98        public internal(set) var file: String?
 99        var fileDescription: String?
100        /// The program writes `file` itself, as graphics languages do.
101        var writesFile = false
102        /// `:cache yes`: the hash for the `#+RESULTS[…]:` line.
103        var hash: String?
104        /// Column and row names a table `:var` gave up, put back on a table result
105        /// (`org-babel-reassemble-table`).
106        var colnames: [String]?
107        var rownames: [String]?
108    }
109}
110
111public struct BabelOutput: Sendable, Equatable {
112    public var stdout: String
113    public var resultFile: String?
114    /// What the program wrote to standard error, and its exit status: Emacs shows them in
115    /// `*Org-Babel Error Output*` and still inserts the results.
116    public var stderr: String
117    public var status: Int32
118    public init(stdout: String, resultFile: String? = nil, stderr: String = "", status: Int32 = 0) {
119        self.stdout = stdout
120        self.resultFile = resultFile
121        self.stderr = stderr
122        self.status = status
123    }
124
125    /// A line for the message area when the program failed or complained, else nil.
126    public var problem: String? {
127        let first = stderr.split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
128        switch (status, first) {
129        case (0, nil): return nil
130        case (0, let line?): return line
131        case (let code, nil): return "Exited with status \(code)"
132        case (let code, let line?): return "Exited with status \(code): \(line)"
133        }
134    }
135}
136
137public enum Babel {
138    public static let resultFileToken = "__ORGSTAR_RESULT_FILE__"
139    /// Stands, in a job's arguments, for the executable file the runner writes `job.script` to.
140    public static let scriptFileToken = "__ORGSTAR_SCRIPT_FILE__"
141    static let shells: Set<String> = ["sh", "bash", "zsh", "shell", "fish", "ksh", "dash", "ash", "csh", "mksh", "posh"]
142    static let generic: [String: (String, [String])] = [
143        "ruby": ("ruby", []), "js": ("node", []), "javascript": ("node", []), "R": ("Rscript", ["-"]),
144        "awk": ("awk", ["-f", "/dev/stdin"]),
145    ]
146
147    public struct Options: Sendable, Equatable {
148        public var python = "python3"
149        /// `shell-file-name`, from `SHELL` as Emacs sets it: runs blocks in the `shell` language
150        /// and chooses how variables are written in the `:cache` hash.
151        public var shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/sh"
152        /// The file the block is in, for Lisp header values that use it.
153        public var file: String?
154        public init() {}
155    }
156
157    // MARK: - Planning
158
159    /// The run for the src block at the caret, or why it can't run.
160    public static func plan(_ context: EditContext, options: Options = Options()) -> Result<BabelJob, Failure> {
161        plan(context, options: options, resolved: [:])
162    }
163
164    /// Plans the block again with the value of the block `job` needed: the output of
165    /// `need.job`, as `org-babel-ref-resolve` reads it.
166    public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
167        var resolved = job.resolved
168        resolved[need.reference] = varValue(need.job.finish, output)
169        let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
170        return plan(context, options: job.options, resolved: resolved)
171    }
172
173    /// Plans `job`'s block again knowing the file it is in.
174    public static func replan(_ job: BabelJob, file: String, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
175        var options = job.options
176        options.file = file
177        let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
178        return plan(context, options: options, resolved: job.resolved)
179    }
180
181    static func plan(_ context: EditContext, options: Options, resolved: [String: VarValue]) -> Result<BabelJob, Failure> {
182        let text = context.text
183        let ns = text as NSString
184        let model = DocumentModel(tree: context.tree)
185        let refs = References(resolved: resolved, options: options)
186        func located(_ result: Result<BabelJob, Failure>) -> Result<BabelJob, Failure> {
187            result.map { job in
188                var job = job
189                (job.caret, job.resolved, job.options) = (context.caret, resolved, options)
190                return job
191            }
192        }
193        do {
194            if let block = model.srcBlocks.first(where: { $0.range.contains(context.caret) || $0.range.upperBound == context.caret }) {
195                return located(plan(block, params: try Params(block: block, model: model, text: ns), model: model, text: ns, options: options,
196                                    location: block.range, name: block.name, refs: refs))
197            }
198            if let call = try callAt(context.caret, model: model, text: ns) {
199                return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: call.name, refs: refs))
200            }
201            if let call = try inlineCallAt(context.caret, tree: context.tree, model: model, text: ns) {
202                return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: nil, inline: true, refs: refs))
203            }
204            if let inline = try inlineAt(context.caret, tree: context.tree, model: model, text: ns) {
205                return located(plan(inline.block, params: inline.params, model: model, text: ns, options: options, location: inline.block.range, name: nil, inline: true, refs: refs))
206            }
207        } catch let error as Failure {
208            return .failure(error)
209        } catch {
210            return .failure(.message("\(error)"))
211        }
212        return .failure(.message("Not in a source block"))
213    }
214
215    /// The `#+CALL:` line at `offset`: the block it names, with the call's inside header, its
216    /// arguments as `:var` and its end header over the block's own (`org-babel-lob-get-info`).
217    static func callAt(_ offset: Int, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>, name: String?)? {
218        let lineRange = text.lineRange(for: NSRange(location: min(offset, text.length), length: 0))
219        let line = text.substring(with: lineRange)
220        guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+CALL:[ \t]*([^\s(\[]+)(?:\[([^\]]*)\])?\((.*?)\)[ \t]*(.*?)[ \t]*\n?$/#) else { return nil }
221        let name = String(m.1)
222        guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
223        var extra = [lobDefaults] + callProperties(block, at: lineRange.location, model: model)
224        if let inside = m.2 { extra.append(Params.parse(String(inside))) }
225        extra.append(splitArguments(String(m.3)).map { (":var", $0) })
226        if !m.4.isEmpty { extra.append(Params.parse(String(m.4))) }
227        // The call's own #+NAME names its results.
228        var callName: String?
229        if lineRange.location > 0 {
230            let previous = text.substring(with: text.lineRange(for: NSRange(location: lineRange.location - 1, length: 0)))
231            callName = previous.firstMatch(of: #/(?i)^[ \t]*#\+NAME:[ \t]*(\S+)/#).map { String($0.1) }
232        }
233        let location = lineRange.location..<NSMaxRange(lineRange)
234        return (block, try Params(block: block, model: model, text: text, extra: extra), location, callName)
235    }
236
237    /// The inline `call_NAME[INSIDE](ARGS)[END]` at `offset`: like `#+CALL`, with the result
238    /// after the call.
239    static func inlineCallAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>)? {
240        var node = tree.root
241        var found: SyntaxNode?
242        while let child = node.child(containing: offset) {
243            if child.kind == .inlineBabelCall { found = child }
244            node = child
245        }
246        guard let object = found, let m = object.text.firstMatch(of: /^call_([^()\[\]\s]+)(?:\[([^\]]*)\])?\((.*?)\)(?:\[([^\]]*)\])?$/) else { return nil }
247        let name = String(m.1)
248        guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
249        var extra = [lobDefaults] + callProperties(block, at: object.range.lowerBound, model: model)
250        if let inside = m.2 { extra.append(Params.parse(String(inside))) }
251        extra.append(splitArguments(String(m.3)).map { (":var", $0) })
252        if let end = m.4 { extra.append(Params.parse(String(end))) }
253        return (block, try Params(block: block, model: model, text: text, extra: extra), object.range)
254    }
255
256    /// The `header-args` properties where a call is, in the called block's language, which
257    /// `org-babel-lob-get-info` puts after `lobDefaults`.
258    static func callProperties(_ block: SrcBlockInfo, at location: Int, model: DocumentModel) -> [[(String, String)]] {
259        let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location }
260        return Params.propertyLayers(language: block.language ?? "", heading: heading, model: model)
261    }
262
263    /// `org-babel-default-lob-header-args`, over the called block's own header arguments.
264    static let lobDefaults = [(":exports", "results")]
265
266    /// `org-babel-default-header-args:LANG` in Org 9.8.7 other than `:exports`.
267    static let languageDefaults = ["java": [(":results", "output"), (":dir", ".")]]
268
269    /// `:exports` from the language's `org-babel-default-header-args:LANG` in Org 9.8.7.
270    static let languageExports = ["dot": "results", "plantuml": "results", "ditaa": "results", "gnuplot": "results",
271                                  "latex": "results", "lilypond": "results"]
272
273    /// What export shows of the src block, `#+CALL:` line, inline call or inline src block
274    /// starting at `offset` (`org-babel-exp-process-buffer`): `code`, `results`, `both` or
275    /// `none`, from the header arguments as evaluation resolves them. Calls never show code.
276    /// Nil when nothing there runs. Without `languages`, as in `emacs -Q`, no language's
277    /// `ob-` library is loaded to give its own default.
278    public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString, languages: Bool = true) -> String? {
279        func value(_ params: Params?, language: String?) -> String {
280            (params?.single[":exports"] ?? language.flatMap { languages ? languageExports[$0] : nil } ?? "code").lowercased()
281        }
282        if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) {
283            return value(try? Params(block: block, model: model, text: text), language: block.language)
284        }
285        let line = text.substring(with: text.lineRange(for: NSRange(location: min(offset, text.length), length: 0)))
286        let call: Params?
287        if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil {
288            call = (try? callAt(offset, model: model, text: text))?.params
289        } else if tree.root.descendants().contains(where: { $0.kind == .inlineBabelCall && $0.range.lowerBound == offset }) {
290            // `org-babel-remove-result` only takes away `#+RESULTS:`, so an inline call's
291            // `{{{results(...)}}}` stays whatever `:exports` says.
292            return "results"
293        } else if let inline = try? inlineAt(offset, tree: tree, model: model, text: text), inline.block.range.lowerBound == offset {
294            return value(inline.params, language: inline.block.language)
295        } else {
296            return nil
297        }
298        // `org-babel-exp-code` for a call is `org-babel-exp-call-line-template`, empty.
299        switch call?.single[":exports"]?.lowercased() ?? "results" {
300        case "both", "results": return "results"
301        default: return "none"
302        }
303    }
304
305    /// Call arguments split on commas outside quotes and parentheses.
306    static func splitArguments(_ s: String) -> [String] {
307        var parts: [String] = []
308        var current = ""
309        var depth = 0
310        var quoted = false
311        for c in s {
312            if c == "\"" { quoted.toggle() }
313            if !quoted, c == "(" { depth += 1 }
314            if !quoted, c == ")" { depth -= 1 }
315            if c == ",", !quoted, depth == 0 {
316                parts.append(current)
317                current = ""
318            } else {
319                current.append(c)
320            }
321        }
322        parts.append(current)
323        return parts.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
324    }
325
326    /// The inline `src_LANG[HEADERS]{BODY}` at `offset`.
327    static func inlineAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params)? {
328        var node = tree.root
329        var found: SyntaxNode?
330        while let child = node.child(containing: offset) {
331            if child.kind == .inlineSourceBlock { found = child }
332            node = child
333        }
334        guard let object = found, let m = object.text.firstMatch(of: /^src_([^\s\[{]+)(?:\[([^\]]*)\])?\{(.*)\}$/) else { return nil }
335        let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= object.range.lowerBound }
336        let block = SrcBlockInfo(range: object.range, heading: heading, name: nil, language: String(m.1), switches: [], body: String(m.3), headerArguments: [:])
337        let extra = m.2.map { [Params.parse(String($0))] } ?? []
338        return (block, try Params(block: block, model: model, text: text, defaults: [(":exports", "results"), (":hlines", "yes")], extra: extra, inline: true))
339    }
340
341    /// What `:var` references resolve to while planning.
342    struct References {
343        var resolved: [String: VarValue]
344        var options: Options
345        /// Blocks being planned for a reference, to stop cycles.
346        var visiting: Set<String> = []
347    }
348
349    /// A reference to a block that has to run first.
350    struct Needed: Error {
351        let need: BabelJob.Need
352    }
353
354    static func plan(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
355                     location: Range<Int>, name: String?, inline: Bool = false, refs: References? = nil, useCache: Bool = true) -> Result<BabelJob, Failure> {
356        var evaluated = params
357        evaluated.evaluateLisp(file: options.file)
358        let needsFile = options.file == nil && evaluated.lisp.contains { evaluated.evaluated[$0] == nil }
359        return planBlock(block, params: params, model: model, text: ns, options: options, location: location, name: name, inline: inline,
360                         refs: refs, useCache: useCache).map { job in
361            var job = job
362            job.needsFile = needsFile
363            return job
364        }
365    }
366
367    static func planBlock(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
368                          location: Range<Int>, name: String?, inline: Bool, refs: References?, useCache: Bool) -> Result<BabelJob, Failure> {
369        let refs = refs ?? References(resolved: [:], options: options)
370        var params = params
371        params.evaluateLisp(file: options.file)
372        let needsFile = options.file == nil && params.lisp.contains { params.evaluated[$0] == nil }
373        guard let language = block.language else { return .failure(.message("This block has no language")) }
374        let eval = params.single[":eval"]?.lowercased()
375        if eval == "never" || eval == "no" {
376            return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
377        }
378        let compiled = expandedLanguages.contains(language)
379        if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled {
380            return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
381        }
382        let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp", "calc", "sqlite"].contains(language) || generic[language] != nil
383        for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
384            && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
385            return .failure(.message("\(key) isn't supported yet; nothing was run."))
386        }
387        // The compiled languages' `org-babel-execute:` ignore `:session`.
388        let session = compiled ? nil : params.single[":session"].flatMap { $0 == "none" ? nil : ($0.isEmpty ? "*\(language)*" : $0) }
389        if session != nil, !shells.contains(language), !["python", "ruby", "js", "javascript", "R"].contains(language) {
390            return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
391        }
392        var body = normalizedBody(block)
393        if nowebEvaluates(params.single[":noweb"]) {
394            do {
395                body = try expandNoweb(block, params: params, model: model, text: ns)
396            } catch let error as Failure {
397                return .failure(error)
398            } catch {
399                return .failure(.message("\(error)"))
400            }
401        }
402        let output = params.results.contains("output")
403        let file = params.single[":file"].map { name in
404            params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
405        }
406        let toFile = params.results.contains("file")
407        var hash: String?
408        var tables = Tables()
409        let finishBase = { (kind: BabelJob.Finish.Kind) in
410            BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: name, inline: inline,
411                            file: toFile ? file : nil, fileDescription: params.single[":file-desc"], hash: hash,
412                            colnames: tables.picked(tables.colnames, ":colnames", params), rownames: tables.picked(tables.rownames, ":rownames", params))
413        }
414        let vars: [(String, VarValue)]
415        var stdin: VarValue?
416        do {
417            tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }, params: params)
418            vars = tables.vars
419            stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) }
420        } catch let needed as Needed {
421            // Asked about once, with every block the references reach; asked every time when
422            // any of them has `:eval query`.
423            let reached = referencedBlocks(params, model: model, text: ns, seen: [])
424            let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
425            let query = eval == "query" || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
426            var job = BabelJob(
427                language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
428                block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finishBase(.generic), needs: [needed.need]
429            )
430            job.approved = texts
431            return .success(job)
432        } catch let error as Failure {
433            return .failure(error)
434        } catch {
435            return .failure(.message("\(error)"))
436        }
437        if useCache, !inline, !needsFile, params.single[":cache"] == "yes" {
438            do {
439                let state = try cacheState(language: language, params: params, tables: tables, body: body, location: location, name: name,
440                                           call: location != block.range, text: ns, options: options, model: model)
441                if state.current { return .failure(.message(cachedMessage(state.value))) }
442                // Appended or prepended results accumulate, so they carry no hash.
443                if params.results.contains("replace") { hash = state.hash }
444            } catch let error as Failure {
445                return .failure(error)
446            } catch {
447                return .failure(.message("\(error)"))
448            }
449        }
450        let blockText = ns.substring(with: NSRange(location))
451        let dir = params.single[":dir"]
452        let alwaysAsk = eval == "query"
453
454        if shells.contains(language) {
455            let valueIsExitStatus = params.results.contains("value")
456            let executable = language == "shell" ? options.shell : language
457            let lines = shellAssignments(vars, shell: executable, params: params)
458            let cmdline = params.single[":cmdline"]
459            let shebang = params.single[":shebang"].flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil }
460            if stdin != nil || cmdline != nil || (session == nil && shebang != nil) {
461                // `org-babel-sh-evaluate`: an executable script, run by the shell with the
462                // command line after it and `:stdin` as its input; the result is its standard
463                // output, or its exit status for `:results value`. `:stdin` and `:cmdline`
464                // run it even with a session, which the script doesn't use.
465                var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n"
466                if params.single[":padline"] != "no" { script += "\n" }
467                script += expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
468                let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "")
469                var job = BabelJob(
470                    language: language, runner: .process(executable: executable, arguments: ["-c", command]),
471                    input: stdin.map { shellString($0) } ?? "", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
472                    finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
473                )
474                job.script = script
475                return .success(job)
476            }
477            let full = expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
478            return .success(BabelJob(
479                language: language, runner: session.map { .session(name: $0, executable: executable, kind: .shell) } ?? .process(executable: executable, arguments: []),
480                input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
481                block: location, blockText: blockText, alwaysAsk: alwaysAsk,
482                finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
483            ))
484        }
485        if language == "python", let session {
486            // `org-babel-python--eval-ast`: the body at top level in the session, the value its
487            // last expression's.
488            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
489            let source = expandGeneric(body, lines, params)
490            let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
491            let program: String
492            if output {
493                program = "exec(compile(\(literal), '<org-babel>', 'exec'), globals())\n"
494            } else {
495                program = pythonFormatter + """
496                    import ast as __orgstar_ast
497                    __orgstar_tree = __orgstar_ast.parse(\(literal))
498                    __orgstar_last = None
499                    if __orgstar_tree.body and isinstance(__orgstar_tree.body[-1], __orgstar_ast.Expr):
500                        __orgstar_last = __orgstar_ast.Expression(__orgstar_tree.body.pop().value)
501                    exec(compile(__orgstar_tree, '<org-babel>', 'exec'), globals())
502                    __orgstar_format(eval(compile(__orgstar_last, '<org-babel>', 'eval'), globals()) if __orgstar_last else None, '\(resultFileToken)', [
503                    """ + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
504            }
505            return .success(BabelJob(
506                language: language, runner: .session(name: session, executable: params.single[":python"] ?? options.python, kind: .python),
507                input: program, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.python)
508            ))
509        }
510        if language == "python" {
511            let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
512            var full = expandGeneric(body, lines, params)
513            if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
514            let input: String
515            if output {
516                input = full + "\n"
517            } else {
518                input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
519                    + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
520            }
521            return .success(BabelJob(
522                language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
523                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
524                finish: finishBase(.python)
525            ))
526        }
527        if language == "emacs-lisp" || language == "elisp" {
528            let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
529            // `org-babel-expand-body:emacs-lisp` adds the prologue and epilogue only with variables.
530            let prologue = params.single[":prologue"].map { $0 + "\n      " } ?? ""
531            let epilogue = params.single[":epilogue"].map { "\n      " + $0 + "\n" } ?? ""
532            let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n      ")))\n\(prologue)\(body)\(epilogue)\n)"
533            let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
534            var job = BabelJob(
535                language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
536                directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
537            )
538            job.lispForm = form
539            return .success(job)
540        }
541        if language == "calc" {
542            do {
543                return .success(try calcJob(body: body, vars: vars, params: params, finish: finishBase(.calc), directory: dir, block: location,
544                                            blockText: blockText, alwaysAsk: alwaysAsk))
545            } catch let error as Failure {
546                return .failure(error)
547            } catch {
548                return .failure(.message("\(error)"))
549            }
550        }
551        if language == "sqlite" {
552            do {
553                return .success(try sqliteJob(body: body, vars: vars, params: params, finishBase: finishBase, directory: dir, block: location,
554                                              blockText: blockText, alwaysAsk: alwaysAsk))
555            } catch let error as Failure {
556                return .failure(error)
557            } catch {
558                return .failure(.message("\(error)"))
559            }
560        }
561        if ["dot", "plantuml", "mermaid"].contains(language) {
562            // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
563            guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
564            let quoted = "'" + file.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
565            let ext = (file as NSString).pathExtension.isEmpty ? "png" : (file as NSString).pathExtension
566            let cmdline = params.single[":cmdline"].map { " " + $0 } ?? ""
567            var input = body + "\n"
568            let command: String
569            switch language {
570            case "dot":
571                command = "dot\(cmdline) -T\(ext) -o \(quoted)"
572            case "plantuml":
573                if body.range(of: "^[ \\t]*@start", options: .regularExpression) == nil { input = "@startuml\n" + body + "\n@enduml\n" }
574                command = "plantuml\(cmdline) -p -t\(ext) > \(quoted)"
575            default:
576                command = "f=$(mktemp).mmd; cat > \"$f\"; mmdc\(cmdline) -i \"$f\" -o \(quoted); s=$?; rm -f \"$f\"; exit $s"
577            }
578            var finish = finishBase(.generic)
579            finish.file = file
580            finish.writesFile = true
581            finish.params = params.results.filter { !["table", "scalar", "verbatim", "list", "vector"].contains($0) } + (params.results.contains("file") ? [] : ["file"])
582            var job = BabelJob(
583                language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", command]),
584                input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish
585            )
586            if language != "plantuml" { job.diagram = Diagram(source: body, file: file, cmdline: params.single[":cmdline"]) }
587            return .success(job)
588        }
589        if compiled {
590            do {
591                let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound }
592                let run = try compiledRun(language: language, body: body, tables: tables, params: params,
593                                          properties: { inheritedProperty($0, heading: heading, model: model) })
594                var finish = finishBase(.compiled)
595                // ob-clojure doesn't reassemble tables.
596                if language == "clojure" { (finish.colnames, finish.rownames) = (nil, nil) }
597                var job = BabelJob(language: language, runner: .process(executable: "/bin/sh", arguments: [scriptFileToken]), input: run.source,
598                                   directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
599                job.script = run.script
600                job.programs = run.programs
601                return .success(job)
602            } catch let error as Failure {
603                return .failure(error)
604            } catch {
605                return .failure(.message("\(error)"))
606            }
607        }
608        if let (executable, arguments) = generic[language] {
609            switch language {
610            case "ruby":
611                let full = expandGeneric(body, vars.map { "\($0.0)=\(rubyLiteral($0.1))" }, params)
612                if let session {
613                    return .success(BabelJob(
614                        language: language, runner: .session(name: session, executable: params.single[":ruby"] ?? executable, kind: .ruby),
615                        input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: false, session: true))
616                    ))
617                }
618                return .success(BabelJob(
619                    language: language, runner: .process(executable: params.single[":ruby"] ?? executable, arguments: arguments),
620                    input: output ? full : rubyWrapper(full, pp: params.results.contains("pp")), directory: dir, block: location, blockText: blockText,
621                    alwaysAsk: alwaysAsk, finish: finishBase(.script(js: false))
622                ))
623            case "js", "javascript":
624                let full = expandGeneric(body, vars.map { "var \($0.0)=\(jsLiteral($0.1));" }, params)
625                if let session {
626                    return .success(BabelJob(
627                        language: language, runner: .session(name: session, executable: params.single[":cmd"] ?? executable, kind: .node),
628                        input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true))
629                    ))
630                }
631                // `org-babel-execute:js`: the program in a file, run as `:cmd FILE`, with the
632                // newline `org-babel-eval` sends as its input.
633                var job = BabelJob(
634                    language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: [scriptFileToken]),
635                    input: "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true))
636                )
637                job.script = output ? full : jsWrapper(full)
638                return .success(job)
639            case "awk":
640                // `org-babel-expand-body:awk`; the variables go on the command line.
641                let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
642                return .success(BabelJob(
643                    language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", awkCommand(vars, params: params)]),
644                    input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
645                    finish: finishBase(.shell(valueIsExitStatus: false))
646                ))
647            default:
648                let lines = language == "R" ? vars.map { name, value in
649                    rAssignment(name, value, colnames: tables.colnames.first { $0.0 == name }?.1, colnamesYes: params.single[":colnames"] == "yes",
650                                rownamesYes: params.single[":rownames"] == "yes")
651                } : []
652                // An R session runs `R` itself, which reads its commands as they come.
653                let runner: BabelJob.Runner = session.map { .session(name: $0, executable: params.single[":cmd"] ?? "R", kind: .r) }
654                    ?? .process(executable: params.single[":cmd"] ?? executable, arguments: arguments)
655                return .success(BabelJob(
656                    language: language, runner: runner,
657                    input: expandGeneric(body, lines, params) + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
658                    finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline, hash: hash)
659                ))
660            }
661        }
662        return .failure(.message("No way to run \(language) blocks yet."))
663    }
664
665    public enum Failure: Error, Equatable {
666        case message(String)
667    }
668
669    /// A dot or mermaid block: what to draw, and the file to draw it into.
670    public struct Diagram: Sendable, Equatable {
671        public let source: String
672        public let file: String
673        public let cmdline: String?
674    }
675
676}
677
678/// C-c C-c in a src block: `org-babel-execute-src-block`.
679public struct ExecuteSrcBlock: OrgCommand {
680    public init() {}
681    public var id: String { "org.babel.execute" }
682    public var title: String { "Run Source Block" }
683    public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
684
685    /// On a `#+CALL:` line, an inline `call_` or an inline `src_` block.
686    static func atCallOrInline(_ context: EditContext) -> Bool {
687        let ns = context.text as NSString
688        let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
689        if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
690        var node = context.tree.root
691        while let child = node.child(containing: context.caret) {
692            if child.kind == .inlineSourceBlock || child.kind == .inlineBabelCall { return true }
693            node = child
694        }
695        return false
696    }
697
698    public func run(in context: EditContext) -> CommandStep {
699        switch Babel.plan(context) {
700        case .success(let job): return .external(.babel(job))
701        case .failure(.message(let message)): return .failed(message)
702        }
703    }
704}