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