Commit e1afdafd04

e1afdafd04487f57291d2d8523db06ea480c88a0

parent: 4916f87658

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 10:30 UTC

Match org-sbe on :lexical t, COMMENT headings and function values, and gate it on Babel

Layout: unified · split

Sources/OrgCore/Compute/TableSbe.swift +45 −7
@@ -9,12 +9,19 @@ import Foundation
99public enum TableBlocks {
1010 /// Runs a js job to the end on the calling thread; nil when it can't. The app sets it.
1111 nonisolated(unsafe) public static var javaScript: ((BabelJob) throws -> BabelOutput?)?
12 /// Whether `org-sbe` may run; the app ties it to running source blocks.
13 nonisolated(unsafe) public static var allowed: () -> Bool = { true }
14 /// The reason a table goes to the app when `allowed` is false.
15 public static let lockedReason = "Lisp org-sbe with source blocks locked"
1216}
1317
1418extension Babel {
1519 /// Defines `org-sbe` for formulas in the file whose text `text` gives.
1620 static func defineSbe(_ lisp: Elisp, text: @escaping () -> String) {
17 lisp.defineForm("org-sbe") { _, args in .string(try sbe(args, text: text())) }
21 lisp.defineForm("org-sbe") { _, args in
22 guard TableBlocks.allowed() else { throw Elisp.Unsupported(what: "org-sbe with source blocks locked") }
23 return .string(try sbe(args, text: text()))
24 }
1825 }
1926
2027 /// The macro's value: `(org-trim (format "%S" result))`, or the result when it is a string.
@@ -82,16 +89,40 @@ extension Babel {
8289 let ns = text as NSString
8390 let model = DocumentModel(tree: OrgParser.parse(text))
8491 let options = Options()
85 // The first `#+NAME:` line with the name: a src block's, or another element's.
92 // The first `#+NAME:` line with the name outside COMMENTed headings that names an
93 // element: a src block's, or another element's.
8694 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
87 guard let named = text.range(of: pattern, options: .regularExpression) else { throw notFound(name, text: text) }
88 let start = NSRange(named, in: text).location
95 let matches = try NSRegularExpression(pattern: pattern).matches(in: text, range: NSRange(location: 0, length: ns.length)).map(\.range)
96 let headingStarts = model.headings.map(\.headingRange.lowerBound)
97 func commented(_ location: Int) -> Bool {
98 guard let h = headingStarts.lastIndex(where: { $0 <= location }) else { return false }
99 return ([h] + model.ancestors(of: h)).contains { model.headings[$0].title == "COMMENT" || model.headings[$0].title.hasPrefix("COMMENT ") }
100 }
101 // A keyword followed by a blank line, after any other affiliated keywords, names nothing.
102 func orphaned(_ match: NSRange) -> Bool {
103 var location = NSMaxRange(ns.lineRange(for: match))
104 while location < ns.length {
105 let line = ns.lineRange(for: NSRange(location: location, length: 0))
106 let content = ns.substring(with: line)
107 if content.range(of: "(?i)^[ \\t]*#\\+(name|caption|header|plot|results|attr_[-\\w]+)(\\[.*\\])?:", options: .regularExpression) == nil {
108 return content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
109 }
110 location = NSMaxRange(line)
111 }
112 return true
113 }
114 guard let named = matches.first(where: { !commented($0.location) && !orphaned($0) }) else { throw notFound(name, text: text) }
115 let start = named.location
89116 let block = model.srcBlocks.first { block in
90117 guard block.name == name, block.range.lowerBound > start else { return false }
91118 let between = ns.substring(with: NSRange(location: start, length: block.range.lowerBound - start))
92119 return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") }
93120 }
94121 guard let block else {
122 // `resolve` reads the first element with the name, and runs a src block before it.
123 guard named == matches.first, !model.srcBlocks.contains(where: { $0.name == name }) else {
124 throw Elisp.Unsupported(what: "org-sbe with a name used more than once")
125 }
95126 do {
96127 return try sbeSexp(resolve(name, model: model, text: ns, refs: References(resolved: [:], options: options)))
97128 } catch let failure as Failure {
@@ -118,7 +149,14 @@ extension Babel {
118149 refs.resolved[need.reference] = varValue(need.job.finish, try sbeRun(need.job))
119150 continue
120151 }
121 return try sbeValue(job, lexical: params.single[":lexical"] == "yes")
152 // `org-babel-emacs-lisp-lexical`: "yes" and "t" are lexical; other Lisp is read.
153 let lexical: Bool
154 switch params.single[":lexical"] {
155 case "yes", "t": lexical = true
156 case nil, "no", "nil": lexical = false
157 default: throw Elisp.Unsupported(what: "org-sbe with this :lexical")
158 }
159 return try sbeValue(job, lexical: lexical)
122160 }
123161 }
124162 }
@@ -149,13 +187,13 @@ extension Babel {
149187 || params.contains("pp") || ((params.contains("output") || params.contains("raw") || params.contains("org")) && !params.contains("table"))
150188 var result: Sexp
151189 if let form = job.lispForm {
152 // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical yes`.
190 // `org-babel-execute:emacs-lisp`: dynamic binding unless `:lexical` is yes or t.
153191 let lisp = Elisp()
154192 lisp.lexical = lexical
155193 lisp.syntax = .emacsLisp
156194 lisp.standardTime()
157195 result = try lisp.eval(try LispReader.readFirst(form).sexp)
158 if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a closure") }
196 if Elisp.containsFunction(result) { throw Elisp.Unsupported(what: "org-sbe with a function value") }
159197 if scalar {
160198 result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result]))
161199 }
Tests/OrgCoreTests/TableSbeTests.swift +44
@@ -76,6 +76,15 @@ struct TableSbeTests {
7676 blocks + "| n | out | quad | oops | data | items | verbatim | empty | two |\n|---+-----+------+------+------+-------+----------+-------+-----|\n| 4 | | | | | | | | |\n"
7777 + "#+TBLFM: $2='(org-sbe out (x $1))::$3='(org-sbe quad)::$4='(org-sbe oops)::$5='(org-sbe data)::$6='(org-sbe items)::$7='(org-sbe greet \":results verbatim\" (who $$1))::$8='(org-sbe \"\")::$9='(org-sbe two (a $1 $1) (b $$1))\n",
7878 blocks + "| n | sum |\n|---+-----|\n| 2 | |\n| 5 | |\n#+TBLFM: $2='(+ 1 (string-to-number (org-sbe square (n $1))))\n",
79 // `:lexical t` and `yes` are lexical; a name under a COMMENT heading, or on a keyword
80 // that names nothing, is skipped.
81 "#+NAME: lext\n#+begin_src emacs-lisp :lexical t\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n"
82 + "#+NAME: lexy\n#+begin_src emacs-lisp :lexical yes\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n"
83 + "#+NAME: dyn\n#+begin_src emacs-lisp :lexical no\n(let ((f (let ((y 2)) (lambda () y)))) (let ((y 3)) (funcall f)))\n#+end_src\n\n"
84 + "#+NAME: orph\n\n#+NAME: orph\n#+begin_src emacs-lisp\n\"real\"\n#+end_src\n\n"
85 + "| t | yes | no | cm | orph |\n|---+-----+----+----+------|\n| | | | | |\n"
86 + "#+TBLFM: $1='(org-sbe lext)::$2='(org-sbe lexy)::$3='(org-sbe dyn)::$4='(org-sbe cm)::$5='(org-sbe orph)\n\n"
87 + "* COMMENT Old\n#+NAME: cm\n| old |\n\n* New\n#+NAME: cm\n#+begin_src emacs-lisp\n\"new\"\n#+end_src\n",
7988 ]
8089
8190 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -95,6 +104,41 @@ struct TableSbeTests {
95104 }
96105 }
97106
107 /// The reason a table with `org-sbe` in `formula` goes to Emacs; nil when it doesn't.
108 static func reason(_ head: String, _ formula: String) -> String? {
109 let text = head + "| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2=" + formula + "\n"
110 let caret = (text as NSString).range(of: "#+TBLFM").location + 3
111 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
112 guard case .external(.emacsTable(_, _, _, let reason, _, _, _)) = TableRecalculate(all: true).run(in: context) else { return nil }
113 return reason
114 }
115
116 /// Values Emacs 31 prints as interpreted-function objects, `:lexical` values Emacs reads as
117 /// Lisp, and a name whose first use is skipped and that doesn't name a src block go to Emacs.
118 @Test func refusesWhatPrintsOrReadsDifferently() {
119 let lambda = "#+NAME: lam\n#+begin_src emacs-lisp\n(lambda () 1)\n#+end_src\n\n"
120 let quoted = "#+NAME: lam\n#+begin_src emacs-lisp :lexical yes\n(list 1 '(lambda () 1))\n#+end_src\n\n"
121 let lexical = "#+NAME: lam\n#+begin_src emacs-lisp :lexical (identity t)\n1\n#+end_src\n\n"
122 let twice = "* COMMENT Old\n#+NAME: lam\n| a |\n\n* New\n#+NAME: lam\n| b |\n\n"
123 #expect(Self.reason(lambda, "'(org-sbe lam)") == "Lisp org-sbe with a function value")
124 #expect(Self.reason(quoted, "'(org-sbe lam)") == "Lisp org-sbe with a function value")
125 #expect(Self.reason(lexical, "'(org-sbe lam)") == "Lisp org-sbe with this :lexical")
126 #expect(Self.reason(twice, "'(org-sbe lam)") == "Lisp org-sbe with a name used more than once")
127 #expect(Self.reason("#+NAME: lam\n| a |\n\n", "'(org-sbe lam)") == nil)
128 }
129
130 @TaskLocal static var locked = false
131
132 /// Without the app's leave to run blocks, `org-sbe` goes to the app with `lockedReason`.
133 @Test func lockedWithoutBabel() {
134 TableBlocks.allowed = { !TableSbeTests.locked }
135 let square = "#+NAME: f\n#+begin_src emacs-lisp :var n=2\n(* n n)\n#+end_src\n\n"
136 Self.$locked.withValue(true) {
137 #expect(Self.reason(square, "'(org-sbe f (n $1))") == TableBlocks.lockedReason)
138 }
139 #expect(Self.reason(square, "'(org-sbe f (n $1))") == nil)
140 }
141
98142 /// Other languages, and references only Emacs follows, go to Emacs.
99143 @Test func otherLanguagesNeedEmacs() {
100144 let python = "#+NAME: f\n#+begin_src python :var n=2\nreturn n\n#+end_src\n\n"
docs/manual/guide/10-tables.org +13 −7
@@ -589,14 +589,20 @@ writes =#ERROR= in the field, as does a Calc error.
589589
590590As in Org, a field's text is read as a value, so =abc= names another block or table;
591591write =$$1= instead of =$1= to pass the text as a string. A string before the variables
592holds header arguments, and the name may also be a named table or list in the file.
592holds header arguments, and the name may also be a named table or list in the file. As in
593Org, a name under a =COMMENT= heading is skipped. =org-sbe= needs Pro's source blocks
594feature.
595
593596Emacs Lisp blocks run in orgstar's interpreter, with dynamic binding unless the block
594has =:lexical yes=, and =js= blocks run in JavaScriptCore, everywhere and without asking,
595since neither can reach files or other programs. Blocks in other languages, blocks with
596=:cache yes=, =:file= results or column and row names, Lisp values with symbols in a
597variable with several values, references to an =ID= or =CUSTOM_ID=, and =js= values
598that are arrays need Emacs. When Emacs runs the table for =org-sbe=, it runs the
599blocks without asking again.
597has =:lexical yes= or =:lexical t=, and =js= blocks run in JavaScriptCore, everywhere and
598without asking, since neither can reach files or other programs. A =js= block that runs
599longer than five seconds is stopped, and the table needs Emacs. Blocks in other languages, blocks with =:cache yes=,
600=:file= results or column and row names, other =:lexical= values, values that hold a
601function, Lisp values with symbols in a variable with several values, a name given to
602more than one element when the first isn't a src block, references to an =ID= or
603=CUSTOM_ID=, and =js= values that are arrays need Emacs. When Emacs runs a table in a file
604that uses =org-sbe=, it runs the blocks without asking again, so orgstar asks
605=This table's formulas run Lisp and source blocks. Run them? (yes, no)= each time.
600606
601607* Entering formulas
602608