Commit 8a65cd2d5d

8a65cd2d5ddb0084d5206f86a4c3d19ff28965c5

parent: 6384ff6ccb

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 15:25 UTC

Babel: :var for ruby, js, R and awk; prologues for interpreted languages

:var for ruby, js, R and awk as their ob- files write them, ruby's and js's :results value through Emacs's wrappers, awk run with -v, :cmd-line and :in-file, and :prologue/:epilogue for shells, Python, Emacs Lisp, ruby, js, R and awk.

Closes #51

Layout: unified · split

Sources/OrgCore/Compute/Babel.swift +47 −13
@@ -58,7 +58,9 @@ public struct BabelJob: Sendable, Equatable {
58 58
59 public struct Finish: Sendable, Equatable { 59 public struct Finish: Sendable, Equatable {
60 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`. 60 /// `compiled`: C, C++, D, Java, Fortran and Clojure, by `language`.
61 enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled } 61 /// `script`: ruby and js, whose value comes back as their `inspect` prints it, from
62 /// the result file for ruby and the output for js.
63 enum Kind: Sendable, Equatable { case shell(valueIsExitStatus: Bool), python, generic, emacsLisp, compiled, script(js: Bool) }
62 let kind: Kind 64 let kind: Kind
63 var language = "" 65 var language = ""
64 public internal(set) var params: [String] 66 public internal(set) var params: [String]
@@ -351,8 +353,9 @@ public enum Babel {
351 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled { 353 if params.single[":cmdline"] != nil, !["dot", "plantuml", "mermaid"].contains(language), !shells.contains(language), !compiled {
352 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run.")) 354 return .failure(.message(":cmdline isn't supported for \(language) yet; nothing was run."))
353 } 355 }
356 let wraps = compiled || shells.contains(language) || ["python", "emacs-lisp", "elisp"].contains(language) || generic[language] != nil
354 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil 357 for key in [":prologue", ":epilogue", ":post", ":stdin", ":shebang"] where params.single[key] != nil
355 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(compiled && [":prologue", ":epilogue"].contains(key)) { 358 && !(shells.contains(language) && [":stdin", ":shebang"].contains(key)) && !(wraps && [":prologue", ":epilogue"].contains(key)) {
356 return .failure(.message("\(key) isn't supported yet; nothing was run.")) 359 return .failure(.message("\(key) isn't supported yet; nothing was run."))
357 } 360 }
358 // The compiled languages' `org-babel-execute:` ignore `:session`. 361 // The compiled languages' `org-babel-execute:` ignore `:session`.
@@ -435,7 +438,7 @@ public enum Babel {
435 // run it even with a session, which the script doesn't use. 438 // run it even with a session, which the script doesn't use.
436 var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n" 439 var script = (shebang ?? "#!/usr/bin/env \(executable)") + "\n"
437 if params.single[":padline"] != "no" { script += "\n" } 440 if params.single[":padline"] != "no" { script += "\n" }
438 script += (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "") 441 script += expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
439 let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "") 442 let command = Babel.scriptFileToken + (stdin != nil || cmdline != nil ? " " + (cmdline ?? "") : "")
440 var job = BabelJob( 443 var job = BabelJob(
441 language: language, runner: .process(executable: executable, arguments: ["-c", command]), 444 language: language, runner: .process(executable: executable, arguments: ["-c", command]),
@@ -445,7 +448,7 @@ public enum Babel {
445 job.script = script 448 job.script = script
446 return .success(job) 449 return .success(job)
447 } 450 }
448 let full = (lines + [body]).joined(separator: "\n") + (valueIsExitStatus ? "\necho $?" : "") 451 let full = expandGeneric(body, lines, params) + (valueIsExitStatus ? "\necho $?" : "")
449 return .success(BabelJob( 452 return .success(BabelJob(
450 language: language, runner: session.map { .session(name: $0, executable: executable, python: false) } ?? .process(executable: executable, arguments: []), 453 language: language, runner: session.map { .session(name: $0, executable: executable, python: false) } ?? .process(executable: executable, arguments: []),
451 input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir, 454 input: full.trimmingCharacters(in: .whitespacesAndNewlines) + "\n", directory: dir,
@@ -457,7 +460,7 @@ public enum Babel {
457 // `org-babel-python--eval-ast`: the body at top level in the session, the value its 460 // `org-babel-python--eval-ast`: the body at top level in the session, the value its
458 // last expression's. 461 // last expression's.
459 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" } 462 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
460 let source = (lines + [body]).joined(separator: "\n") 463 let source = expandGeneric(body, lines, params)
461 let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast() 464 let literal = String(data: try! JSONSerialization.data(withJSONObject: [source]), encoding: .utf8)!.dropFirst().dropLast()
462 let program: String 465 let program: String
463 if output { 466 if output {
@@ -480,7 +483,7 @@ public enum Babel {
480 } 483 }
481 if language == "python" { 484 if language == "python" {
482 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" } 485 let lines = vars.map { "\($0.0)=\(pythonLiteral($0.1))" }
483 var full = (lines + [body]).joined(separator: "\n") 486 var full = expandGeneric(body, lines, params)
484 if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" } 487 if let returnValue = params.single[":return"], !output { full += "\nreturn \(returnValue)" }
485 let input: String 488 let input: String
486 if output { 489 if output {
@@ -497,7 +500,10 @@ public enum Babel {
497 } 500 }
498 if language == "emacs-lisp" || language == "elisp" { 501 if language == "emacs-lisp" || language == "elisp" {
499 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" } 502 let bindings = vars.map { "(\($0.0) '\(lispLiteral($0.1)))" }
500 let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(body)\n)" 503 // `org-babel-expand-body:emacs-lisp` adds the prologue and epilogue only with variables.
504 let prologue = params.single[":prologue"].map { $0 + "\n " } ?? ""
505 let epilogue = params.single[":epilogue"].map { "\n " + $0 + "\n" } ?? ""
506 let expanded = bindings.isEmpty ? body + "\n" : "(let (\(bindings.joined(separator: "\n ")))\n\(prologue)\(body)\(epilogue)\n)"
501 let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)" 507 let form = output ? "(with-output-to-string \(expanded))" : "(progn \(expanded)\n)"
502 var job = BabelJob( 508 var job = BabelJob(
503 language: language, runner: .emacs, input: emacsScript(form: form, params: params.results), 509 language: language, runner: .emacs, input: emacsScript(form: form, params: params.results),
@@ -552,12 +558,40 @@ public enum Babel {
552 } 558 }
553 } 559 }
554 if let (executable, arguments) = generic[language] { 560 if let (executable, arguments) = generic[language] {
555 guard vars.isEmpty else { return .failure(.message(":var isn't supported for \(language) yet.")) } 561 switch language {
556 return .success(BabelJob( 562 case "ruby":
557 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments), 563 let full = expandGeneric(body, vars.map { "\($0.0)=\(rubyLiteral($0.1))" }, params)
558 input: body + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, 564 return .success(BabelJob(
559 finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline, hash: hash) 565 language: language, runner: .process(executable: params.single[":ruby"] ?? executable, arguments: arguments),
560 )) 566 input: output ? full : rubyWrapper(full, pp: params.results.contains("pp")), directory: dir, block: location, blockText: blockText,
567 alwaysAsk: alwaysAsk, finish: finishBase(.script(js: false))
568 ))
569 case "js", "javascript":
570 let full = expandGeneric(body, vars.map { "var \($0.0)=\(jsLiteral($0.1));" }, params)
571 return .success(BabelJob(
572 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
573 input: output ? full : jsWrapper(full), directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
574 finish: finishBase(.script(js: true))
575 ))
576 case "awk":
577 // `org-babel-expand-body:awk`; the variables go on the command line.
578 let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
579 return .success(BabelJob(
580 language: language, runner: .process(executable: "/bin/sh", arguments: ["-c", awkCommand(vars, params: params)]),
581 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
582 finish: finishBase(.shell(valueIsExitStatus: false))
583 ))
584 default:
585 let lines = language == "R" ? vars.map { name, value in
586 rAssignment(name, value, colnames: tables.colnames.first { $0.0 == name }?.1, colnamesYes: params.single[":colnames"] == "yes",
587 rownamesYes: params.single[":rownames"] == "yes")
588 } : []
589 return .success(BabelJob(
590 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
591 input: expandGeneric(body, lines, params) + "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
592 finish: BabelJob.Finish(kind: .generic, language: language, params: params.results + (output ? [] : ["output"]), output: true, wrap: params.wrap, name: name, inline: inline, hash: hash)
593 ))
594 }
561 } 595 }
562 return .failure(.message("No way to run \(language) blocks yet.")) 596 return .failure(.message("No way to run \(language) blocks yet."))
563 } 597 }
Sources/OrgCore/Compute/BabelResults.swift +6
@@ -85,6 +85,11 @@ extension Babel {
85 return printed == "nil" ? .none : .string(printed) 85 return printed == "nil" ? .none : .string(printed)
86 case .compiled: 86 case .compiled:
87 return compiledValue(finish, output, scalar: scalar) 87 return compiledValue(finish, output, scalar: scalar)
88 case .script(let js):
89 let raw = rawResult(finish, output)
90 if scalar { return .string(raw) }
91 // `org-babel-ruby-table-or-string`, its nils rules.
92 return js ? jsValue(raw) : pythonValue(raw, none: "nil", braces: true)
88 } 93 }
89 } 94 }
90 95
@@ -99,6 +104,7 @@ extension Babel {
99 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout 104 return valueIsExitStatus ? output.stdout.split(separator: "\n").last.map(String.init) ?? "" : output.stdout
100 case .generic: return output.stdout 105 case .generic: return output.stdout
101 case .compiled: return compiledResult(finish, output) 106 case .compiled: return compiledResult(finish, output)
107 case .script(let js): return finish.output || js ? output.stdout : (output.resultFile ?? "")
102 } 108 }
103 } 109 }
104 110
Sources/OrgCore/Compute/BabelScripts.swift added +133
@@ -0,0 +1,133 @@
1import Foundation
2
3// Variables, `:prologue` and `:epilogue` for the interpreted languages (ob-ruby, ob-js, ob-R,
4// ob-awk, Org 9.8.7), and how ob-ruby and ob-js return a block's value.
5
6extension Babel {
7 /// `org-babel-expand-body:generic`: the prologue, the variables, the body and the epilogue,
8 /// a line apart.
9 static func expandGeneric(_ body: String, _ lines: [String], _ params: Params) -> String {
10 ((params.single[":prologue"].map { [$0] } ?? []) + lines + [body] + (params.single[":epilogue"].map { [$0] } ?? [])).joined(separator: "\n")
11 }
12
13 /// `org-babel-ruby-var-to-ruby`: lists in brackets, a rule `nil`, the rest as `prin1`.
14 static func rubyLiteral(_ value: VarValue) -> String {
15 func cell(_ c: Cell) -> String {
16 switch c {
17 case .number(let n): n
18 case .text(let s): lispString(s)
19 }
20 }
21 switch value {
22 case .scalar(let s): return lispString(s)
23 case .number(let n): return n
24 case .list(let items): return "[" + items.map(cell).joined(separator: ", \n") + "]"
25 case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", \n") + "]" } ?? "nil" }.joined(separator: ", \n") + "]"
26 }
27 }
28
29 /// `org-babel-js-var-to-js`: lists in brackets, the rest as `prin1` with newlines as `\n`.
30 static func jsLiteral(_ value: VarValue) -> String {
31 func atom(_ printed: String) -> String { printed.replacingOccurrences(of: "\n", with: "\\n") }
32 func cell(_ c: Cell) -> String {
33 switch c {
34 case .number(let n): n
35 case .text(let s): atom(lispString(s))
36 }
37 }
38 switch value {
39 case .scalar(let s): return atom(lispString(s))
40 case .number(let n): return n
41 case .list(let items): return "[" + items.map(cell).joined(separator: ", ") + "]"
42 case .table(let rows): return "[" + rows.map { $0.map { "[" + $0.map(cell).joined(separator: ", ") + "]" } ?? "hline" }.joined(separator: ", ") + "]"
43 }
44 }
45
46 /// `org-babel-R-assign-elisp`: a table or list read from its TSV text, an integer with `L`,
47 /// a float or a string as they print. `colnames` are the header row `:colnames` took off,
48 /// which ob-R puts back.
49 static func rAssignment(_ name: String, _ value: VarValue, colnames: [Cell]?, colnamesYes: Bool, rownamesYes: Bool) -> String {
50 // `orgtbl-to-tsv` makes every field a string, which `org-babel-R-quote-tsv-field` quotes.
51 func field(_ c: Cell) -> String { "\"" + cellText(c).replacingOccurrences(of: "\"", with: "\"\"") + "\"" }
52 var rows: [[Cell]?]
53 switch value {
54 case .scalar(let s): return "\(name) <- \(lispString(s))"
55 case .number(let n): return "\(name) <- " + (n.contains(where: { ".eE".contains($0) }) ? n : n + "L")
56 case .list(let items): rows = items.map { [$0] }
57 case .table(let table): rows = table
58 }
59 if let colnames { rows = [colnames, nil] + rows }
60 let lengths = rows.compactMap { $0?.count }
61 let tsv = rows.compactMap { $0.map { $0.map(field).joined(separator: "\t") } }.joined(separator: "\n")
62 let header = (rows.count > 1 && rows[1] == nil) || colnamesYes ? "TRUE" : "FALSE"
63 let rowNames = rownamesYes ? "1" : "NULL"
64 let common = """
65 \(name) <- local({
66 con <- textConnection(
67 \(lispString(tsv))
68 )
69 res <- utils::read.table(
70 con,
71 header = \(header),
72 row.names = \(rowNames),
73 sep = "\\t",
74 as.is = TRUE
75 """
76 if lengths.max() == lengths.min() {
77 return common + "\n )\n close(con)\n res\n })"
78 }
79 return common + ",\n fill = TRUE,\n col.names = paste(\"V\", seq_len(\(lengths.max() ?? 0)), sep =\"\")\n )\n close(con)\n res\n })"
80 }
81
82 /// `org-babel-ruby-wrapper-method` and `org-babel-ruby-pp-wrapper-method`: the body's
83 /// value written to the result file.
84 static func rubyWrapper(_ body: String, pp: Bool) -> String {
85 pp ? """
86
87 require 'pp'
88 results = (lambda do
89 \(body)
90 end).call
91 File.open('\(resultFileToken)', 'w') do |f|
92 $stdout = f
93 pp results
94 end
95
96 """ : """
97
98 results = (lambda do
99 \(body)
100 end).call
101 File.open('\(resultFileToken)', 'w'){ |f| f.write((results.class == String) ? results : results.inspect) }
102
103 """
104 }
105
106 /// `org-babel-js-function-wrapper`: the body's value printed with `util.inspect`.
107 static func jsWrapper(_ body: String) -> String {
108 "require('process').stdout.write(require('util').inspect(function(){\(body)\n}()));"
109 }
110
111 /// `org-babel-awk-command`'s command line: the program in a file, `:cmd-line`, a `-v` for
112 /// each variable, and `:in-file`.
113 static func awkCommand(_ vars: [(String, VarValue)], params: Params) -> String {
114 var parts = ["awk", "-f", "\"$f\""]
115 if let cmdline = params.single[":cmd-line"] { parts.append(cmdline) }
116 parts += vars.map { "-v \($0.0)='\(shellString($0.1))'" }
117 if let file = params.single[":in-file"] { parts.append(file) }
118 return "f=$(mktemp); cat > \"$f\"; " + parts.joined(separator: " ") + " < /dev/null; s=$?; rm -f \"$f\"; exit $s"
119 }
120}
121
122extension Babel {
123 /// `org-babel-js-read`: an array read as a list once its quotes and commas are Lisp's;
124 /// otherwise `org-babel-read`, which takes a quoted word as the symbol it names.
125 static func jsValue(_ raw: String) -> Value {
126 if raw.hasPrefix("["), raw.hasSuffix("]") { return pythonValue(raw, none: "\u{0}") }
127 if raw.hasPrefix("'") {
128 return .string(String(raw.dropFirst().prefix { !$0.isWhitespace && !"()\"';".contains($0) }))
129 }
130 if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 { return .string(String(raw.dropFirst().dropLast())) }
131 return .string(raw)
132 }
133}
Tests/OrgCoreTests/BabelScriptTests.swift added +98
@@ -0,0 +1,98 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `:var`, `:prologue` and `:epilogue` for the interpreted languages, and ruby's and js's
6/// values, run here and in Emacs.
7struct BabelScriptTests {
8 static let table = "#+NAME: tbl\n| 1 | 2 |\n| 3 | 4 |\n\n"
9 static let headed = "#+NAME: hd\n| a | b |\n|---+---|\n| 1 | 2 |\n\n"
10
11 static let cases: [String] = [
12 // Ruby.
13 "#+begin_src ruby :var x=3 y=\"hi\"\nx * 2\n#+end_src\n",
14 "#+begin_src ruby :var x=3 y=\"hi\" :results output\nputs y * x\n#+end_src\n",
15 table + "#+begin_src ruby :var t=tbl\nt.map { |r| r.sum }\n#+end_src\n",
16 table + "#+begin_src ruby :var t=tbl\nt.map { |r| r.map { |c| c * 10 } }\n#+end_src\n",
17 "#+begin_src ruby :var l='(1 2 3)\nl.reverse\n#+end_src\n",
18 "#+begin_src ruby :var s=\"a\\\"b\"\ns.length\n#+end_src\n",
19 "#+begin_src ruby\n[[1, 2], nil, [3, 4]]\n#+end_src\n",
20 "#+begin_src ruby\n\"plain\"\n#+end_src\n",
21 "#+begin_src ruby :prologue x = 5 :epilogue x + 1\nx = x * 2\n#+end_src\n",
22 "#+begin_src ruby :results output :prologue puts \"first\" :epilogue puts \"last\"\nputs \"body\"\n#+end_src\n",
23 headed + "#+begin_src ruby :var t=hd\nt.length\n#+end_src\n",
24 // JavaScript.
25 "#+begin_src js :var x=3\nreturn x * 2\n#+end_src\n",
26 "#+begin_src js :var x=3 :results output\nconsole.log(x + 1)\n#+end_src\n",
27 table + "#+begin_src js :var t=tbl\nreturn t.map(r => r[0] + r[1])\n#+end_src\n",
28 table + "#+begin_src js :var t=tbl\nreturn t\n#+end_src\n",
29 "#+begin_src js :var s=\"two words\"\nreturn s.length\n#+end_src\n",
30 "#+begin_src js :prologue var k = 7; :epilogue return k;\nk = k * 6;\n#+end_src\n",
31 "#+begin_src js\nreturn 'abc'\n#+end_src\n",
32 "#+begin_src js :results output :epilogue console.log('end')\nconsole.log('body')\n#+end_src\n",
33 // awk.
34 "#+begin_src awk :var n=5\nBEGIN { print n * 2 }\n#+end_src\n",
35 table + "#+begin_src awk :var t=tbl\nBEGIN { print t }\n#+end_src\n",
36 "#+begin_src awk :prologue BEGIN { x = 1 } :epilogue BEGIN { print \"end\" }\nBEGIN { print x + 1 }\n#+end_src\n",
37 "#+begin_src awk :cmd-line -v y=3\nBEGIN { print y }\n#+end_src\n",
38 "#+begin_src awk :results output\nBEGIN { print \"a b\"; print \"c d\" }\n#+end_src\n",
39 // Shell, Python and Emacs Lisp prologues.
40 "#+begin_src sh :prologue x=1 :epilogue echo end :results output\necho $x\n#+end_src\n",
41 "#+begin_src sh :var y=2 :prologue echo start :results output\necho $y\n#+end_src\n",
42 "#+begin_src python :prologue import math\nreturn math.floor(2.5)\n#+end_src\n",
43 "#+begin_src python :results output :prologue print('a') :epilogue print('c')\nprint('b')\n#+end_src\n",
44 "#+begin_src emacs-lisp :var x=1 :prologue \"(setq y 2)\" :epilogue \"(* x 10)\"\n(+ x y)\n#+end_src\n",
45 "#+begin_src emacs-lisp :prologue \"(error \\\"never\\\")\"\n1\n#+end_src\n",
46 ]
47
48 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
49 && BabelCompiledTests.installed("ruby") && BabelCompiledTests.installed("node")))
50 func scriptsMatchEmacs() throws {
51 let folder = FileManager.default.temporaryDirectory
52 var emacsCases: [EmacsOracle.Case] = []
53 var ours: [(text: String, failure: String?)] = []
54 for text in Self.cases {
55 let caret = (text as NSString).range(of: "#+begin_src").location + 2
56 ours.append(try TestBabelRunner.execute(text, caret: caret, directory: folder))
57 emacsCases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
58 (progn (require 'ob-ruby) (require 'ob-js) (require 'ob-awk) (require 'ob-shell) (require 'ob-python)
59 (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" org-babel-python-command "python3" default-directory temporary-file-directory)
60 (org-babel-execute-src-block))
61 """))
62 }
63 let emacs = try EmacsOracle.run(emacsCases)
64 for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
65 #expect(mine.text == theirs.text, "case \(i):\n\(Self.cases[i])\nours (\(mine.failure ?? "")):\n\(mine.text)\nemacs (\(theirs.error)):\n\(theirs.text)")
66 }
67 }
68
69 /// R isn't needed to compare what ob-R sends it.
70 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
71 func rExpansionMatchesEmacs() throws {
72 let blocks = [
73 "#+begin_src R :var x=3 y=1.5 s=\"a \\\"q\\\"\"\nx + y\n#+end_src\n",
74 Self.table + "#+begin_src R :var t=tbl :prologue library(stats) :epilogue print(t)\nsummary(t)\n#+end_src\n",
75 Self.headed + "#+begin_src R :var t=hd\nt$a\n#+end_src\n",
76 "#+NAME: ragged\n| 1 | 2 |\n| 3 |\n\n#+begin_src R :var r=ragged\nr\n#+end_src\n",
77 "#+begin_src R :var l='(1 \"two\" 3)\nl\n#+end_src\n",
78 ]
79 var cases: [EmacsOracle.Case] = []
80 var ours: [String] = []
81 for text in blocks {
82 let caret = (text as NSString).range(of: "#+begin_src").location + 2
83 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
84 (progn (require 'ob-R)
85 (let* ((info (org-babel-get-src-block-info)) (params (org-babel-process-params (nth 2 info)))
86 (expanded (org-babel-expand-body:R (nth 1 info) params)))
87 (erase-buffer) (insert expanded)))
88 """))
89 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
90 guard case .success(let job) = Babel.plan(context) else { ours.append("no job"); continue }
91 ours.append(String(job.input.dropLast()))
92 }
93 let results = try EmacsOracle.run(cases)
94 for (i, (mine, theirs)) in zip(ours, results).enumerated() {
95 #expect(mine == theirs.text, "case \(i): \(theirs.error)\nours:\n\(mine)\nemacs:\n\(theirs.text)")
96 }
97 }
98}
docs/manual/guide/11-code-blocks.org +16 −8
@@ -90,14 +90,14 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a
90| =shell= | The shell in =SHELL=, or =/bin/sh= | 90| =shell= | The shell in =SHELL=, or =/bin/sh= |
91| =python= | =python3=, or the program in =:python= | 91| =python= | =python3=, or the program in =:python= |
92| =emacs-lisp=, =elisp= | =emacs -Q --batch=; see Emacs Lisp blocks below | 92| =emacs-lisp=, =elisp= | =emacs -Q --batch=; see Emacs Lisp blocks below |
93| =ruby= | =ruby= | 93| =ruby= | =ruby=, or the program in =:ruby= |
94| =js=, =javascript= | =node= | 94| =js=, =javascript= | =node= |
95| =R= | =Rscript -= | 95| =R= | =Rscript -= |
96| =awk= | =awk -f /dev/stdin= | 96| =awk= | =awk -f=, the program written to a file |
97| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below | 97| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below |
98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below | 98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
99 99
100For =ruby=, =js=, =javascript=, =R= and =awk=, =:cmd= names a different program. These languages always return their standard output, and =:var= is refused for them. 100For =js=, =javascript= and =R=, =:cmd= names a different program. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
101 101
102Any other language is refused with "No way to run /language/ blocks yet." 102Any other language is refused with "No way to run /language/ blocks yet."
103 103
@@ -206,7 +206,10 @@ What "value" means depends on the language:
206| Python | What the block returns. The body runs as a function, so it needs =return=. =:return expr= adds a final =return expr=. | 206| Python | What the block returns. The body runs as a function, so it needs =return=. =:return expr= adds a final =return expr=. |
207| Python in a =:session= | The value of the last expression. | 207| Python in a =:session= | The value of the last expression. |
208| Emacs Lisp | The value of the last form. | 208| Emacs Lisp | The value of the last form. |
209| =ruby=, =js=, =R=, =awk= | Standard output, always. | 209| =ruby= | The value of the body, run as a lambda; strings as they are, other values as =inspect= prints them, arrays read as tables with =nil= rows as rules. =:results pp= prints it with =pp=. |
210| =js=, =javascript= | What the body returns, as =util.inspect= prints it, arrays read as tables; it runs as a function, so it needs =return=. |
211| =awk= | Standard output, read as a table as for shells. |
212| =R= | Standard output, always. |
210| C, C++, D | Standard output without its common indentation, read as a table as for shells. | 213| C, C++, D | Standard output without its common indentation, read as a table as for shells. |
211| Fortran | The same, with blank space around the output trimmed. | 214| Fortran | The same, with blank space around the output trimmed. |
212| Java | With =:results value=, what the body returns; it runs as =main=, so it needs =return=. Lists and arrays become tables, with =null= rows as rules, and a returned string is written without its quotes. Java's default is =:results output=. | 215| Java | With =:results value=, what the body returns; it runs as =main=, so it needs =return=. Lists and arrays become tables, with =null= rows as rules, and a returned string is written without its quotes. Java's default is =:results output=. |
@@ -362,7 +365,8 @@ A string or number takes the place of the form. Lisp that the interpreter cannot
362| =:shebang= | =#!…= line | Runs the block as a script with this first line. Shells only; also used by tangling. | 365| =:shebang= | =#!…= line | Runs the block as a script with this first line. Shells only; also used by tangling. |
363| =:padline= | =no= | No blank line after the shebang of a script, or between tangled blocks. | 366| =:padline= | =no= | No blank line after the shebang of a script, or between tangled blocks. |
364| =:python= | program | Python interpreter to use. | 367| =:python= | program | Python interpreter to use. |
365| =:cmd= | program | Interpreter for =ruby=, =js=, =javascript=, =R= and =awk=. | 368| =:cmd= | program | Interpreter for =js=, =javascript= and =R=; =:ruby= for =ruby=. |
369| =:cmd-line=, =:in-file= | arguments, file | =awk=: arguments after the program, and the file it reads. |
366| =:return= | expression | Python: the value to return. | 370| =:return= | expression | Python: the value to return. |
367| =:cache= | =yes=, =no= | Skip the run when the result is current (see Caching below). | 371| =:cache= | =yes=, =no= | Skip the run when the result is current (see Caching below). |
368| =:eval= | =never=, =no=, =query=, … | Whether and how to ask before running (see =:eval= above). | 372| =:eval= | =never=, =no=, =query=, … | Whether and how to ask before running (see =:eval= above). |
@@ -379,11 +383,11 @@ orgstar does not run a block whose arguments it would handle differently from Em
379 383
380| Argument | Refused for | Message | 384| Argument | Refused for | Message |
381|-----------------------------+-------------------------------------------------+----------------------------------------------------------| 385|-----------------------------+-------------------------------------------------+----------------------------------------------------------|
382| =:prologue=, =:epilogue=, =:post= | every language when running, except =:prologue= and =:epilogue= for the compiled languages (tangling uses =:prologue= and =:epilogue=) | "=:prologue= isn't supported yet; nothing was run." | 386| =:prologue=, =:epilogue= | graphics (=dot=, =plantuml=, =mermaid=) | "=:prologue= isn't supported yet; nothing was run." |
387| =:post= | every language | "=:post= isn't supported yet; nothing was run." |
383| =:stdin=, =:shebang= | languages other than shells | "=:stdin= isn't supported yet; nothing was run." | 388| =:stdin=, =:shebang= | languages other than shells | "=:stdin= isn't supported yet; nothing was run." |
384| =:cmdline= | languages other than shells, graphics and the compiled languages | "=:cmdline= isn't supported for /language/ yet; nothing was run." | 389| =:cmdline= | languages other than shells, graphics and the compiled languages | "=:cmdline= isn't supported for /language/ yet; nothing was run." |
385| =:session= | languages other than shells, Python and the compiled languages, which ignore it | "=:session= isn't supported for /language/ yet; nothing was run." | 390| =:session= | languages other than shells, Python and the compiled languages, which ignore it | "=:session= isn't supported for /language/ yet; nothing was run." |
386| =:var= | =ruby=, =js=, =javascript=, =R=, =awk= | "=:var= isn't supported for /language/ yet." |
387 391
388* Variables 392* Variables
389 393
@@ -425,8 +429,12 @@ How a value reaches the code depends on the language:
425| fish | =set name 'value'= | as other shells | as other shells | 429| fish | =set name 'value'= | as other shells | as other shells |
426| Python | literal | list | list of lists, =None= for rules | 430| Python | literal | list | list of lists, =None= for rules |
427| Emacs Lisp | =let=-bound value | list | list of lists, =hline= for rules | 431| Emacs Lisp | =let=-bound value | list | list of lists, =hline= for rules |
432| Ruby | =name=value= literal | array | array of arrays, =nil= for rules |
433| JavaScript | =var name=value;= | array | array of arrays, =hline= for rules |
434| R | =name <- value=, integers with =L= | one-column data frame | data frame read from tab-separated text, a header when the table has one |
435| awk | =-v name='value'= | one item per line | rows on lines, cells separated by a tab |
428 436
429For =shell= blocks, the bash forms are used when =SHELL= is bash. C, C++, D, Java, Fortran and Clojure blocks get declarations as their expansion writes them; see Tangling below. 437For =shell= blocks, the bash forms are used when =SHELL= is bash. =:prologue= and =:epilogue= add a line before the variables and one after the body, in every language that runs; in Emacs Lisp only when the block has variables, as =org-babel-expand-body:emacs-lisp= does. C, C++, D, Java, Fortran and Clojure blocks get declarations as their expansion writes them; see Tangling below.
430 438
431#+BEGIN_SRC org 439#+BEGIN_SRC org
432,#+NAME: kv 440,#+NAME: kv
docs/manual/guide/15-alongside-emacs.org +2 −2
@@ -214,10 +214,10 @@ orgstar refuses some things with a message rather than doing something different
214Code blocks (see [[file:11-code-blocks.org][Code blocks]]): 214Code blocks (see [[file:11-code-blocks.org][Code blocks]]):
215 215
216- =:cmdline= is supported only for shells, =dot=, =plantuml=, =mermaid= and C, C++, D, Java, Fortran and Clojure. 216- =:cmdline= is supported only for shells, =dot=, =plantuml=, =mermaid= and C, C++, D, Java, Fortran and Clojure.
217- =:post= isn't supported; =:prologue= and =:epilogue= only for C, C++, D, Java, Fortran and Clojure; =:stdin= and =:shebang= only for shells. 217- =:post= isn't supported; =:prologue= and =:epilogue= aren't for =dot=, =plantuml= and =mermaid=; =:stdin= and =:shebang= only for shells.
218- =:session= is supported only for shells and Python. C, C++, D, Java, Fortran and Clojure ignore it, as in Org. 218- =:session= is supported only for shells and Python. C, C++, D, Java, Fortran and Clojure ignore it, as in Org.
219- Clojure runs with babashka or the Clojure CLI only; other =:backend= values are refused. 219- Clojure runs with babashka or the Clojure CLI only; other =:backend= values are refused.
220- =:var= isn't supported for Ruby, JavaScript, R and awk blocks. 220- R blocks return their standard output, whatever =:results= says; ob-R returns the value with =:results value=.
221- Header arguments, =:var= values and =:cache= that need Lisp evaluated by Emacs are refused when orgstar's interpreter can't evaluate them: "… is Lisp that only Emacs can evaluate; nothing was run." 221- Header arguments, =:var= values and =:cache= that need Lisp evaluated by Emacs are refused when orgstar's interpreter can't evaluate them: "… is Lisp that only Emacs can evaluate; nothing was run."
222- Noweb references that run a block aren't supported. 222- Noweb references that run a block aren't supported.
223- Tangling refuses =:var= that would run a block, and tables and lists in =:var= for some languages. 223- Tangling refuses =:var= that would run a block, and tables and lists in =:var= for some languages.