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