Sources/OrgCore/Compute/Babel.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Sources/OrgCore/Compute/Babel.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form