Sources/OrgCore/Compute/Babel.swift
1546 lines · 79195 bytes
1import Foundation
2
3// Babel (ob-core.el, ob-shell.el, ob-python.el, ob-emacs-lisp.el, Org 9.8.7): executing a src
4// block is planned here, run by the platform, and finished here. The plan resolves header
5// arguments and refuses anything that would make the run differ from Emacs's; the finish turns
6// the output into a result the way `org-babel-insert-result` writes it.
7
8/// A src block run for the platform to carry out.
9public struct BabelJob: Sendable, Equatable {
10 public enum Runner: Sendable, Equatable {
11 /// An interpreter reading the program on standard input.
12 case process(executable: String, arguments: [String])
13 /// `emacs --batch` loading `input` as a script.
14 case emacs
15 /// A long-running interpreter named by `:session`: a shell gets `input` as commands, Python
16 /// runs `input` as a program in its globals.
17 case session(name: String, executable: String, python: Bool)
18 }
19
20 public let language: String
21 public let runner: Runner
22 /// Standard input, or the Emacs script. `Babel.resultFileToken` stands for a file the runner
23 /// creates; its contents come back as `BabelOutput.resultFile`.
24 public let input: String
25 /// `:dir`, relative to the file's folder; nil for the folder itself.
26 public let directory: String?
27 /// The block as it was planned, to find it again when the run ends.
28 public let block: Range<Int>
29 public let blockText: String
30 /// Asks every time (`:eval query`) rather than trusting by content.
31 public let alwaysAsk: Bool
32 public let finish: Finish
33 /// A named block a `:var` refers to: run it first, then `Babel.resume` with its output.
34 public var needs: [Need] = []
35 /// With `needs`: the text of every block the run may execute, the one asked about and
36 /// those its references reach. A later job for a block not among them is refused.
37 public internal(set) var approved: [String] = []
38 /// Values of the references resolved so far, and how to plan again.
39 var resolved: [String: Babel.VarValue] = [:]
40 var caret = 0
41 var options = Babel.Options()
42 /// A script for the runner to write to an executable file, for `Babel.scriptFileToken`.
43 public internal(set) var script: String?
44 /// An Emacs Lisp block's form, for `Babel.evaluateNatively`.
45 public internal(set) var lispForm: String?
46
47 public struct Need: Sendable, Equatable {
48 /// The `:var` value, `name` or `name(args)`.
49 public let reference: String
50 public let job: BabelJob
51 }
52
53 public struct Finish: Sendable, Equatable {
54 enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp }
55 let kind: Kind
56 var language = ""
57 public internal(set) var params: [String]
58 let output: Bool
59 let wrap: String?
60 let name: String?
61 /// An inline block: the result goes after it, in `{{{results(…)}}}`.
62 var inline = false
63 /// `:file` (under `:output-dir`) with `:results file`, and `:file-desc`.
64 var file: String?
65 var fileDescription: String?
66 /// The program writes `file` itself, as graphics languages do.
67 var writesFile = false
68 }
69}
70
71public struct BabelOutput: Sendable, Equatable {
72 public var stdout: String
73 public var resultFile: String?
74 /// What the program wrote to standard error, and its exit status: Emacs shows them in
75 /// `*Org-Babel Error Output*` and still inserts the results.
76 public var stderr: String
77 public var status: Int32
78 public init(stdout: String, resultFile: String? = nil, stderr: String = "", status: Int32 = 0) {
79 self.stdout = stdout
80 self.resultFile = resultFile
81 self.stderr = stderr
82 self.status = status
83 }
84
85 /// A line for the message area when the program failed or complained, else nil.
86 public var problem: String? {
87 let first = stderr.split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)
88 switch (status, first) {
89 case (0, nil): return nil
90 case (0, let line?): return line
91 case (let code, nil): return "Exited with status \(code)"
92 case (let code, let line?): return "Exited with status \(code): \(line)"
93 }
94 }
95}
96
97public enum Babel {
98 public static let resultFileToken = "__ORGSTAR_RESULT_FILE__"
99 /// Stands, in a job's arguments, for the executable file the runner writes `job.script` to.
100 public static let scriptFileToken = "__ORGSTAR_SCRIPT_FILE__"
101 static let shells: Set<String> = ["sh", "bash", "zsh", "shell", "fish", "ksh", "dash", "ash", "csh", "mksh", "posh"]
102 static let generic: [String: (String, [String])] = [
103 "ruby": ("ruby", []), "js": ("node", []), "javascript": ("node", []), "R": ("Rscript", ["-"]),
104 "awk": ("awk", ["-f", "/dev/stdin"]),
105 ]
106
107 public struct Options: Sendable, Equatable {
108 public var python = "python3"
109 /// `shell-file-name`, for blocks in the `shell` language.
110 public var shell = "/bin/sh"
111 public init() {}
112 }
113
114 // MARK: - Planning
115
116 /// The run for the src block at the caret, or why it can't run.
117 public static func plan(_ context: EditContext, options: Options = Options()) -> Result<BabelJob, Failure> {
118 plan(context, options: options, resolved: [:])
119 }
120
121 /// Plans the block again with the value of the block `job` needed: the output of
122 /// `need.job`, as `org-babel-ref-resolve` reads it.
123 public static func resume(_ job: BabelJob, need: BabelJob.Need, output: BabelOutput, text: String, tree: OrgTree) -> Result<BabelJob, Failure> {
124 var resolved = job.resolved
125 resolved[need.reference] = varValue(need.job.finish, output)
126 let context = EditContext(revision: 0, text: text, tree: tree, selection: [job.caret..<job.caret])
127 return plan(context, options: job.options, resolved: resolved)
128 }
129
130 static func plan(_ context: EditContext, options: Options, resolved: [String: VarValue]) -> Result<BabelJob, Failure> {
131 let text = context.text
132 let ns = text as NSString
133 let model = DocumentModel(tree: context.tree)
134 let refs = References(resolved: resolved, options: options)
135 func located(_ result: Result<BabelJob, Failure>) -> Result<BabelJob, Failure> {
136 result.map { job in
137 var job = job
138 (job.caret, job.resolved, job.options) = (context.caret, resolved, options)
139 return job
140 }
141 }
142 do {
143 if let block = model.srcBlocks.first(where: { $0.range.contains(context.caret) || $0.range.upperBound == context.caret }) {
144 return located(plan(block, params: try Params(block: block, model: model, text: ns), model: model, text: ns, options: options,
145 location: block.range, name: block.name, refs: refs))
146 }
147 if let call = try callAt(context.caret, model: model, text: ns) {
148 return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: call.name, refs: refs))
149 }
150 if let call = try inlineCallAt(context.caret, tree: context.tree, model: model, text: ns) {
151 return located(plan(call.block, params: call.params, model: model, text: ns, options: options, location: call.location, name: nil, inline: true, refs: refs))
152 }
153 if let inline = try inlineAt(context.caret, tree: context.tree, model: model, text: ns) {
154 return located(plan(inline.block, params: inline.params, model: model, text: ns, options: options, location: inline.block.range, name: nil, inline: true, refs: refs))
155 }
156 } catch let error as Failure {
157 return .failure(error)
158 } catch {
159 return .failure(.message("\(error)"))
160 }
161 return .failure(.message("Not in a source block"))
162 }
163
164 /// The `#+CALL:` line at `offset`: the block it names, with the call's inside header, its
165 /// arguments as `:var` and its end header over the block's own (`org-babel-lob-get-info`).
166 static func callAt(_ offset: Int, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>, name: String?)? {
167 let lineRange = text.lineRange(for: NSRange(location: min(offset, text.length), length: 0))
168 let line = text.substring(with: lineRange)
169 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+CALL:[ \t]*([^\s(\[]+)(?:\[([^\]]*)\])?\((.*?)\)[ \t]*(.*?)[ \t]*\n?$/#) else { return nil }
170 let name = String(m.1)
171 guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
172 var extra: [[(String, String)]] = []
173 if let inside = m.2 { extra.append(Params.parse(String(inside))) }
174 extra.append(splitArguments(String(m.3)).map { (":var", $0) })
175 if !m.4.isEmpty { extra.append(Params.parse(String(m.4))) }
176 // The call's own #+NAME names its results.
177 var callName: String?
178 if lineRange.location > 0 {
179 let previous = text.substring(with: text.lineRange(for: NSRange(location: lineRange.location - 1, length: 0)))
180 callName = previous.firstMatch(of: #/(?i)^[ \t]*#\+NAME:[ \t]*(\S+)/#).map { String($0.1) }
181 }
182 let location = lineRange.location..<NSMaxRange(lineRange)
183 return (block, try Params(block: block, model: model, text: text, extra: extra), location, callName)
184 }
185
186 /// The inline `call_NAME[INSIDE](ARGS)[END]` at `offset`: like `#+CALL`, with the result
187 /// after the call.
188 static func inlineCallAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params, location: Range<Int>)? {
189 var node = tree.root
190 var found: SyntaxNode?
191 while let child = node.child(containing: offset) {
192 if child.kind == .inlineBabelCall { found = child }
193 node = child
194 }
195 guard let object = found, let m = object.text.firstMatch(of: /^call_([^()\[\]\s]+)(?:\[([^\]]*)\])?\((.*?)\)(?:\[([^\]]*)\])?$/) else { return nil }
196 let name = String(m.1)
197 guard let block = model.srcBlocks.first(where: { $0.name == name }) else { throw Failure.message("Reference '\(name)' not found in this buffer") }
198 var extra: [[(String, String)]] = []
199 if let inside = m.2 { extra.append(Params.parse(String(inside))) }
200 extra.append(splitArguments(String(m.3)).map { (":var", $0) })
201 if let end = m.4 { extra.append(Params.parse(String(end))) }
202 return (block, try Params(block: block, model: model, text: text, extra: extra), object.range)
203 }
204
205 /// Call arguments split on commas outside quotes and parentheses.
206 static func splitArguments(_ s: String) -> [String] {
207 var parts: [String] = []
208 var current = ""
209 var depth = 0
210 var quoted = false
211 for c in s {
212 if c == "\"" { quoted.toggle() }
213 if !quoted, c == "(" { depth += 1 }
214 if !quoted, c == ")" { depth -= 1 }
215 if c == ",", !quoted, depth == 0 {
216 parts.append(current)
217 current = ""
218 } else {
219 current.append(c)
220 }
221 }
222 parts.append(current)
223 return parts.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
224 }
225
226 /// The inline `src_LANG[HEADERS]{BODY}` at `offset`.
227 static func inlineAt(_ offset: Int, tree: OrgTree, model: DocumentModel, text: NSString) throws -> (block: SrcBlockInfo, params: Params)? {
228 var node = tree.root
229 var found: SyntaxNode?
230 while let child = node.child(containing: offset) {
231 if child.kind == .inlineSourceBlock { found = child }
232 node = child
233 }
234 guard let object = found, let m = object.text.firstMatch(of: /^src_([^\s\[{]+)(?:\[([^\]]*)\])?\{(.*)\}$/) else { return nil }
235 let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= object.range.lowerBound }
236 let block = SrcBlockInfo(range: object.range, heading: heading, name: nil, language: String(m.1), switches: [], body: String(m.3), headerArguments: [:])
237 var extra: [[(String, String)]] = [[(":exports", "results"), (":hlines", "yes")]]
238 if let headers = m.2 { extra.append(Params.parse(String(headers))) }
239 return (block, try Params(block: block, model: model, text: text, extra: extra, inline: true))
240 }
241
242 /// What `:var` references resolve to while planning.
243 struct References {
244 var resolved: [String: VarValue]
245 var options: Options
246 /// Blocks being planned for a reference, to stop cycles.
247 var visiting: Set<String> = []
248 }
249
250 /// A reference to a block that has to run first.
251 struct Needed: Error {
252 let need: BabelJob.Need
253 }
254
255 static func plan(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text ns: NSString, options: Options,
256 location: Range<Int>, name: String?, inline: Bool = false, refs: References? = nil) -> Result<BabelJob, Failure> {
257 let refs = refs ?? References(resolved: [:], options: options)
258 guard let language = block.language else { return .failure(.message("This block has no language")) }
259 let eval = params.single[":eval"]?.lowercased()
260 if eval == "never" || eval == "no" || eval == "never-export" || eval == "no-export" {
261 return .failure(.message("Evaluation of this \(language) code block\(block.name.map { " (\($0)) " } ?? " ")is disabled."))
262 }
263 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language) {
264 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
265 }
266 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
267 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) {
268 return .failure(.message("\(key) isn't supported yet; nothing was run."))
269 }
270 let session = params.single[":session"].flatMap { $0 == "none" ? nil : ($0.isEmpty ? "*\(language)*" : $0) }
271 if session != nil, !shells.contains(language), language != "python" {
272 return .failure(.message(":session isn't supported for \(language) yet; nothing was run."))
273 }
274 if params.single[":cache"] == "yes" { return .failure(.message(":cache isn't supported yet; nothing was run.")) }
275
276 var body = normalizedBody(block)
277 if nowebEvaluates(params.single[":noweb"]) {
278 do {
279 body = try expandNoweb(block, params: params, model: model, text: ns)
280 } catch let error as Failure {
281 return .failure(error)
282 } catch {
283 return .failure(.message("\(error)"))
284 }
285 }
286 let output = params.results.contains("output")
287 let file = params.single[":file"].map { name in
288 params.single[":output-dir"].map { $0.hasSuffix("/") ? $0 + name : $0 + "/" + name } ?? name
289 }
290 let toFile = params.results.contains("file")
291 let finishBase = { (kind: BabelJob.Finish.Kind) in
292 BabelJob.Finish(kind: kind, language: language, params: params.results, output: output, wrap: params.wrap, name: name, inline: inline,
293 file: toFile ? file : nil, fileDescription: params.single[":file-desc"])
294 }
295 let vars: [(String, VarValue)]
296 var stdin: VarValue?
297 do {
298 vars = try params.vars.map { ($0.name, try resolve($0.value, model: model, text: ns, refs: refs)) }
299 stdin = try params.single[":stdin"].map { try resolve($0, model: model, text: ns, refs: refs) }
300 } catch let needed as Needed {
301 // Asked about once, with every block the references reach; asked every time when
302 // any of them has `:eval query`.
303 let reached = referencedBlocks(params, model: model, text: ns, seen: [])
304 let texts = [ns.substring(with: NSRange(location))] + reached.map { ns.substring(with: NSRange($0.range)) }
305 let query = eval == "query" || reached.contains { (try? Params(block: $0, model: model, text: ns))?.single[":eval"]?.lowercased() == "query" }
306 var job = BabelJob(
307 language: language, runner: .process(executable: "", arguments: []), input: "", directory: params.single[":dir"],
308 block: location, blockText: texts.joined(separator: "\n"), alwaysAsk: query, finish: finishBase(.generic), needs: [needed.need]
309 )
310 job.approved = texts
311 return .success(job)
312 } catch let error as Failure {
313 return .failure(error)
314 } catch {
315 return .failure(.message("\(error)"))
316 }
317 let blockText = ns.substring(with: NSRange(location))
318 let dir = params.single[":dir"]
319 let alwaysAsk = eval == "query"
320
321 if shells.contains(language) {
322 let valueIsExitStatus = params.results.contains("value")
323 var lines: [String] = []
324 for (name, value) in vars {
325 let s: String
326 switch value {
327 case .scalar(let v), .number(let v): s = v
328 default: return .failure(.message("Tables and lists in :var aren't supported for \(language) yet."))
329 }
330 lines.append("\(name)='" + s.replacingOccurrences(of: "'", with: "'\"'\"'") + "'")
331 }
332 let executable = language == "shell" ? options.shell : language
333 let cmdline = params.single[":cmdline"]
334 let shebang = params.single[":shebang"].flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil }
335 if session == nil, stdin != nil || cmdline != nil || shebang != nil {
336 // `org-babel-sh-evaluate`: an executable script, run by the shell with the
337 // command line after it and `:stdin` as its input; the value is its last line.
338 var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n"
339 if params.single[":padline"] != "no" { script += "\n" }
340 script += (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
341 let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "")
342 var job = BabelJob(
343 language: language, runner: .process(executable: executable, arguments: ["-c", command]),
344 input: stdin.map(shellString) ?? "", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
345 finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
346 )
347 job.script = script
348 return .success(job)
349 }
350 let full = (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "")
351 return .success(BabelJob(
352 language: language, runner: session.map { .session(name: $0, executable: executable, python: false) } ?? .process(executable: executable, arguments: []),
353 input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
354 block: location, blockText: blockText, alwaysAsk: alwaysAsk,
355 finish: finishBase(.shell(valueIsExitStatus: valueIsExitStatus))
356 ))
357 }
358 if language == "python", let session {
359 // `org-babel-python--eval-ast`: the body at top level in the session, the value its
360 // last expression's.
361 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
362 let source = (lines + [body]).joined(separator: "\n")
363 let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
364 let program: String
365 if output {
366 program = "exec(compile(\(literal), '<org-babel>', 'exec'), globals())\n"
367 } else {
368 program = pythonFormatter + """
369 import ast as __orgstar_ast
370 __orgstar_tree = __orgstar_ast.parse(\(literal))
371 __orgstar_last = None
372 if __orgstar_tree.body and isinstance(__orgstar_tree.body[-1], __orgstar_ast.Expr):
373 __orgstar_last = __orgstar_ast.Expression(__orgstar_tree.body.pop().value)
374 exec(compile(__orgstar_tree, '<org-babel>', 'exec'), globals())
375 __orgstar_format(eval(compile(__orgstar_last, '<org-babel>', 'eval'), globals()) if __orgstar_last else None, '\(resultFileToken)', [
376 """ + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
377 }
378 return .success(BabelJob(
379 language: language, runner: .session(name: session, executable: params.single[":python"] ?? options.python, python: true),
380 input: program, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.python)
381 ))
382 }
383 if language == "python" {
384 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
385 var full = (lines + [body]).joined(separator: "\n")
386 if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
387 let input: String
388 if output {
389 input = full + "\n"
390 } else {
391 input = pythonFormatter + "def main():\n" + shiftRight(full) + "\n\n__orgstar_format(main(), '\(resultFileToken)', ["
392 + params.results.map { "\"\($0)\"" }.joined(separator: ", ") + "])\n"
393 }
394 return .success(BabelJob(
395 language: language, runner: .process(executable: params.single[":python"] ?? options.python, arguments: []),
396 input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
397 finish: finishBase(.python)
398 ))
399 }
400 if language == "emacs-lisp" || language == "elisp" {
401 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
402 let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)"
403 let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
404 var job = BabelJob(
405 language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
406 directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.emacsLisp)
407 )
408 job.lispForm = form
409 return .success(job)
410 }
411 if ["dot", "plantuml", "mermaid"].contains(language) {
412 // ob-dot, ob-plantuml and ob-mermaid: the program draws into `:file`.
413 guard let file else { return .failure(.message("\(language) code blocks need a :file header argument")) }
414 let quoted = "'" + file.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
415 let ext = (file as NSString).pathExtension.isEmpty ? "png" : (file as NSString).pathExtension
416 let cmdline = params.single[":cmdline"].map { " " + $0 } ?? ""
417 var input = body + "\n"
418 let command: String
419 switch language {
420 case "dot":
421 command = "dot\(cmdline) -T\(ext) -o \(quoted)"
422 case "plantuml":
423 if body.range(of: "^[ \\t]*@start", options: .regularExpression) == nil { input = "@startuml\n" + body + "\n@enduml\n" }
424 command = "plantuml\(cmdline) -p -t\(ext) > \(quoted)"
425 default:
426 command = "f=$(mktemp).mmd; cat > \"$f\"; mmdc\(cmdline) -i \"$f\" -o \(quoted); s=$?; rm -f \"$f\"; exit $s"
427 }
428 var finish = finishBase(.generic)
429 finish.file = file
430 finish.writesFile = true
431 finish.params = params.results.filter { !["table", "scalar", "verbatim", "list", "vector"].contains($0) } + (params.results.contains("file") ? [] : ["file"])
432 return .success(BabelJob(
433 language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", command]),
434 input: input, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finish
435 ))
436 }
437 if let (executable, arguments) = generic[language] {
438 guard vars.isEmpty else { return .failure(.message(":var isn't supported for \(language) yet.")) }
439 return .success(BabelJob(
440 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
441 input: body + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
442 finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline)
443 ))
444 }
445 return .failure(.message("No way to run \(language) blocks yet."))
446 }
447
448 public enum Failure: Error, Equatable {
449 case message(String)
450 }
451
452 // MARK: - Noweb
453
454 /// `org-babel-noweb-p` in the `:eval` context.
455 static func nowebEvaluates(_ value: String?) -> Bool {
456 (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "no-export", "strip-export", "eval", "strip-tangle"].contains(String($0)) }
457 }
458
459 /// `org-babel-noweb-p` for `:tangle`.
460 static func nowebTangles(_ value: String?) -> Bool {
461 (value ?? "").split(whereSeparator: \.isWhitespace).contains { ["yes", "tangle", "no-export", "strip-export", "strip-tangle"].contains(String($0)) }
462 }
463
464 /// `org-babel-expand-noweb-references` for evaluation: each `<<name>>` becomes the body of
465 /// the block named so, or of every block with that `:noweb-ref`, joined by `:noweb-sep`, or
466 /// the contents of the heading with that ID; the text before it on its line goes before
467 /// each line it brings.
468 /// `tangling` expands the blocks it brings in as tangling would (`:noweb tangle`), not as
469 /// evaluation does.
470 /// `links` gives a block's begin and end comments, for `:comments noweb` when tangling.
471 static func expandNoweb(_ block: SrcBlockInfo, params: Params, model: DocumentModel, text: NSString, tangling: Bool = false, depth: Int = 0,
472 links: ((SrcBlockInfo, Params) throws -> (begin: String, end: String))? = nil) throws -> String {
473 guard depth < 32 else { throw Failure.message("Noweb references nest too deeply") }
474 let body = normalizedBody(block)
475 let prefixing = params.single[":noweb-prefix"].map { $0 != "no" && $0 != "nil" } ?? true
476 let commenting = tangling && links != nil && params.single[":comments"] == "noweb"
477 func expand(_ other: SrcBlockInfo) throws -> String {
478 let otherParams = try Params(block: other, model: model, text: text)
479 let expands = tangling ? nowebTangles(otherParams.single[":noweb"]) : nowebEvaluates(otherParams.single[":noweb"])
480 let b = expands
481 ? try expandNoweb(other, params: otherParams, model: model, text: text, tangling: tangling, depth: depth + 1, links: links)
482 : normalizedBody(other)
483 guard commenting, let links else { return b }
484 // `c-wrap`: commented in this block's language, trimmed.
485 func wrap(_ s: String) throws -> String {
486 try Tangle.commentRegion(s, language: block.language ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
487 }
488 var (begin, end) = try links(other.name == nil ? block : other, other.name == nil ? params : otherParams)
489 // A `:noweb-ref` block without a name: the link is the including block's, the name empty.
490 if other.name == nil {
491 if let split = begin.range(of: "][") { begin = begin[..<split.lowerBound] + "][]]" }
492 end = " ends here"
493 }
494 return try wrap(begin) + "\n" + b + "\n" + (try wrap(end)) + "\n"
495 }
496 func inCommentedHeading(_ b: SrcBlockInfo) -> Bool {
497 guard let h = b.heading else { return false }
498 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
499 }
500 let regex = try! NSRegularExpression(pattern: "(.*?)(<<([^ \\t\\n](?:.*?[^ \\t\\n])?)>>)")
501 let ns = body as NSString
502 var out = ""
503 var at = 0
504 for m in regex.matches(in: body, range: NSRange(location: 0, length: ns.length)) {
505 let prefix = ns.substring(with: m.range(at: 1))
506 let id = ns.substring(with: m.range(at: 3))
507 out += ns.substring(with: NSRange(location: at, length: m.range(at: 2).location - at))
508 at = NSMaxRange(m.range)
509 var expansion = ""
510 if id.range(of: "\\(.*\\)", options: .regularExpression) != nil {
511 throw Failure.message("Noweb references that run a block (\(id)) aren't supported yet; nothing was run.")
512 } else if let heading = model.headings.firstIndex(where: { h in
513 h.properties.contains { ($0.key.uppercased() == "ID" && $0.value == id) || ($0.key.uppercased() == "CUSTOM_ID" && "#" + $0.value == id) }
514 }) {
515 expansion = headlineBody(heading, model: model, text: text)
516 } else if let named = model.srcBlocks.first(where: { $0.name == id }), !inCommentedHeading(named) {
517 expansion = try expand(named)
518 } else {
519 var parts: [String] = []
520 var separators: [String] = []
521 for other in model.srcBlocks where !inCommentedHeading(other) {
522 let p = try Params(block: other, model: model, text: text)
523 guard p.single[":noweb-ref"] == id else { continue }
524 parts.append(try expand(other))
525 separators.append(p.single[":noweb-sep"] ?? "\n")
526 }
527 for (i, part) in parts.enumerated() {
528 if i > 0 { expansion += separators[i - 1] }
529 expansion += part
530 }
531 }
532 out += prefixing ? expansion.components(separatedBy: CharacterSet(charactersIn: "\n\r")).joined(separator: "\n" + prefix) : expansion
533 }
534 return out + ns.substring(from: at)
535 }
536
537 /// `org-babel-ref-headline-body`: the entry after its planning and drawers.
538 static func headlineBody(_ index: Int, model: DocumentModel, text: NSString) -> String {
539 let heading = model.headings[index]
540 let buffer = EmacsBuffer(text as String, point: heading.headingRange.lowerBound)
541 buffer.endOfMetaData()
542 let start = buffer.point
543 let end = model.headings[(index + 1)...].first.map { $0.headingRange.lowerBound } ?? text.length
544 return start < end ? text.substring(with: NSRange(location: start, length: end - start)).trimmingCharacters(in: .whitespacesAndNewlines) : ""
545 }
546
547 /// `org-babel--normalize-body`: without the final newline, and without the indentation
548 /// common to its lines unless `-i` keeps it.
549 static func normalizedBody(_ block: SrcBlockInfo) -> String {
550 var lines = block.body.components(separatedBy: "\n")
551 if lines.last == "" { lines.removeLast() }
552 // Org escapes lines starting with `*` or `#+` inside blocks with a comma.
553 lines = lines.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
554 if !block.switches.contains("-i") {
555 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " || $0 == "\t" }.count }
556 let common = indents.min() ?? 0
557 lines = lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " || $0 == "\t" }.count))) }
558 }
559 return lines.joined(separator: "\n")
560 }
561
562 // MARK: - Header arguments
563
564 struct Params {
565 var results: [String] = ["replace"]
566 var single: [String: String] = [:]
567 var vars: [(name: String, value: String)] = []
568 var wrap: String?
569 /// Keys whose value is Lisp to evaluate (`org-babel-read`): unquoted, starting with `(`.
570 var lisp: Set<String> = []
571
572 static let resultGroups: [Set<String>] = [
573 ["file", "list", "vector", "table", "scalar", "verbatim"],
574 ["raw", "html", "latex", "org", "code", "pp", "drawer", "link", "graphics"],
575 ["replace", "silent", "none", "discard", "append", "prepend"],
576 ["output", "value"],
577 ]
578
579 init(block: SrcBlockInfo, model: DocumentModel, text: NSString, extra: [[(String, String)]] = [], inline: Bool = false) throws {
580 var layers: [[(String, String)]] = []
581 let language = block.language ?? ""
582 // `org-babel-params-from-properties`: the inherited `header-args`, then the inherited
583 // `header-args:LANG`, each the nearest value with `+` additions after it.
584 var levels = [model.fileProperties]
585 if let heading = block.heading {
586 levels += (model.ancestors(of: heading).reversed() + [heading]).map { model.headings[$0].properties }
587 }
588 for key in ["header-args", "header-args:\(language)"] {
589 var value: String?
590 for entries in levels {
591 for entry in entries where entry.key.lowercased() == key {
592 value = entry.additive ? [value, entry.value].compactMap { $0 }.joined(separator: " ") : entry.value
593 }
594 }
595 if let value { layers.append(Params.parse(value)) }
596 }
597 let firstLine = inline ? "" : text.substring(with: text.lineRange(for: NSRange(location: block.range.lowerBound, length: 0)))
598 if let r = firstLine.range(of: "(?i)#\\+begin_src[ \\t]+\\S+", options: .regularExpression) {
599 var rest = String(firstLine[r.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
600 while let first = rest.split(separator: " ").first, first.hasPrefix("-") || first.hasPrefix("+") {
601 rest = String(rest.dropFirst(first.count)).trimmingCharacters(in: .whitespaces)
602 }
603 layers.append(Params.parse(rest))
604 }
605 // `#+HEADER:` lines above the block.
606 var headers: [String] = []
607 var location = block.range.lowerBound
608 while !inline, location > 0 {
609 let previous = text.lineRange(for: NSRange(location: location - 1, length: 0))
610 let line = text.substring(with: previous).trimmingCharacters(in: .whitespacesAndNewlines)
611 guard line.range(of: "(?i)^#\\+(header|name|caption|attr_[a-z]+|results|plot|label):", options: .regularExpression) != nil else { break }
612 if line.lowercased().hasPrefix("#+header:") { headers.insert(String(line.dropFirst("#+header:".count)), at: 0) }
613 location = previous.location
614 }
615 for header in headers { layers.append(Params.parse(header)) }
616 layers += extra
617
618 for layer in layers {
619 for (key, raw) in layer {
620 let quoted = key != ":var" && raw.count >= 2 && raw.hasPrefix("\"") && raw.hasSuffix("\"")
621 let value = quoted ? Params.unescape(String(raw.dropFirst().dropLast())) : raw
622 if key != ":var" {
623 if !quoted, value.hasPrefix("(") { lisp.insert(key) } else { lisp.remove(key) }
624 }
625 switch key {
626 case ":results":
627 for word in value.split(whereSeparator: \.isWhitespace).map(String.init) {
628 if let group = Params.resultGroups.first(where: { $0.contains(word) }) { results.removeAll { group.contains($0) } }
629 results.removeAll { $0 == word }
630 results.insert(word, at: 0)
631 }
632 case ":var":
633 for value in Params.splitVars(value) {
634 guard let eq = value.firstIndex(of: "=") else { throw Failure.message(":var \(value) needs a name and a value") }
635 let name = value[..<eq].trimmingCharacters(in: .whitespaces)
636 let assigned = value[value.index(after: eq)...].trimmingCharacters(in: .whitespaces)
637 vars.removeAll { $0.name == name }
638 vars.append((name, assigned))
639 }
640 case ":wrap":
641 wrap = value
642 default:
643 single[key] = value
644 }
645 }
646 }
647 }
648
649 /// `org-babel-parse-header-arguments`: split before each `:key` outside quotes and
650 /// parentheses.
651 /// A Lisp string's contents as `read` gives them.
652 static func unescape(_ s: String) -> String {
653 var out = ""
654 var escaped = false
655 for c in s {
656 if escaped {
657 switch c {
658 case "n": out.append("\n")
659 case "t": out.append("\t")
660 default: out.append(c)
661 }
662 escaped = false
663 } else if c == "\\" {
664 escaped = true
665 } else {
666 out.append(c)
667 }
668 }
669 return out
670 }
671
672 /// `org-babel-parse-multiple-vars`: one `:var` value holding several assignments split
673 /// on spaces outside quotes and brackets, pieces split beside `=` joined again.
674 static func splitVars(_ value: String) -> [String] {
675 var pieces: [String] = []
676 var current = ""
677 var depth = 0
678 var quoted = false
679 var previous: Character = " "
680 for c in value {
681 if c == "\"", previous != "\\" { quoted.toggle() }
682 previous = c
683 if !quoted, "([{".contains(c) { depth += 1 }
684 if !quoted, ")]}".contains(c) { depth = max(0, depth - 1) }
685 if c == " ", !quoted, depth == 0 {
686 if !current.isEmpty { pieces.append(current) }
687 current = ""
688 } else {
689 current.append(c)
690 }
691 }
692 if !current.isEmpty { pieces.append(current) }
693 var joined: [String] = []
694 for piece in pieces {
695 if let last = joined.last, last.hasSuffix("=") || piece.hasPrefix("=") {
696 joined[joined.count - 1] = last + piece
697 } else {
698 joined.append(piece)
699 }
700 }
701 return joined.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
702 }
703
704 static func parse(_ text: String) -> [(String, String)] {
705 var parts: [String] = []
706 var current = ""
707 var depth = 0
708 var quoted = false
709 var previous: Character = " "
710 for c in text {
711 if c == "\"", previous != "\\" { quoted.toggle() }
712 if !quoted {
713 if c == "(" { depth += 1 }
714 if c == ")" { depth = max(0, depth - 1) }
715 }
716 if c == ":", !quoted, depth == 0, previous == " " || previous == "\t" {
717 parts.append(current)
718 current = ""
719 }
720 current.append(c)
721 previous = c
722 }
723 parts.append(current)
724 var pairs: [(String, String)] = []
725 for part in parts {
726 let trimmed = part.trimmingCharacters(in: .whitespaces)
727 guard trimmed.hasPrefix(":") else { continue }
728 let key = String(trimmed.prefix { !$0.isWhitespace }).lowercased()
729 // Quotes stay until the value is used, so a quoted string isn't taken for Lisp.
730 pairs.append((key, trimmed.dropFirst(key.count).trimmingCharacters(in: .whitespaces)))
731 }
732 return pairs
733 }
734 }
735
736 // MARK: - Variables
737
738 /// A referenced block's result as a `:var` value.
739 static func varValue(_ finish: BabelJob.Finish, _ output: BabelOutput) -> VarValue {
740 switch value(finish, output) {
741 case .none: return .scalar("")
742 case .string(let s): return number(s).map(VarValue.number) ?? .scalar(s)
743 case .table(let rows): return .table(rows.compactMap { $0?.map(cell) })
744 }
745 }
746
747 enum VarValue: Equatable, Sendable {
748 case scalar(String)
749 case number(String)
750 case table([[Cell]])
751 case list([Cell])
752 }
753
754 enum Cell: Equatable, Sendable {
755 case text(String)
756 case number(String)
757 }
758
759 /// `org-babel--string-to-number`, keeping Emacs's printed form.
760 static func number(_ s: String) -> String? {
761 let t = s.trimmingCharacters(in: .whitespaces)
762 guard !t.isEmpty, !t.contains(where: \.isWhitespace), t.range(of: "^[0-9e.+ -]+$", options: .regularExpression) != nil else { return nil }
763 if t.range(of: "^[-+]?[0-9]+\\.?$", options: .regularExpression) != nil {
764 var digits = t.hasSuffix(".") ? String(t.dropLast()) : t
765 let negative = digits.hasPrefix("-")
766 if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() }
767 digits = String(digits.drop { $0 == "0" })
768 if digits.isEmpty { return "0" }
769 return (negative ? "-" : "") + digits
770 }
771 guard t.range(of: "^[-+]?([0-9]+\\.[0-9]+|[0-9]*\\.[0-9]+|[0-9]+(\\.[0-9]*)?e[-+]?[0-9]+|[0-9]*\\.[0-9]+e[-+]?[0-9]+)$", options: .regularExpression) != nil,
772 let d = Double(t) else { return nil }
773 return emacsFloat(d)
774 }
775
776 /// How Emacs prints a float.
777 static func emacsFloat(_ d: Double) -> String {
778 if d == d.rounded(), abs(d) < 1e16 { return String(format: "%.1f", d) }
779 return "\(d)"
780 }
781
782 static func cell(_ s: String) -> Cell {
783 var t = s
784 if let m = s.firstMatch(of: /^\s*"(.+)"\s*$/) { t = String(m.1) }
785 return number(t).map(Cell.number) ?? .text(t)
786 }
787
788 /// `name` or `name(args)` naming a src block in the file: the block and its call arguments.
789 static func referencedBlock(_ value: String, model: DocumentModel) -> (block: SrcBlockInfo, arguments: String?)? {
790 guard let m = value.firstMatch(of: /^([^\s()\[\]"]+)(?:\((.*)\))?$/),
791 let block = model.srcBlocks.first(where: { $0.name == String(m.1) }) else { return nil }
792 return (block, m.2.map(String.init))
793 }
794
795 /// The blocks `params`' references run, directly or through theirs.
796 static func referencedBlocks(_ params: Params, model: DocumentModel, text: NSString, seen: Set<String>) -> [SrcBlockInfo] {
797 var found: [SrcBlockInfo] = []
798 var seen = seen
799 for value in params.vars.map(\.value) + [params.single[":stdin"]].compactMap({ $0 }) {
800 guard let (block, arguments) = referencedBlock(value, model: model), let name = block.name, seen.insert(name).inserted else { continue }
801 found.append(block)
802 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
803 if let inner = try? Params(block: block, model: model, text: text, extra: extra) {
804 found += referencedBlocks(inner, model: model, text: text, seen: seen)
805 }
806 }
807 return found
808 }
809
810 /// `org-babel-ref-resolve` for literals, named tables and lists in the file, and named src
811 /// blocks, which run first (`Needed`) and give their result.
812 static func resolve(_ value: String, model: DocumentModel, text: NSString, refs: References) throws -> VarValue {
813 if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 { return .scalar(Params.unescape(String(value.dropFirst().dropLast()))) }
814 if let n = number(value) { return .number(n) }
815 if let known = refs.resolved[value] { return known }
816 if let (block, arguments) = referencedBlock(value, model: model), let name = block.name {
817 guard !refs.visiting.contains(name) else { throw Failure.message("\(name) refers to itself through :var") }
818 let extra = arguments.map { [splitArguments($0).map { (":var", $0) }] } ?? []
819 var inner = refs
820 inner.visiting.insert(name)
821 switch plan(block, params: try Params(block: block, model: model, text: text, extra: extra), model: model, text: text,
822 options: refs.options, location: block.range, name: name, refs: inner) {
823 case .failure(let failure): throw failure
824 case .success(let job):
825 throw Needed(need: job.needs.first ?? BabelJob.Need(reference: value, job: job))
826 }
827 }
828 if value.contains("(") || value.contains("[") { throw Failure.message("References like \(value) aren't supported yet.") }
829 // A named element: `#+NAME: value` above a table or list.
830 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
831 guard let r = (text as String).range(of: pattern, options: .regularExpression) else {
832 throw Failure.message("Can't find \(value) for :var.")
833 }
834 let start = NSMaxRange(text.lineRange(for: NSRange(r, in: text as String)))
835 var location = start
836 var rows: [[Cell]] = []
837 var items: [Cell] = []
838 while location < text.length {
839 let lineRange = text.lineRange(for: NSRange(location: location, length: 0))
840 let line = text.substring(with: lineRange).trimmingCharacters(in: .newlines)
841 let trimmed = line.trimmingCharacters(in: .whitespaces)
842 if trimmed.hasPrefix("|") {
843 if trimmed.hasPrefix("|-") { throw Failure.message("Tables with rules in :var aren't supported yet.") }
844 let cells = trimmed.dropFirst().split(separator: "|", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
845 rows.append((trimmed.hasSuffix("|") ? Array(cells.dropLast()) : cells).map(cell))
846 } else if let m = trimmed.firstMatch(of: /^[-+*] (.*)$/), rows.isEmpty {
847 items.append(cell(String(m.1)))
848 } else if trimmed.hasPrefix("#+") || (!rows.isEmpty || !items.isEmpty) {
849 if rows.isEmpty, items.isEmpty, trimmed.lowercased().hasPrefix("#+begin_src") {
850 throw Failure.message("Using a src block's result in :var isn't supported yet.")
851 }
852 break
853 } else {
854 break
855 }
856 location = NSMaxRange(lineRange)
857 }
858 if !rows.isEmpty { return .table(rows) }
859 if !items.isEmpty { return .list(items) }
860 throw Failure.message("\(value) isn't a table or list.")
861 }
862
863 /// `org-babel-sh-var-to-string`: a table's rows as tab-separated lines, a list's items as
864 /// lines.
865 static func shellString(_ value: VarValue) -> String {
866 func cell(_ c: Cell) -> String {
867 switch c {
868 case .number(let n): n
869 case .text(let s): s
870 }
871 }
872 switch value {
873 case .scalar(let s), .number(let s): return s
874 case .list(let items): return items.map(cell).joined(separator: "\n")
875 case .table(let rows): return rows.map { $0.map(cell).joined(separator: "\t") }.joined(separator: "\n")
876 }
877 }
878
879 /// `org-babel-python-var-to-python`.
880 static func pythonLiteral(_ value: VarValue) -> String {
881 func cell(_ c: Cell) -> String {
882 switch c {
883 case .number(let n): return n
884 case .text(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
885 }
886 }
887 switch value {
888 case .scalar(let s): return lispString(s, triple: s.contains("\n") || s.contains("\r"))
889 case .number(let n): return n
890 case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
891 case .table(let rows): return "[" + rows.map { "[" + $0.map(cell).joined(separator: ", ") + "]" }.joined(separator: ", ") + "]"
892 }
893 }
894
895 /// `prin1` of a string.
896 static func lispString(_ s: String, triple: Bool = false) -> String {
897 let quoted = "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
898 return triple ? "\"\"" + quoted + "\"\"" : quoted
899 }
900
901 static func lispLiteral(_ value: VarValue) -> String {
902 func cell(_ c: Cell) -> String {
903 switch c {
904 case .number(let n): return n
905 case .text(let s): return lispString(s)
906 }
907 }
908 switch value {
909 case .scalar(let s): return lispString(s)
910 case .number(let n): return n
911 case .list(let items): return "(" + items.map(cell).joined(separator: " ") + ")"
912 case .table(let rows): return "(" + rows.map { "(" + $0.map(cell).joined(separator: " ") + ")" }.joined(separator: " ") + ")"
913 }
914 }
915
916 // MARK: - Python
917
918 /// Writes the value of `main()` to the result file as org's Python wrapper does: `pprint`
919 /// for `pp`, `key :: value` items for a dict as a list, dicts as rows for tables,
920 /// otherwise `str`.
921 static let pythonFormatter = """
922 def __orgstar_format(value, path, params):
923 def rows(v):
924 if isinstance(v, dict):
925 return [(k, rows(x)) for k, x in v.items()]
926 if isinstance(v, (list, tuple)):
927 return [rows(x) for x in v]
928 return v
929 with open(path, 'w') as out:
930 if 'pp' in params:
931 import pprint
932 out.write(pprint.pformat(value))
933 elif 'list' in params and isinstance(value, dict):
934 out.write(str(['{} :: {}'.format(k, v) for k, v in value.items()]))
935 else:
936 if not set(params) & {'scalar', 'verbatim', 'raw'} and 'table' in params:
937 value = rows(value)
938 out.write(str(value))
939
940 """
941
942 /// `org-babel-python--shift-right`: four spaces more on every line outside strings.
943 static func shiftRight(_ body: String) -> String {
944 var inString: String?
945 var lines: [String] = []
946 for line in body.components(separatedBy: "\n") {
947 lines.append(inString == nil ? " " + line : line)
948 var i = line.startIndex
949 while i < line.endIndex {
950 if let delimiter = inString {
951 if line[i...].hasPrefix(delimiter) {
952 inString = nil
953 i = line.index(i, offsetBy: 3)
954 continue
955 }
956 } else if line[i] == "#" {
957 break
958 } else if line[i...].hasPrefix("\"\"\"") || line[i...].hasPrefix("'''") {
959 inString = String(line[i...].prefix(3))
960 i = line.index(i, offsetBy: 3)
961 continue
962 } else if line[i] == "\"" || line[i] == "'" {
963 let quote = line[i]
964 i = line.index(after: i)
965 while i < line.endIndex, line[i] != quote {
966 if line[i] == "\\" { i = line.index(after: i) }
967 if i < line.endIndex { i = line.index(after: i) }
968 }
969 }
970 if i < line.endIndex { i = line.index(after: i) }
971 }
972 }
973 return lines.joined(separator: "\n")
974 }
975
976 // MARK: - Emacs Lisp
977
978 /// Evaluates `form` and prints the result as JSON: its `%s` and `%S` forms, and its rows
979 /// when it is a table.
980 static func emacsScript(form: String, params: [String]) -> String {
981 """
982 ;;; -*- lexical-binding: t -*-
983 (require 'cl-lib)
984 (require 'json)
985 (let* ((result \(form))
986 (print-level nil)
987 (print-length nil)
988 (cell (lambda (c) (if (stringp c) c (format "%s" c))))
989 (tabulable (and (proper-list-p result)
990 (cl-every (lambda (e) (or (atom e) (proper-list-p e))) result)))
991 (rows (and tabulable result
992 (if (cl-every (lambda (e) (or (eq e 'hline) (listp e))) result)
993 (mapcar (lambda (r) (if (eq r 'hline) "hline" (vconcat (mapcar cell r)))) result)
994 (list (vconcat (mapcar cell result)))))))
995 (princ (json-encode `((s . ,(format "%s" result))
996 (S . ,(format "%S" result))
997 (string . ,(if (stringp result) t :json-false))
998 (rows . ,(if rows (vconcat rows) :json-null))))))
999 """
1000 }
1001
1002 /// An Emacs Lisp job run by `Elisp` instead of Emacs: the output `emacsScript` would print.
1003 /// A Lisp error fails the run, as it does in Emacs; nil when the block uses what `Elisp`
1004 /// doesn't have.
1005 public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? {
1006 guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil }
1007 let lisp = Elisp()
1008 let result: Sexp
1009 do {
1010 result = try lisp.eval(sexp)
1011 } catch is Elisp.Unsupported {
1012 return nil
1013 } catch {
1014 throw .message("\(error)")
1015 }
1016 func cell(_ c: Sexp) -> String { Elisp.printed(c) }
1017 func isProper(_ v: Sexp) -> Bool {
1018 if case .list = v { return true }
1019 return Elisp.isNil(v)
1020 }
1021 func isAtom(_ v: Sexp) -> Bool {
1022 switch v {
1023 case .list(let items): items.isEmpty
1024 case .dotted: false
1025 default: true
1026 }
1027 }
1028 var rows: [Any] = []
1029 if case .list(let items) = result, items.allSatisfy({ isAtom($0) || isProper($0) }) {
1030 if items.allSatisfy({ $0 == .symbol("hline") || isProper($0) }) {
1031 rows = items.map { $0 == .symbol("hline") ? "hline" as Any : ((try? Elisp.elements($0)) ?? []).map(cell) as Any }
1032 } else {
1033 rows = [items.map(cell)]
1034 }
1035 }
1036 var object: [String: Any] = ["s": Elisp.printed(result), "S": Elisp.printed(result, escape: true), "string": result.string != nil]
1037 object["rows"] = rows.isEmpty ? NSNull() : rows
1038 guard let data = try? JSONSerialization.data(withJSONObject: object), let json = String(data: data, encoding: .utf8) else { return nil }
1039 return BabelOutput(stdout: lisp.standardOutput + json, stderr: lisp.messages)
1040 }
1041
1042 // MARK: - Finishing
1043
1044 /// What the run produced, as Babel holds it before inserting.
1045 enum Value: Equatable {
1046 case none
1047 case string(String)
1048 /// Rows of cells; nil rows are rules.
1049 case table([[String]?])
1050 }
1051
1052 /// The edit that writes the run's result under the block, or why it can't.
1053 public static func finish(_ job: BabelJob, output: BabelOutput, text: String, settings: OrgSettings = .default) -> Result<[TextEdit], Failure> {
1054 let ns = text as NSString
1055 var blockRange = job.block
1056 if blockRange.upperBound > ns.length || ns.substring(with: NSRange(blockRange)) != job.blockText {
1057 let found = ns.range(of: job.blockText)
1058 guard found.location != NSNotFound,
1059 ns.range(of: job.blockText, range: NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))).location == NSNotFound else {
1060 return .failure(.message("The block changed while it ran; the result wasn't written."))
1061 }
1062 blockRange = found.location..<NSMaxRange(found)
1063 }
1064 let value = Self.value(job.finish, output)
1065 if job.finish.params.contains("silent") || job.finish.params.contains("none") || job.finish.params.contains("discard") { return .success([]) }
1066 let buffer = EmacsBuffer(text, point: 0, settings: settings)
1067 if job.finish.inline {
1068 do {
1069 try insertInlineResult(value, job.finish, at: blockRange, buffer: buffer)
1070 } catch let error as Failure {
1071 return .failure(error)
1072 } catch {
1073 return .failure(.message("\(error)"))
1074 }
1075 return .success(TextEdit.between(text, buffer.text as String))
1076 }
1077 insertResult(value, job.finish, block: blockRange, buffer: buffer)
1078 return .success(TextEdit.between(text, buffer.text as String))
1079 }
1080
1081 /// The language's result handling: `org-babel-result-cond` and the table import.
1082 static func value(_ finish: BabelJob.Finish, _ output: BabelOutput) -> Value {
1083 let params = finish.params
1084 if params.contains("file") {
1085 // `org-babel-result-to-file`: a link to `:file`, or to the result as a path.
1086 let path = finish.file ?? rawResult(finish, output)
1087 var link = "[[file:" + path + "]"
1088 if let description = finish.fileDescription { link += "[" + (description.isEmpty ? path : description) + "]" }
1089 return .string(link + "]")
1090 }
1091 let scalar = params.contains("scalar") || params.contains("verbatim") || params.contains("html") || params.contains("code")
1092 || params.contains("pp") || params.contains("file")
1093 || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
1094 switch finish.kind {
1095 case .shell(let valueIsExitStatus):
1096 var results = output.stdout
1097 if valueIsExitStatus {
1098 results = results.split(separator: "\n", omittingEmptySubsequences: true).last.map(String.init) ?? ""
1099 }
1100 if scalar { return .string(results) }
1101 return importTable(results)
1102 case .generic:
1103 return .string(output.stdout)
1104 case .python:
1105 let raw = finish.output ? output.stdout : (output.resultFile ?? "")
1106 if scalar { return .string(raw) }
1107 return pythonValue(raw)
1108 case .emacsLisp:
1109 guard let data = output.stdout.data(using: .utf8),
1110 let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .string(output.stdout) }
1111 if scalar {
1112 return .string((params.contains("scalar") || params.contains("verbatim") ? object["S"] : object["s"]) as? String ?? "")
1113 }
1114 if object["string"] as? Bool == true { return .string(object["s"] as? String ?? "") }
1115 if let rows = object["rows"] as? [Any] {
1116 return .table(rows.map { $0 as? String == "hline" ? nil : ($0 as? [String] ?? []) })
1117 }
1118 let printed = object["S"] as? String ?? ""
1119 return printed == "nil" ? .none : .string(printed)
1120 }
1121 }
1122
1123 /// The result as the program left it, before tables are read.
1124 static func rawResult(_ finish: BabelJob.Finish, _ output: BabelOutput) -> String {
1125 switch finish.kind {
1126 case .python: return finish.output ? output.stdout : (output.resultFile ?? "")
1127 case .emacsLisp:
1128 guard let data = output.stdout.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return output.stdout }
1129 return object["s"] as? String ?? ""
1130 case .shell(let valueIsExitStatus):
1131 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
1132 case .generic: return output.stdout
1133 }
1134 }
1135
1136 /// With `:results file` and `:file`, what to write there, relative to the run's folder;
1137 /// nil when there's nothing to write or the program wrote it.
1138 public static func fileResult(_ job: BabelJob, output: BabelOutput) -> (path: String, contents: String)? {
1139 guard job.finish.params.contains("file"), let file = job.finish.file, !job.finish.writesFile else { return nil }
1140 return (file, rawResult(job.finish, output))
1141 }
1142
1143 /// `org-babel-import-elisp-from-file`.
1144 static func importTable(_ results: String) -> Value {
1145 guard !results.isEmpty else { return .none }
1146 var lines = results.components(separatedBy: "\n")
1147 if lines.last == "" { lines.removeLast() }
1148 let nonEmpty = lines.filter { !$0.isEmpty }
1149 let rows: [[String]]
1150 if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains("\t") }) {
1151 rows = lines.map { $0.components(separatedBy: "\t") }
1152 } else if !nonEmpty.isEmpty, nonEmpty.allSatisfy({ $0.contains(",") }) {
1153 rows = lines.map(csvFields)
1154 } else if lines.count == 1 {
1155 rows = [[lines[0]]]
1156 } else {
1157 rows = lines.map { line in
1158 let trimmed = line.drop { $0 == " " }
1159 return trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init).isEmpty
1160 ? [""] : trimmed.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
1161 }
1162 }
1163 let cells = rows.map { row in row.map { field -> String in
1164 let trimmed = field.trimmingCharacters(in: .whitespaces)
1165 switch cell(trimmed) {
1166 case .number(let n): return n
1167 case .text(let t): return t
1168 }
1169 } }
1170 if cells.count == 1, cells[0].count == 1 { return .string(cells[0][0]) }
1171 return .table(cells)
1172 }
1173
1174 static func csvFields(_ line: String) -> [String] {
1175 var fields: [String] = []
1176 var current = ""
1177 var quoted = false
1178 for c in line {
1179 if c == "\"" {
1180 quoted.toggle()
1181 } else if c == ",", !quoted {
1182 fields.append(current.trimmingCharacters(in: .whitespaces))
1183 current = ""
1184 } else {
1185 current.append(c)
1186 }
1187 }
1188 fields.append(current.trimmingCharacters(in: .whitespaces))
1189 return fields
1190 }
1191
1192 /// `org-babel-python-table-or-string`.
1193 static func pythonValue(_ raw: String) -> Value {
1194 guard let first = raw.first, let last = raw.last, raw.count >= 2,
1195 (first == "[" && last == "]") || (first == "(" && last == ")") else {
1196 if raw.isEmpty { return .string("") }
1197 if raw.count > 2, (raw.hasPrefix("'") && raw.hasSuffix("'")) || (raw.hasPrefix("\"") && raw.hasSuffix("\"")) {
1198 return .string(String(raw.dropFirst().dropLast()))
1199 }
1200 if let n = number(raw) { return .string(n) }
1201 return .string(raw)
1202 }
1203 var parser = PythonLiteral(Array(raw))
1204 guard let parsed = parser.parse(), parser.atEnd, case .list(let items) = parsed else { return .string(raw) }
1205 func text(_ v: PythonLiteral.Node) -> String {
1206 switch v {
1207 case .atom(let s): return s
1208 case .string(let s): return s
1209 case .list(let xs): return "(" + xs.map(text).joined(separator: " ") + ")"
1210 }
1211 }
1212 if items.allSatisfy({ if case .list = $0 { return true }; if case .atom("None") = $0 { return true }; return false }) {
1213 return .table(items.map { item -> [String]? in
1214 if case .list(let cells) = item { return cells.map(text) }
1215 return nil
1216 })
1217 }
1218 return .table([items.map { if case .atom("None") = $0 { return "hline" }; return text($0) }])
1219 }
1220
1221 struct PythonLiteral {
1222 indirect enum Node: Equatable {
1223 case atom(String)
1224 case string(String)
1225 case list([Node])
1226 }
1227
1228 let chars: [Character]
1229 var i = 0
1230 init(_ chars: [Character]) { self.chars = chars }
1231 var atEnd: Bool { mutating get { skip(); return i == chars.count } }
1232
1233 mutating func skip() { while i < chars.count, chars[i] == " " || chars[i] == "\n" { i += 1 } }
1234
1235 mutating func parse() -> Node? {
1236 skip()
1237 guard i < chars.count else { return nil }
1238 let c = chars[i]
1239 if c == "[" || c == "(" {
1240 let close: Character = c == "[" ? "]" : ")"
1241 i += 1
1242 var items: [Node] = []
1243 skip()
1244 if i < chars.count, chars[i] == close {
1245 i += 1
1246 return .list(items)
1247 }
1248 while true {
1249 guard let item = parse() else { return nil }
1250 items.append(item)
1251 skip()
1252 guard i < chars.count else { return nil }
1253 if chars[i] == "," {
1254 i += 1
1255 skip()
1256 if i < chars.count, chars[i] == close {
1257 i += 1
1258 return .list(items)
1259 }
1260 continue
1261 }
1262 if chars[i] == close {
1263 i += 1
1264 return .list(items)
1265 }
1266 return nil
1267 }
1268 }
1269 if c == "'" || c == "\"" {
1270 i += 1
1271 var s = ""
1272 while i < chars.count, chars[i] != c {
1273 if chars[i] == "\\", i + 1 < chars.count {
1274 i += 1
1275 switch chars[i] {
1276 case "n": s.append("\n")
1277 case "t": s.append("\t")
1278 default: s.append(chars[i])
1279 }
1280 } else {
1281 s.append(chars[i])
1282 }
1283 i += 1
1284 }
1285 guard i < chars.count else { return nil }
1286 i += 1
1287 return .string(s)
1288 }
1289 var s = ""
1290 while i < chars.count, !",)] \n".contains(chars[i]) {
1291 s.append(chars[i])
1292 i += 1
1293 }
1294 guard !s.isEmpty else { return nil }
1295 return .atom(number(s) ?? s)
1296 }
1297 }
1298
1299 // MARK: - Inserting
1300
1301 static let resultKeyword = "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:"
1302
1303 /// `org-babel-where-is-src-block-result` with `insert`: the line of the block's results
1304 /// keyword, added when there is none.
1305 static func resultsLine(_ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) -> Int {
1306 let ns = buffer.text
1307 if let name = finish.name {
1308 let pattern = "(?im)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
1309 let regex = try! NSRegularExpression(pattern: pattern)
1310 for m in regex.matches(in: ns as String, range: NSRange(location: 0, length: ns.length)) {
1311 // Not the name of another block.
1312 return m.range.location
1313 }
1314 } else {
1315 // The element after the block, past blank lines.
1316 var location = block.upperBound
1317 while location < ns.length {
1318 let line = ns.lineRange(for: NSRange(location: location, length: 0))
1319 let content = ns.substring(with: line)
1320 if content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1321 location = NSMaxRange(line)
1322 continue
1323 }
1324 if content.range(of: "(?i)^[ \\t]*#\\+results(\\[[^\\]]*\\])?:[ \\t]*\\n?$", options: .regularExpression) != nil {
1325 return line.location
1326 }
1327 break
1328 }
1329 }
1330 // A new keyword after the block.
1331 buffer.point = min(block.upperBound, buffer.length)
1332 buffer.skipBackward([32, 9, 10, 13])
1333 buffer.forwardLine(1)
1334 if !buffer.bolp { buffer.insert("\n") }
1335 let indent = buffer.saveExcursion { () -> String in
1336 buffer.point = block.lowerBound
1337 let line = buffer.substring(buffer.lineStart(buffer.point), buffer.lineEnd(buffer.point))
1338 return String(line.prefix { $0 == " " || $0 == "\t" })
1339 }
1340 buffer.insert("\n")
1341 let keywordLine = buffer.point
1342 buffer.insert(indent + "#+RESULTS:" + (finish.name.map { " " + $0 } ?? "") + "\n")
1343 if buffer.looking("^[ \\t]*$", caseInsensitive: false, setsMatch: false) == nil {
1344 buffer.saveExcursion { buffer.insert("\n") }
1345 }
1346 return keywordLine
1347 }
1348
1349 /// `org-babel-result-end` with point at the start of the result.
1350 static func resultEnd(_ buffer: EmacsBuffer) -> Int {
1351 let start = buffer.point
1352 let line = buffer.substring(buffer.lineStart(start), buffer.lineEnd(start))
1353 if line.trimmingCharacters(in: .whitespaces).isEmpty { return start }
1354 if line.range(of: "^[ \\t]*\\[\\[[^\\]]+\\](\\[[^\\]]*\\])?\\][ \\t]*$", options: .regularExpression) != nil {
1355 return min(buffer.length, buffer.lineEnd(start) + 1)
1356 }
1357 let tree = OrgParser.parse(buffer.text as String)
1358 var node = tree.root
1359 var found: SyntaxNode?
1360 while let child = node.child(containing: start) {
1361 if child.range.lowerBound == start || (buffer.lineStart(child.range.lowerBound) == start) {
1362 if [.fixedWidth, .table, .plainList, .drawer, .block, .dynamicBlock, .latexFragment].contains(child.kind) {
1363 found = child
1364 break
1365 }
1366 }
1367 node = child
1368 }
1369 guard let element = found else { return start }
1370 var end = element.range.upperBound
1371 while end > start, let c = buffer.character(at: end - 1), c == 32 || c == 9 || c == 10 || c == 13 { end -= 1 }
1372 return min(buffer.length, buffer.lineEnd(end) + 1)
1373 }
1374
1375 /// `org-babel-insert-result` for a src block.
1376 /// An inline block's result, after it: ` {{{results(=value=)}}}`, replacing one already
1377 /// there; raw results go in as they are.
1378 static func insertInlineResult(_ value: Value, _ finish: BabelJob.Finish, at object: Range<Int>, buffer: EmacsBuffer) throws {
1379 var string: String
1380 switch value {
1381 case .none: string = ""
1382 case .string(let s): string = s
1383 case .table(let rows):
1384 let cells = rows.compactMap { $0 }
1385 guard cells.count == 1, cells[0].count == 1 else { throw Failure.message("Inline source block results can't be tables or lists") }
1386 string = cells[0][0]
1387 }
1388 buffer.point = object.upperBound
1389 if let existing = buffer.lookingAt("[ \\t]*\\{\\{\\{results\\(.*?\\)\\}\\}\\}") {
1390 buffer.deleteRegion(existing[0]!.lowerBound, existing[0]!.upperBound)
1391 }
1392 if finish.params.contains("raw") {
1393 buffer.insert(" " + string)
1394 return
1395 }
1396 if string.hasSuffix("\n") { string.removeLast() }
1397 guard !string.contains("\n") else { throw Failure.message("Inline source block results must be one line") }
1398 buffer.insert(" {{{results(=" + string + "=)}}}")
1399 }
1400
1401 static func insertResult(_ value: Value, _ finish: BabelJob.Finish, block: Range<Int>, buffer: EmacsBuffer) {
1402 let params = finish.params
1403 let keyword = resultsLine(finish, block: block, buffer: buffer)
1404 buffer.point = keyword
1405 let indent = buffer.substring(buffer.lineStart(keyword), buffer.lineEnd(keyword)).prefix { $0 == " " || $0 == "\t" }.count
1406 buffer.forwardLine(1)
1407 if buffer.point == buffer.lineEnd(keyword) { buffer.insert("\n") }
1408 var beg = buffer.point
1409 if params.contains("replace") {
1410 buffer.deleteRegion(beg, resultEnd(buffer))
1411 buffer.point = beg
1412 } else if params.contains("append") {
1413 buffer.point = resultEnd(buffer)
1414 beg = buffer.point
1415 }
1416 var tabulated = false
1417 switch value {
1418 case .none:
1419 break
1420 case .string(var s) where params.contains("list"):
1421 if s.last != "\n" { s += "\n" }
1422 let items = s.split(separator: "\n", omittingEmptySubsequences: true)
1423 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1424 case .table(let rows) where params.contains("list"):
1425 let items = rows.count == 1 ? (rows[0] ?? []) : rows.compactMap { $0?.joined(separator: " ") }
1426 buffer.insert(items.map { "- " + $0 }.joined(separator: "\n") + "\n")
1427 case .table(let rows):
1428 tabulated = true
1429 let lines = rows.map { row in row.map { "| " + $0.map { " " + $0 + " " }.joined(separator: "|").dropFirst() + " |" } ?? "|-" }
1430 let start = buffer.point
1431 buffer.insert(lines.joined(separator: "\n") + "\n")
1432 buffer.point = start
1433 buffer.tableAlign()
1434 buffer.point = buffer.tableEnd()
1435 case .string(var s):
1436 if !s.isEmpty, s.last != "\n" { s += "\n" }
1437 buffer.insert(s)
1438 }
1439 let end = buffer.marker(buffer.point, advances: true)
1440 defer { buffer.release(end) }
1441 func wrap(_ open: String, _ close: String, escape: Bool) {
1442 buffer.point = end.position
1443 buffer.insert(close + "\n")
1444 buffer.point = beg
1445 buffer.insert(open + "\n")
1446 if escape { escapeCode(buffer, from: buffer.point, to: end.position - close.utf16.count - 1) }
1447 }
1448 if let wrapValue = finish.wrap {
1449 let full = wrapValue.isEmpty ? "results" : wrapValue
1450 let type = String(full.split(separator: " ").first ?? "results")
1451 if type.lowercased() != "nil", type.lowercased() != "no" {
1452 wrap("#+begin_" + full, "#+end_" + type, escape: !["example", "src", "export"].contains(type.lowercased()) ? false : true)
1453 }
1454 } else if params.contains("html") {
1455 wrap("#+begin_export html", "#+end_export", escape: true)
1456 } else if params.contains("latex") {
1457 wrap("#+begin_export latex", "#+end_export", escape: true)
1458 } else if params.contains("org") {
1459 wrap("#+begin_src org", "#+end_src", escape: true)
1460 } else if params.contains("code") {
1461 wrap("#+begin_src \(finish.language.isEmpty ? "none" : finish.language)", "#+end_src", escape: true)
1462 } else if params.contains("raw") || params.contains("file") {
1463 // As inserted.
1464 } else if params.contains("drawer") {
1465 wrap(":results:", ":end:", escape: false)
1466 } else if !tabulated, !params.contains("list") {
1467 examplify(buffer, beg, end.position)
1468 }
1469 if indent > 0, !(tabulated && params.contains("append")) {
1470 buffer.point = beg
1471 while buffer.point < end.position {
1472 if !buffer.eolp { buffer.insert(String(repeating: " ", count: indent)) }
1473 if buffer.forwardLine(1) != 0 { break }
1474 }
1475 }
1476 }
1477
1478 /// `org-escape-code-in-region`.
1479 static func escapeCode(_ buffer: EmacsBuffer, from start: Int, to end: Int) {
1480 buffer.point = start
1481 let stop = buffer.marker(end)
1482 defer { buffer.release(stop) }
1483 while buffer.point < stop.position {
1484 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
1485 if let m = line.firstMatch(of: /^[ \t]*(,*(\*|#\+))/) {
1486 buffer.point += line[..<m.1.startIndex].utf16.count
1487 buffer.insert(",")
1488 }
1489 if buffer.forwardLine(1) != 0 { break }
1490 }
1491 }
1492
1493 /// `org-babel-examplify-region`: fewer than ten lines get `: `, more an example block.
1494 static func examplify(_ buffer: EmacsBuffer, _ beg: Int, _ end: Int) {
1495 let text = buffer.substring(beg, end)
1496 var size = text.components(separatedBy: "\n").count - (text.hasSuffix("\n") ? 1 : 0)
1497 if text.isEmpty { size = 0 }
1498 guard size > 0 else { return }
1499 if size < 10 {
1500 buffer.point = beg
1501 for _ in 0..<size {
1502 buffer.point = buffer.lineStart(buffer.point)
1503 buffer.insert(": ")
1504 buffer.forwardLine(1)
1505 }
1506 return
1507 }
1508 let endMarker = buffer.marker(end)
1509 defer { buffer.release(endMarker) }
1510 buffer.point = beg
1511 buffer.insert("#+begin_example\n")
1512 escapeCode(buffer, from: buffer.point, to: endMarker.position)
1513 buffer.point = endMarker.position
1514 if !buffer.bolp { buffer.insert("\n") }
1515 buffer.insert("#+end_example")
1516 if !buffer.eolp { buffer.insert("\n") }
1517 }
1518}
1519
1520/// C-c C-c in a src block: `org-babel-execute-src-block`.
1521public struct ExecuteSrcBlock: OrgCommand {
1522 public init() {}
1523 public var id: String { "org.babel.execute" }
1524 public var title: String { "Run Source Block" }
1525 public func applies(in context: EditContext) -> Bool { KeyContext.holds("src", in: context) || Self.atCallOrInline(context) }
1526
1527 /// On a `#+CALL:` line or an inline `src_` block.
1528 static func atCallOrInline(_ context: EditContext) -> Bool {
1529 let ns = context.text as NSString
1530 let line = ns.substring(with: ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0)))
1531 if line.range(of: "(?i)^[ \\t]*#\\+CALL:", options: .regularExpression) != nil { return true }
1532 var node = context.tree.root
1533 while let child = node.child(containing: context.caret) {
1534 if child.kind == .inlineSourceBlock { return true }
1535 node = child
1536 }
1537 return false
1538 }
1539
1540 public func run(in context: EditContext) -> CommandStep {
1541 switch Babel.plan(context) {
1542 case .success(let job): return .external(.babel(job))
1543 case .failure(.message(let message)): return .failed(message)
1544 }
1545 }
1546}