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