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