Sources/OrgCore/Compute/Babel.swift

71cfd8421de8b3d3c1fbdc9f394e56b267ec23e1
orgstar/Sources/OrgCore/Compute/Babel.swift

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