Sources/OrgCore/Compute/Babel.swift
cmc Match ox-odt on included links, blank src lines, local TOCs and Babel defaults
f4b1fe8a56 6 days ago651 lines · 38593 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. Without `languages`, as in `emacs -Q`, no language's
256 /// `ob-` library is loaded to give its own default.
257 public static func exports(at offset: Int, tree: OrgTree, model: DocumentModel, text: NSString, languages: Bool = true) -> String? {
258 func value(_ params: Params?, language: String?) -> String {
259 (params?.single[":exports"] ?? language.flatMap { languages ? languageExports[$0] : nil } ?? "code").lowercased()
260 }
261 if let block = model.srcBlocks.first(where: { $0.range.lowerBound == offset }) {
262 return value(try? Params(block: block, model: model, text: text), language: block.language)
263 }
264 let line = text.substring(with: text.lineRange(for: NSRange(location: min(offset, text.length), length: 0)))
265 let call: Params?
266 if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil {
267 call = (try? callAt(offset, model: model, text: text))?.params
268 } else if tree.root.descendants().contains(where: { $0.kind == .inlineBabelCall && $0.range.lowerBound == offset }) {
269 // `org-babel-remove-result` only takes away `#+RESULTS:`, so an inline call's
270 // `{{{results(...)}}}` stays whatever `:exports` says.
271 return "results"
272 } else if let inline = try? inlineAt(offset, tree: tree, model: model, text: text), inline.block.range.lowerBound == offset {
273 return value(inline.params, language: inline.block.language)
274 } else {
275 return nil
276 }
277 // `org-babel-exp-code` for a call is `org-babel-exp-call-line-template`, empty.
278 switch call?.single[":exports"]?.lowercased() ?? "results" {
279 case "both", "results": return "results"
280 default: return "none"
281 }
282 }
283
284 /// Call arguments split on commas outside quotes and parentheses.
285 static func splitArguments(_ s: String) -> [String] {
286 var parts: [String] = []
287 var current = ""
288 var depth = 0
289 var quoted = false
290 for c in s {
291 if c == "\"" { quoted.toggle() }
292 if !quoted, c == "(" { depth += 1 }
293 if !quoted, c == ")" { depth -= 1 }
294 if c == ",", !quoted, depth == 0 {
295 parts.append(current)
296 current = ""
297 } else {
298 current.append(c)
299 }
300 }
301 parts.append(current)
302 return parts.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
303 }
304
305 /// The inline `src_LANG[HEADERS]{BODY}` at `offset`.
306 static func inlineAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params)? {
307 var node = tree.root
308 var found: SyntaxNode?
309 while let child = node.child(containing: offset) {
310 if child.kind == .inlineSourceBlock { found = child }
311 node = child
312 }
313 guard let object = found, let m = object.text.firstMatch(of: /^src_([^\s\[{]+)(?:\[([^\]]*)\])?\{(.*)\}$/) else { return nil }
314 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= object.range.lowerBound }
315 let block = SrcBlockInfo(range: object.range, heading: heading, name: nil, language: String(m.1), switches: [], body: String(m.3), headerArguments: [:])
316 let extra = m.2.map { [Params.parse(String($0))] } ?? []
317 return (block, try Params(block: block, model: model, text: text, defaults: [(":exports", "results"), (":hlines", "yes")], extra: extra, inline: true))
318 }
319
320 /// What `:var` references resolve to while planning.
321 struct References {
322 var resolved: [String: VarValue]
323 var options: Options
324 /// Blocks being planned for a reference, to stop cycles.
325 var visiting: Set<String> = []
326 }
327
328 /// A reference to a block that has to run first.
329 struct Needed: Error {
330 let need: BabelJob.Need
331 }
332
333 static func plan(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
334 location: Range<Int>, name: String?, inline: Bool = false, refs: References? = nil, useCache: Bool = true) -> Result<BabelJob, Failure> {
335 var evaluated = params
336 evaluated.evaluateLisp(file: options.file)
337 let needsFile = options.file == nil && evaluated.lisp.contains { evaluated.evaluated[$0] == nil }
338 return planBlock(block, params: params, model: model, text: ns, options: options, location: location, name: name, inline: inline,
339 refs: refs, useCache: useCache).map { job in
340 var job = job
341 job.needsFile = needsFile
342 return job
343 }
344 }
345
346 static func planBlock(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
347 location: Range<Int>, name: String?, inline: Bool, refs: References?, useCache: Bool) -> Result<BabelJob, Failure> {
348 let refs = refs ?? References(resolved: [:], options: options)
349 var params = params
350 params.evaluateLisp(file: options.file)
351 let needsFile = options.file == nil && params.lisp.contains { params.evaluated[$0] == nil }
352 guard let language = block.language else { return .failure(.message("This block has no language")) }
353 let eval = params.single[":eval"]?.lowercased()
354 if eval == "never" || eval == "no" {
355 return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
356 }
357 let compiled = expandedLanguages.contains(language)
358 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled {
359 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
360 }
361 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp"].contains(language) || generic[language] != nil
362 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
363 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
364 return .failure(.message("\(key) isn't supported yet; nothing was run."))
365 }
366 // The compiled languages' `org-babel-execute:` ignore `:session`.
367 let session = compiled ? nil : params.single[":session"].flatMap { $0 == "none" ? nil : ($0.isEmpty ? "*\(language)*" : $0) }
368 if session != nil, !shells.contains(language), !["python", "ruby", "js", "javascript", "R"].contains(language) {
369 return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
370 }
371 var body = normalizedBody(block)
372 if nowebEvaluates(params.single[":noweb"]) {
373 do {
374 body = try expandNoweb(block, params: params, model: model, text: ns)
375 } catch let error as Failure {
376 return .failure(error)
377 } catch {
378 return .failure(.message("\(error)"))
379 }
380 }
381 let output = params.results.contains("output")
382 let file = params.single[":file"].map { name in
383 params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
384 }
385 let toFile = params.results.contains("file")
386 var hash: String?
387 var tables = Tables()
388 let finishBase = { (kind: BabelJob.Finish.Kind) in
389 BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: name, inline: inline,
390 file: toFile ? file : nil, fileDescription: params.single[":file-desc"], hash: hash,
391 colnames: tables.picked(tables.colnames, ":colnames", params), rownames: tables.picked(tables.rownames, ":rownames", params))
392 }
393 let vars: [(String, VarValue)]
394 var stdin: VarValue?
395 do {
396 tables = try disassemble(params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }, params: params)
397 vars = tables.vars
398 stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) }
399 } catch let needed as Needed {
400 // Asked about once, with every block the references reach; asked every time when
401 // any of them has `:eval query`.
402 let reached = referencedBlocks(params, model: model, text: ns, seen: [])
403 let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
404 let query = eval == "query" || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
405 var job = BabelJob(
406 language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
407 block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finishBase(.generic), needs: [needed.need]
408 )
409 job.approved = texts
410 return .success(job)
411 } catch let error as Failure {
412 return .failure(error)
413 } catch {
414 return .failure(.message("\(error)"))
415 }
416 if useCache, !inline, !needsFile, params.single[":cache"] == "yes" {
417 do {
418 let state = try cacheState(language: language, params: params, tables: tables, body: body, location: location, name: name,
419 call: location != block.range, text: ns, options: options, model: model)
420 if state.current { return .failure(.message(cachedMessage(state.value))) }
421 // Appended or prepended results accumulate, so they carry no hash.
422 if params.results.contains("replace") { hash = state.hash }
423 } catch let error as Failure {
424 return .failure(error)
425 } catch {
426 return .failure(.message("\(error)"))
427 }
428 }
429 let blockText = ns.substring(with: NSRange(location))
430 let dir = params.single[":dir"]
431 let alwaysAsk = eval == "query"
432
433 if shells.contains(language) {
434 let valueIsExitStatus = params.results.contains("value")
435 let executable = language == "shell" ? options.shell : language
436 let lines = shellAssignments(vars, shell: executable, params: params)
437 let cmdline = params.single[":cmdline"]
438 let shebang = params.single[":shebang"].flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil }
439 if stdin != nil || cmdline != nil || (session == nil && shebang != nil) {
440 // `org-babel-sh-evaluate`: an executable script, run by the shell with the
441 // command line after it and `:stdin` as its input; the result is its standard
442 // output, or its exit status for `:results value`. `:stdin` and `:cmdline`
443 // run it even with a session, which the script doesn't use.
444 var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n"
445 if params.single[":padline"] != "no" { script += "\n" }
446 script += expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
447 let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "")
448 var job = BabelJob(
449 language: language, runner: .process(executable: executable, arguments: ["-c", command]),
450 input: stdin.map { shellString($0) } ?? "", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
451 finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
452 )
453 job.script = script
454 return .success(job)
455 }
456 let full = expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
457 return .success(BabelJob(
458 language: language, runner: session.map { .session(name: $0, executable: executable, kind: .shell) } ?? .process(executable: executable, arguments: []),
459 input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
460 block: location, blockText: blockText, alwaysAsk: alwaysAsk,
461 finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
462 ))
463 }
464 if language == "python", let session {
465 // `org-babel-python--eval-ast`: the body at top level in the session, the value its
466 // last expression's.
467 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
468 let source = expandGeneric(body, lines, params)
469 let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
470 let program: String
471 if output {
472 program = "exec(compile(\(literal), '<org-babel>', 'exec'), globals())\n"
473 } else {
474 program = pythonFormatter + """
475 import ast as __orgstar_ast
476 __orgstar_tree = __orgstar_ast.parse(\(literal))
477 __orgstar_last = None
478 if __orgstar_tree.body and isinstance(__orgstar_tree.body[-1], __orgstar_ast.Expr):
479 __orgstar_last = __orgstar_ast.Expression(__orgstar_tree.body.pop().value)
480 exec(compile(__orgstar_tree, '<org-babel>', 'exec'), globals())
481 __orgstar_format(eval(compile(__orgstar_last, '<org-babel>', 'eval'), globals()) if __orgstar_last else None, '\(resultFileToken)', [
482 """ + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
483 }
484 return .success(BabelJob(
485 language: language, runner: .session(name: session, executable: params.single[":python"] ?? options.python, kind: .python),
486 input: program, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.python)
487 ))
488 }
489 if language == "python" {
490 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
491 var full = expandGeneric(body, lines, params)
492 if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
493 let input: String
494 if output {
495 input = full + "\n"
496 } else {
497 input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
498 + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
499 }
500 return .success(BabelJob(
501 language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
502 input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
503 finish: finishBase(.python)
504 ))
505 }
506 if language == "emacs-lisp" || language == "elisp" {
507 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
508 // `org-babel-expand-body:emacs-lisp` adds the prologue and epilogue only with variables.
509 let prologue = params.single[":prologue"].map { $0 + "\n " } ?? ""
510 let epilogue = params.single[":epilogue"].map { "\n " + $0 + "\n" } ?? ""
511 let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(prologue)\(body)\(epilogue)\n)"
512 let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
513 var job = BabelJob(
514 language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
515 directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
516 )
517 job.lispForm = form
518 return .success(job)
519 }
520 if ["dot", "plantuml", "mermaid"].contains(language) {
521 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
522 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
523 let quoted = "'" + file.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
524 let ext = (file as NSString).pathExtension.isEmpty ? "png" : (file as NSString).pathExtension
525 let cmdline = params.single[":cmdline"].map { " " + $0 } ?? ""
526 var input = body + "\n"
527 let command: String
528 switch language {
529 case "dot":
530 command = "dot\(cmdline) -T\(ext) -o \(quoted)"
531 case "plantuml":
532 if body.range(of: "^[ \\t]*@start", options: .regularExpression) == nil { input = "@startuml\n" + body + "\n@enduml\n" }
533 command = "plantuml\(cmdline) -p -t\(ext) > \(quoted)"
534 default:
535 command = "f=$(mktemp).mmd; cat > \"$f\"; mmdc\(cmdline) -i \"$f\" -o \(quoted); s=$?; rm -f \"$f\"; exit $s"
536 }
537 var finish = finishBase(.generic)
538 finish.file = file
539 finish.writesFile = true
540 finish.params = params.results.filter { !["table", "scalar", "verbatim", "list", "vector"].contains($0) } + (params.results.contains("file") ? [] : ["file"])
541 return .success(BabelJob(
542 language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", command]),
543 input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish
544 ))
545 }
546 if compiled {
547 do {
548 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= location.lowerBound }
549 let run = try compiledRun(language: language, body: body, tables: tables, params: params,
550 properties: { inheritedProperty($0, heading: heading, model: model) })
551 var finish = finishBase(.compiled)
552 // ob-clojure doesn't reassemble tables.
553 if language == "clojure" { (finish.colnames, finish.rownames) = (nil, nil) }
554 var job = BabelJob(language: language, runner: .process(executable: "/bin/sh", arguments: [scriptFileToken]), input: run.source,
555 directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish)
556 job.script = run.script
557 job.programs = run.programs
558 return .success(job)
559 } catch let error as Failure {
560 return .failure(error)
561 } catch {
562 return .failure(.message("\(error)"))
563 }
564 }
565 if let (executable, arguments) = generic[language] {
566 switch language {
567 case "ruby":
568 let full = expandGeneric(body, vars.map { "\($0.0)=\(rubyLiteral($0.1))" }, params)
569 if let session {
570 return .success(BabelJob(
571 language: language, runner: .session(name: session, executable: params.single[":ruby"] ?? executable, kind: .ruby),
572 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: false, session: true))
573 ))
574 }
575 return .success(BabelJob(
576 language: language, runner: .process(executable: params.single[":ruby"] ?? executable, arguments: arguments),
577 input: output ? full : rubyWrapper(full, pp: params.results.contains("pp")), directory: dir, block: location, blockText: blockText,
578 alwaysAsk: alwaysAsk, finish: finishBase(.script(js: false))
579 ))
580 case "js", "javascript":
581 let full = expandGeneric(body, vars.map { "var \($0.0)=\(jsLiteral($0.1));" }, params)
582 if let session {
583 return .success(BabelJob(
584 language: language, runner: .session(name: session, executable: params.single[":cmd"] ?? executable, kind: .node),
585 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true))
586 ))
587 }
588 return .success(BabelJob(
589 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
590 input: output ? full : jsWrapper(full), directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
591 finish: finishBase(.script(js: true))
592 ))
593 case "awk":
594 // `org-babel-expand-body:awk`; the variables go on the command line.
595 let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
596 return .success(BabelJob(
597 language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", awkCommand(vars, params: params)]),
598 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
599 finish: finishBase(.shell(valueIsExitStatus: false))
600 ))
601 default:
602 let lines = language == "R" ? vars.map { name, value in
603 rAssignment(name, value, colnames: tables.colnames.first { $0.0 == name }?.1, colnamesYes: params.single[":colnames"] == "yes",
604 rownamesYes: params.single[":rownames"] == "yes")
605 } : []
606 // An R session runs `R` itself, which reads its commands as they come.
607 let runner: BabelJob.Runner = session.map { .session(name: $0, executable: params.single[":cmd"] ?? "R", kind: .r) }
608 ?? .process(executable: params.single[":cmd"] ?? executable, arguments: arguments)
609 return .success(BabelJob(
610 language: language, runner: runner,
611 input: expandGeneric(body, lines, params) + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
612 finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline, hash: hash)
613 ))
614 }
615 }
616 return .failure(.message("No way to run \(language) blocks yet."))
617 }
618
619 public enum Failure: Error, Equatable {
620 case message(String)
621 }
622
623}
624
625/// C-c C-c in a src block: `org-babel-execute-src-block`.
626public struct ExecuteSrcBlock: OrgCommand {
627 public init() {}
628 public var id: String { "org.babel.execute" }
629 public var title: String { "Run Source Block" }
630 public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
631
632 /// On a `#+CALL:` line, an inline `call_` or an inline `src_` block.
633 static func atCallOrInline(_ context: EditContext) -> Bool {
634 let ns = context.text as NSString
635 let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
636 if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
637 var node = context.tree.root
638 while let child = node.child(containing: context.caret) {
639 if child.kind == .inlineSourceBlock || child.kind == .inlineBabelCall { return true }
640 node = child
641 }
642 return false
643 }
644
645 public func run(in context: EditContext) -> CommandStep {
646 switch Babel.plan(context) {
647 case .success(let job): return .external(.babel(job))
648 case .failure(.message(let message)): return .failed(message)
649 }
650 }
651}