Commit 95111c0832

95111c0832aafcab0ec8ef3eeb3c138d3ae6d79e

parent: bd76469f57

Verified · cmc

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

Make dynamic lambdas function values and match org-sbe names by case

Layout: unified · split

Sources/OrgCore/Compute/BabelExpand.swift +2 −2
@@ -41,7 +41,7 @@ extension Babel {
4141 guard let raw = params.single[key] else { return nil }
4242 var value = params.evaluated[key]
4343 if value == nil, params.lisp.contains(key) {
44 guard let form = try? LispReader.readFirst(raw).sexp, let result = try? Elisp().eval(form) else {
44 guard let form = try? LispReader.readFirst(raw).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else {
4545 throw Failure.message("\(key) \(raw) is Lisp that only Emacs can evaluate.")
4646 }
4747 value = result
@@ -61,7 +61,7 @@ extension Babel {
6161 guard case .string(let s) = read(value) else { return .string(value) }
6262 return .string(s)
6363 }
64 guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else {
64 guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else {
6565 throw Failure.message("The property value \(value) is Lisp that only Emacs can evaluate.")
6666 }
6767 if let s = result.string { return .string(s) }
Sources/OrgCore/Compute/BabelHeaders.swift +1 −1
@@ -21,7 +21,7 @@ extension Babel {
2121 mutating func evaluateLisp(file: String?) {
2222 for key in lisp {
2323 guard let form = try? LispReader.readFirst(single[key] ?? "").sexp,
24 let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form) else { continue }
24 let value = try? (file.map { Tangle.fileLisp(path: $0) } ?? Elisp()).eval(form), !Elisp.containsClosure(value) else { continue }
2525 let printed = Elisp.printed(value)
2626 if let s = value.string {
2727 single[key] = s
Sources/OrgCore/Compute/BabelVars.swift +1 −1
@@ -88,7 +88,7 @@ extension Babel {
8888 /// table.
8989 static func lispValue(_ value: String) throws -> VarValue {
9090 let refusal = Failure.message(":var value \(value) is Lisp that only Emacs can evaluate.")
91 guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form) else { throw refusal }
91 guard let form = try? LispReader.readFirst(value).sexp, let result = try? Elisp().eval(form), !Elisp.containsClosure(result) else { throw refusal }
9292 func cell(_ v: Sexp) throws -> Cell {
9393 if let s = v.string { return .text(s) }
9494 if let n = number(Elisp.printed(v)), Elisp.printed(v) == n { return .number(n) }
Sources/OrgCore/Compute/TableFormulas.swift +2
@@ -661,6 +661,8 @@ extension EmacsBuffer {
661661 } catch {
662662 return "#ERROR"
663663 }
664 // Emacs prints functions as `#[ARGS BODY ENV]`.
665 if Elisp.containsClosure(value) { throw Calc.Unsupported("Lisp formula with a function value") }
664666 var result = Elisp.printed(value)
665667 if let duration { result = try Self.secondsToString(Elisp.stringToNumber(result), duration) }
666668 return result
Sources/OrgCore/Compute/TableSbe.swift +9 −6
@@ -90,9 +90,11 @@ extension Babel {
9090 let model = DocumentModel(tree: OrgParser.parse(text))
9191 let options = Options()
9292 // The first `#+NAME:` line with the name outside COMMENTed headings that names an
93 // element: a src block's, or another element's.
94 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]*$"
95 let matches = try NSRegularExpression(pattern: pattern).matches(in: text, range: NSRange(location: 0, length: ns.length)).map(\.range)
93 // element: a src block's, or another element's. The keyword's case doesn't matter; the
94 // name's does.
95 let pattern = "(?im)^[ \\t]*#\\+name:[ \\t]*(" + NSRegularExpression.escapedPattern(for: name) + ")[ \\t]*$"
96 let found = try NSRegularExpression(pattern: pattern).matches(in: text, range: NSRange(location: 0, length: ns.length))
97 let matches = found.filter { ns.substring(with: $0.range(at: 1)) == name }.map(\.range)
9698 let headingStarts = model.headings.map(\.headingRange.lowerBound)
9799 func commented(_ location: Int) -> Bool {
98100 guard let h = headingStarts.lastIndex(where: { $0 <= location }) else { return false }
@@ -119,8 +121,9 @@ extension Babel {
119121 return between.split(separator: "\n").allSatisfy { $0.trimmingCharacters(in: .whitespaces).hasPrefix("#+") }
120122 }
121123 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 // `resolve` reads the first element with the name in any case, and runs a src block
125 // before it.
126 guard named == found.first?.range, !model.srcBlocks.contains(where: { $0.name == name }) else {
124127 throw Elisp.Unsupported(what: "org-sbe with a name used more than once")
125128 }
126129 do {
@@ -193,7 +196,7 @@ extension Babel {
193196 lisp.syntax = .emacsLisp
194197 lisp.standardTime()
195198 result = try lisp.eval(try LispReader.readFirst(form).sexp)
196 if Elisp.containsFunction(result) { throw Elisp.Unsupported(what: "org-sbe with a function value") }
199 if Elisp.containsClosure(result) { throw Elisp.Unsupported(what: "org-sbe with a function value") }
197200 if scalar {
198201 result = .string(params.contains("scalar") || params.contains("verbatim") ? Elisp.printed(result, escape: true) : try Elisp.format([.string("%s"), result]))
199202 }
Sources/OrgCore/Config/Elisp.swift +15 −16
@@ -49,7 +49,7 @@ public final class Elisp {
4949 /// Variables bound dynamically when `lexical` is set.
5050 var specials: Set<String> = []
5151 /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding:
52 /// every variable is bound dynamically and lambdas aren't closures.
52 /// every variable is bound dynamically and lambdas capture nothing.
5353 private var dynamicOnly = false
5454 /// The functions `defun` defined, which may take closures.
5555 var defined: Set<String> = []
@@ -148,11 +148,19 @@ public final class Elisp {
148148 scopes[0].vars[name] = v
149149 }
150150
151 /// The ids in `closures` of functions made under dynamic binding, which capture nothing.
152 var dynamicClosures: Set<Int> = []
153
151154 /// A lambda as `function` makes it: a closure over the local frames under lexical
152 /// binding, else the list itself.
155 /// binding, else one that captures nothing. Emacs 31 makes both function objects, not lists.
153156 func closure(_ lambda: Sexp) -> Sexp {
154 guard lexical, !dynamicOnly, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda }
155 closures.append(Array(scopes.dropFirst()))
157 guard case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda }
158 if lexical, !dynamicOnly {
159 closures.append(Array(scopes.dropFirst()))
160 } else {
161 closures.append([])
162 dynamicClosures.insert(closures.count - 1)
163 }
156164 return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst())
157165 }
158166
@@ -166,7 +174,7 @@ public final class Elisp {
166174 static let closureArguments: [String: Int] = [
167175 "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0,
168176 "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0,
169 "replace-regexp-in-string": 1, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0,
177 "replace-regexp-in-string": 1, "org-lookup-first": 3, "org-lookup-last": 3, "org-lookup-all": 3, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0,
170178 ]
171179 /// Builtins that compare or print what lists hold.
172180 static let closureInspectors: Set<String> = [
@@ -194,17 +202,6 @@ public final class Elisp {
194202 }
195203 }
196204
197 /// Whether `v` contains a closure or a `(lambda ...)` list, which Emacs 31 prints as an
198 /// interpreted-function object.
199 static func containsFunction(_ v: Sexp) -> Bool {
200 switch v {
201 case .list(let items): isClosure(v) || items.first == .symbol("lambda") || items.contains(where: containsFunction)
202 case .dotted(let items, let last): items.first == .symbol("lambda") || items.contains(where: containsFunction) || containsFunction(last)
203 case .vector(let items): items.contains(where: containsFunction)
204 default: false
205 }
206 }
207
208205 /// The variable named by the first argument of the function being called from `eval`, read
209206 /// once.
210207 func takeInPlaceVariable() -> String? {
@@ -338,6 +335,7 @@ public final class Elisp {
338335 case .string(let s): return escape ? "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" : s
339336 case .float(let d): return floatText(d)
340337 case .character(let c): return String(c)
338 case .list(let items) where items.isEmpty: return "nil"
341339 case .list(let items): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + ")"
342340 case .dotted(let items, let last): return "(" + items.map { printed($0, escape: escape) }.joined(separator: " ") + " . " + printed(last, escape: escape) + ")"
343341 case .vector(let items): return "[" + items.map { printed($0, escape: escape) }.joined(separator: " ") + "]"
@@ -583,6 +581,7 @@ public final class Elisp {
583581 case .symbol(let name): return try callNamed(name, args)
584582 case .list(let items) where Self.isClosure(function):
585583 guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") }
584 if dynamicClosures.contains(items[1].integer!) { return try call(.list([.symbol("lambda")] + items.dropFirst(2)), args) }
586585 let saved = dynamicOnly
587586 dynamicOnly = false
588587 defer { dynamicOnly = saved }
Sources/OrgCore/Links/Links.swift +1 −1
@@ -281,7 +281,7 @@ extension Links {
281281 EmacsBuffer.defineLookups(lisp)
282282 do {
283283 let value = try lisp.eval(try LispReader.readFirst(form).sexp)
284 if Elisp.containsFunction(value) { return "This link uses Emacs Lisp that runs only in Emacs." }
284 if Elisp.containsClosure(value) { return "This link uses Emacs Lisp that runs only in Emacs." }
285285 return "\(form) => \(try Elisp.format([.string("%s"), value]))"
286286 } catch is Elisp.Unsupported {
287287 return "This link uses Emacs Lisp that runs only in Emacs."
Tests/OrgCoreTests/ElispLinkTests.swift +4 −2
@@ -7,7 +7,7 @@ struct ElispLinkTests {
77 static let forms = [
88 "(+ 1 2)", "(list 1 \"a\" 'b 2.5)", "(concat \"a\" \"b\")", "(message \"hi\")", "(let ((x 2)) (* x x))",
99 "(mapcar (lambda (n) (* n 10)) '(1 2 3))", "nil", "(car 1)", "(/ 1 0)", "(error \"Nope %d\" 3)", "(format \"%S\" \"q\")",
10 "(org-lookup-first 2 '(1 2 3) '(a b c))", "(org-lookup-all 1 '(1 2 1) '(x y z))",
10 "(org-lookup-first 2 '(1 2 3) '(a b c))", "(org-lookup-all 1 '(1 2 1) '(x y z))", "(format \"%S\" '(lambda () 1))",
1111 ]
1212
1313 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -26,6 +26,8 @@ struct ElispLinkTests {
2626 @Test func refusesWhatOnlyEmacsHas() {
2727 #expect(Links.evaluateElisp("(org-agenda nil \"a\")") == "This link uses Emacs Lisp that runs only in Emacs.")
2828 // Emacs 31 prints a function made under dynamic binding as `#[nil (1) nil]`.
29 #expect(Links.evaluateElisp("(let ((f (lambda () 1))) f)") == "This link uses Emacs Lisp that runs only in Emacs.")
29 for form in ["(let ((f (lambda () 1))) f)", "(prin1-to-string (lambda () 1))", "(format \"%S\" (lambda () 1))", "(car (lambda () 1))"] {
30 #expect(Links.evaluateElisp(form) == "This link uses Emacs Lisp that runs only in Emacs.", "\(form)")
31 }
3032 }
3133}
Tests/OrgCoreTests/TableSbeTests.swift +13 −3
@@ -85,6 +85,12 @@ struct TableSbeTests {
8585 + "| t | yes | no | cm | orph |\n|---+-----+----+----+------|\n| | | | | |\n"
8686 + "#+TBLFM: $1='(org-sbe lext)::$2='(org-sbe lexy)::$3='(org-sbe dyn)::$4='(org-sbe cm)::$5='(org-sbe orph)\n\n"
8787 + "* COMMENT Old\n#+NAME: cm\n| old |\n\n* New\n#+NAME: cm\n#+begin_src emacs-lisp\n\"new\"\n#+end_src\n",
88 // A quoted lambda stays a list, a name in another case names nothing, and a lambda
89 // can be a lookup's predicate.
90 "#+NAME: quo\n#+begin_src emacs-lisp :lexical yes\n(list 1 '(lambda () 1))\n#+end_src\n\n"
91 + "| q | up | lk |\n|---+----+----|\n| | | |\n"
92 + "#+TBLFM: $1='(org-sbe quo)::$2='(org-sbe x)::$3='(org-lookup-first 2 '(1 2 3) '(a b c) (lambda (a b) (= a b)))\n\n"
93 + "#+NAME: X\n| up |\n",
8894 ]
8995
9096 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -113,15 +119,19 @@ struct TableSbeTests {
113119 return reason
114120 }
115121
116 /// Values Emacs 31 prints as interpreted-function objects, `:lexical` values Emacs reads as
122 /// Values Emacs 31 prints or reads as interpreted-function objects, `:lexical` values Emacs reads as
117123 /// Lisp, and a name whose first use is skipped and that doesn't name a src block go to Emacs.
118124 @Test func refusesWhatPrintsOrReadsDifferently() {
119125 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"
126 let printed = "#+NAME: lam\n#+begin_src emacs-lisp\n(format \"%S\" (lambda () 1))\n#+end_src\n\n"
127 let car = "#+NAME: lam\n#+begin_src emacs-lisp\n(car (lambda () 1))\n#+end_src\n\n"
121128 let lexical = "#+NAME: lam\n#+begin_src emacs-lisp :lexical (identity t)\n1\n#+end_src\n\n"
122129 let twice = "* COMMENT Old\n#+NAME: lam\n| a |\n\n* New\n#+NAME: lam\n| b |\n\n"
123130 #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")
131 #expect(Self.reason(printed, "'(org-sbe lam)") == "Lisp format on a closure")
132 #expect(Self.reason(car, "'(org-sbe lam)") == "Lisp car on a closure")
133 #expect(Self.reason("", "'(format \"%S\" (lambda () 1))") == "Lisp format on a closure")
134 #expect(Self.reason("", "'(lambda () 1)") == "Lisp formula with a function value")
125135 #expect(Self.reason(lexical, "'(org-sbe lam)") == "Lisp org-sbe with this :lexical")
126136 #expect(Self.reason(twice, "'(org-sbe lam)") == "Lisp org-sbe with a name used more than once")
127137 #expect(Self.reason("#+NAME: lam\n| a |\n\n", "'(org-sbe lam)") == nil)
docs/manual/guide/10-tables.org +6 −3
@@ -570,7 +570,10 @@ when the error isn't one of =wrong-type-argument=, =args-out-of-range=, =arith-e
570570widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as
571571=YYYY-MM-DD=, with an optional =HH:MM= or =HH:MM:SS=.
572572
573Any other function, or a macro not listed, needs Emacs. An error inside a Lisp formula
573Any other function, or a macro not listed, needs Emacs. As in Emacs 31, =lambda= and
574=function= make function objects rather than lists, so a formula whose value is one, or
575that prints one or takes it apart as a list, needs Emacs; calling one, or passing it to a
576function that calls it, doesn't. An error inside a Lisp formula
574577writes =#ERROR= in the field, as does a Calc error.
575578
576579=org-sbe= writes the value of a named src block, run with the variables given:
@@ -590,7 +593,7 @@ writes =#ERROR= in the field, as does a Calc error.
590593As in Org, a field's text is read as a value, so =abc= names another block or table;
591594write =$$1= instead of =$1= to pass the text as a string. A string before the variables
592595holds 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
596Org, a name under a =COMMENT= heading is skipped, and the name's case must match. =org-sbe= needs Pro's source blocks
594597feature.
595598
596599Emacs Lisp blocks run in orgstar's interpreter, with dynamic binding unless the block
@@ -599,7 +602,7 @@ without asking, since neither can reach files or other programs. A =js= block th
599602longer than five seconds is stopped, and the table needs Emacs. Blocks in other languages, blocks with =:cache yes=,
600603=:file= results or column and row names, other =:lexical= values, values that hold a
601604function, 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
605more than one element, in any case, when the first isn't a src block, references to an =ID= or
603606=CUSTOM_ID=, and =js= values that are arrays need Emacs. When Emacs runs a table in a file
604607that uses =org-sbe=, it runs the blocks without asking again, so orgstar asks
605608=This table's formulas run Lisp and source blocks. Run them? (yes, no)= each time.