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