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