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