Commit 47dd021371

47dd021371c15aee70490c5421c822d081cf0f6e

parent: db6552840c

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 22:07 UTC

Match Emacs in native Lisp: lexical blocks, split-string, shared lists, old dates

Babel runs natively with lexical binding and the Emacs Lisp syntax table, as
emacs -Q --batch -l does. split-string follows Emacs 31 on empty separator
matches. replace-match keeps \?. sort, nreverse and delete-dups refuse lists
another value may share. Times use the proleptic Gregorian calendar.
string-pad rejects a negative length.

Layout: unified · split

Sources/OrgApp/TableReason.swift +4
@@ -71,6 +71,10 @@ public enum TableReason {
7171 let name = String(what.dropLast(" on a place".count))
7272 return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable")
7373 }
74 if what.hasSuffix(" on a list another value shares") {
75 let name = String(what.dropLast(" on a list another value shares".count))
76 return String(localized: "\(name) on a list another value shares", comment: "Why a table needs Emacs: a Lisp function that changes a shared list")
77 }
7478 if what.hasSuffix(" in a buffer") {
7579 let name = String(what.dropLast(" in a buffer".count))
7680 return String(localized: "\(name) in a buffer", comment: comment)
Sources/OrgCore/Compute/BabelLanguages.swift +5
@@ -92,11 +92,16 @@ extension Babel {
9292 /// doesn't have.
9393 public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? {
9494 guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil }
95 // As `emacs -Q --batch -l` runs `emacsScript`: lexical binding, in `*scratch*`.
9596 let lisp = Elisp()
97 lisp.lexical = true
98 lisp.syntax = .emacsLisp
9699 lisp.standardTime()
97100 let result: Sexp
98101 do {
99102 result = try lisp.eval(sexp)
103 // Emacs prints closures as `#[ARGS BODY ENV]`.
104 if Elisp.containsClosure(result) { return nil }
100105 } catch is Elisp.Unsupported {
101106 return nil
102107 } catch {
Sources/OrgCore/Config/Elisp.swift +210 −60
@@ -1,8 +1,8 @@
11import Foundation
22
33/// A small Emacs Lisp evaluator over `Sexp` values: the special forms and functions diary
4/// sexps and table formulas use, with dynamic binding. A function or form it doesn't have
5/// throws `Unsupported`; errors Emacs would signal throw `Signal`.
4/// sexps and table formulas use, with dynamic binding unless `lexical` is set. A function or
5/// form it doesn't have throws `Unsupported`; errors Emacs would signal throw `Signal`.
66public final class Elisp {
77 public struct Unsupported: Error, Equatable, CustomStringConvertible {
88 public let what: String
@@ -16,7 +16,33 @@ public final class Elisp {
1616
1717 public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp
1818
19 var scopes: [[String: Sexp]] = [[:]]
19 /// A set of bindings, shared by the closures created while it is in scope.
20 final class Frame {
21 var vars: [String: Sexp]
22 init(_ vars: [String: Sexp] = [:]) { self.vars = vars }
23 }
24
25 /// The global frame, then the visible local ones, innermost last.
26 var scopes: [Frame] = [Frame()]
27 /// `lexical-binding`: lambdas close over the local frames, and only special variables
28 /// (the host's and `defvar`'s) are bound dynamically.
29 public var lexical = false
30 /// Variables bound dynamically when `lexical` is set.
31 var specials: Set<String> = []
32 /// Each closure's captured frames, by the id in its `(closure ID ARGS . BODY)` value.
33 var closures: [[Frame]] = []
34 /// The scopes of the callers of running closures, and the global values that dynamic
35 /// bindings of special variables hide.
36 private var hiddenScopes: [[Frame]] = []
37 private var hiddenValues: [Sexp] = []
38 /// Values held while a form evaluates: each call's evaluated arguments, innermost last.
39 private var pending: [[Sexp]] = []
40 /// The variable an in-place function's first argument named, for that function to read.
41 private var inPlaceVariable: String?
42 /// The syntax table regexps and case conversion use.
43 var syntax = ElispSyntax.org {
44 didSet { regexes = [:] }
45 }
2046 private var functions: [String: Builtin] = [:]
2147 var steps = 0
2248 static let stepLimit = 1_000_000
@@ -45,27 +71,114 @@ public final class Elisp {
4571 /// Defines or replaces a function.
4672 public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function }
4773
48 /// Sets a global variable.
49 public func set(_ name: String, _ value: Sexp) { scopes[0][name] = value }
74 /// Sets a global variable, which is special.
75 public func set(_ name: String, _ value: Sexp) {
76 scopes[0].vars[name] = value
77 specials.insert(name)
78 }
5079
5180 public func value(_ name: String) throws -> Sexp {
52 for scope in scopes.reversed() { if let v = scope[name] { return v } }
81 for scope in scopes.reversed() { if let v = scope.vars[name] { return v } }
5382 throw Signal(message: "Symbol’s value as variable is void: \(name)")
5483 }
5584
56 /// Evaluates `body` with `bindings` added.
85 /// Evaluates `body` with `bindings` added: in a new frame, or for special variables under
86 /// lexical binding, as their global values until `body` returns.
5787 public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T {
58 scopes.append(bindings)
59 defer { scopes.removeLast() }
88 try binding(Frame(bindings), body)
89 }
90
91 func binding<T>(_ frame: Frame, _ body: () throws -> T) rethrows -> T {
92 let dynamic = lexical ? frame.vars.keys.filter(specials.contains) : []
93 var saved: [(String, Sexp?)] = []
94 for name in dynamic {
95 saved.append((name, scopes[0].vars[name]))
96 if let old = scopes[0].vars[name] { hiddenValues.append(old) }
97 scopes[0].vars[name] = frame.vars.removeValue(forKey: name)
98 }
99 scopes.append(frame)
100 defer {
101 scopes.removeLast()
102 for (name, old) in saved.reversed() {
103 scopes[0].vars[name] = old
104 if old != nil { hiddenValues.removeLast() }
105 }
106 }
60107 return try body()
61108 }
62109
63110 func assign(_ name: String, _ v: Sexp) {
64 for i in scopes.indices.reversed() where scopes[i][name] != nil {
65 scopes[i][name] = v
111 for scope in scopes.reversed() where scope.vars[name] != nil {
112 scope.vars[name] = v
113 return
114 }
115 scopes[0].vars[name] = v
116 }
117
118 /// A lambda as `function` makes it: a closure over the local frames under lexical
119 /// binding, else the list itself.
120 func closure(_ lambda: Sexp) -> Sexp {
121 guard lexical, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda }
122 closures.append(Array(scopes.dropFirst()))
123 return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst())
124 }
125
126 static func isClosure(_ v: Sexp) -> Bool {
127 if case .list(let items) = v, items.count >= 3, items[0] == .symbol("closure"), items[1].integer != nil { return true }
128 return false
129 }
130
131 /// Whether `v` contains a closure, which Emacs prints in a form this evaluator doesn't.
132 static func containsClosure(_ v: Sexp) -> Bool {
133 switch v {
134 case .list(let items): isClosure(v) || items.contains(where: containsClosure)
135 case .dotted(let items, let last): items.contains(where: containsClosure) || containsClosure(last)
136 case .vector(let items): items.contains(where: containsClosure)
137 default: false
138 }
139 }
140
141 /// The variable named by the first argument of the function being called from `eval`, read
142 /// once.
143 func takeInPlaceVariable() -> String? {
144 defer { inPlaceVariable = nil }
145 return inPlaceVariable
146 }
147
148 /// Refuses an in-place change to `v` when another binding, list or pending argument may
149 /// share its cells, which Emacs would change too: any value holding a list that ends like
150 /// `v`, or an equal vector or string. `variable`'s innermost binding is the one `eval`
151 /// updates after the call.
152 func refuseShared(_ v: Sexp, variable: String?, _ name: String) throws {
153 let matches: (Sexp) -> Bool
154 switch v {
155 case .list(let items):
156 guard let last = items.last.map(Self.normalized) else { return }
157 matches = { if case .list(let xs) = $0, let l = xs.last { Self.normalized(l) == last } else { false } }
158 case .dotted(let items, let tail):
159 let last = Self.normalized(items.last!)
160 matches = { if case .dotted(let xs, let t) = $0 { t == tail && Self.normalized(xs.last!) == last } else { false } }
161 case .vector, .string:
162 matches = { $0 == v }
163 default:
66164 return
67165 }
68 scopes[0][name] = v
166 func contains(_ x: Sexp) -> Bool {
167 if matches(x) { return true }
168 switch x {
169 case .list(let items), .vector(let items): return items.contains(where: contains)
170 case .dotted(let items, let last): return items.contains(where: contains) || contains(last)
171 default: return false
172 }
173 }
174 let owner = variable.flatMap { name in scopes.last { $0.vars[name] != nil } }
175 var seen: Set<ObjectIdentifier> = []
176 for frame in (hiddenScopes + [scopes] + closures).joined() where seen.insert(ObjectIdentifier(frame)).inserted {
177 for (key, value) in frame.vars where !(frame === owner && key == variable) && contains(value) {
178 throw Unsupported(what: "\(name) on a list another value shares")
179 }
180 }
181 if (hiddenValues + pending.dropLast().joined()).contains(where: contains) { throw Unsupported(what: "\(name) on a list another value shares") }
69182 }
70183
71184 // MARK: - Values
@@ -202,7 +315,7 @@ public final class Elisp {
202315 guard let head = items.first else { return .nil }
203316 guard case .symbol(let name) = head else {
204317 if case .list(let lambda) = head, lambda.first == .symbol("lambda") {
205 return try call(head, try items.dropFirst().map(eval))
318 return try call(closure(head), try evaluated(items.dropFirst()))
206319 }
207320 throw Signal(message: "Invalid function: \(head.description)")
208321 }
@@ -211,18 +324,30 @@ public final class Elisp {
211324 // The function first, so an unknown one, or a macro this evaluator lacks, is
212325 // unsupported rather than an error from its arguments.
213326 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
214 let values = try args.map(eval)
327 pending.append([])
328 defer { pending.removeLast() }
329 for arg in args { pending[pending.count - 1].append(try eval(arg)) }
330 let values = pending[pending.count - 1]
331 var variable: String?
332 if case .symbol(let s)? = args.first, s != "nil", s != "t", !s.hasPrefix(":") { variable = s }
333 inPlaceVariable = variable
215334 let result = try function(self, values)
216 if case .symbol(let variable)? = args.first, variable != "nil", variable != "t", !variable.hasPrefix(":"),
217 let after = Self.afterInPlace(name, values, result) {
218 assign(variable, after)
219 }
335 inPlaceVariable = nil
336 if let variable, let after = Self.afterInPlace(name, values, result) { assign(variable, after) }
220337 return result
221338 case .dotted: throw Signal(message: "Invalid function")
222339 default: return form
223340 }
224341 }
225342
343 /// `forms`' values, held as pending while the later ones evaluate.
344 func evaluated(_ forms: some Collection<Sexp>) throws -> [Sexp] {
345 pending.append([])
346 defer { pending.removeLast() }
347 for form in forms { pending[pending.count - 1].append(try eval(form)) }
348 return pending[pending.count - 1]
349 }
350
226351 func progn(_ body: some Collection<Sexp>) throws -> Sexp {
227352 var result = Sexp.nil
228353 for form in body { result = try eval(form) }
@@ -235,16 +360,17 @@ public final class Elisp {
235360 case "quote":
236361 return args.first ?? .nil
237362 case "function":
238 return args.first ?? .nil
363 return closure(args.first ?? .nil)
239364 case "lambda":
240 return .list([.symbol("lambda")] + args)
365 return closure(.list([.symbol("lambda")] + args))
241366 case "progn":
242367 return try progn(args)
243368 case "prog1":
244369 guard let first = args.first else { return .nil }
245 let value = try eval(first)
370 pending.append([try eval(first)])
371 defer { pending.removeLast() }
246372 _ = try progn(args.dropFirst())
247 return value
373 return pending[pending.count - 1][0]
248374 case "if":
249375 guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") }
250376 return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1])
@@ -274,22 +400,29 @@ public final class Elisp {
274400 return .nil
275401 case "let", "let*":
276402 guard let first = args.first else { return .nil }
277 var bindings: [String: Sexp] = [:]
278 scopes.append([:])
279 defer { scopes.removeLast() }
403 var specs: [(String, Sexp?)] = []
280404 for binding in try Self.elements(first) {
281 let (variable, value): (String, Sexp)
282405 if case .symbol(let s) = binding {
283 (variable, value) = (s, .nil)
406 specs.append((s, nil))
284407 } else {
285408 let parts = try Self.elements(binding)
286409 guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") }
287 (variable, value) = (s, parts.count > 1 ? try eval(parts[1]) : .nil)
410 specs.append((s, parts.count > 1 ? parts[1] : nil))
288411 }
289 if name == "let*" { scopes[scopes.count - 1][variable] = value } else { bindings[variable] = value }
290412 }
291 if name == "let" { scopes[scopes.count - 1] = bindings }
292 return try progn(args.dropFirst())
413 if name == "let" {
414 let values = try evaluated(specs.map { $0.1 ?? .nil })
415 var bindings: [String: Sexp] = [:]
416 for ((variable, _), value) in zip(specs, values) { bindings[variable] = value }
417 return try binding(bindings) { try progn(args.dropFirst()) }
418 }
419 // `let*` nests a binding per variable, so a closure sees the ones before it.
420 func bind(_ rest: ArraySlice<(String, Sexp?)>) throws -> Sexp {
421 guard let (variable, form) = rest.first else { return try progn(args.dropFirst()) }
422 let value = try form.map(eval) ?? .nil
423 return try binding([variable: value]) { try bind(rest.dropFirst()) }
424 }
425 return try bind(specs[...])
293426 case "setq":
294427 var value = Sexp.nil
295428 var i = 0
@@ -320,17 +453,16 @@ public final class Elisp {
320453 let source = try eval(spec[1])
321454 let items = name == "dolist" ? try Self.elements(source) : []
322455 let count = name == "dolist" ? items.count : max(0, try Self.int(source))
323 scopes.append([:])
324 defer { scopes.removeLast() }
456 pending.append([source])
457 defer { pending.removeLast() }
458 // A new binding each time round, as closures over the variable see it.
325459 for i in 0..<count {
326460 steps += 1
327461 if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") }
328 scopes[scopes.count - 1][variable] = name == "dolist" ? items[i] : .integer(i)
329 _ = try progn(args.dropFirst())
462 _ = try binding([variable: name == "dolist" ? items[i] : .integer(i)]) { try progn(args.dropFirst()) }
330463 }
331464 if spec.count > 2 {
332 scopes[scopes.count - 1][variable] = name == "dotimes" ? .integer(count) : .nil
333 return try eval(spec[2])
465 return try binding([variable: name == "dotimes" ? .integer(count) : .nil]) { try eval(spec[2]) }
334466 }
335467 return .nil
336468 case "with-output-to-string":
@@ -368,37 +500,55 @@ public final class Elisp {
368500 public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp {
369501 switch function {
370502 case .symbol(let name): return try callNamed(name, args)
503 case .list(let items) where Self.isClosure(function):
504 return try apply(parameters: items[2], body: items.dropFirst(3), args, scope: closures[items[1].integer!])
371505 case .list(let items) where items.first == .symbol("lambda") && items.count >= 2:
372 var bindings: [String: Sexp] = [:]
373 var mode = "required"
374 var i = 0
375 for parameter in try Self.elements(items[1]) {
376 guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") }
377 if p == "&optional" || p == "&rest" {
378 mode = p
379 continue
380 }
381 if mode == "&rest" {
382 bindings[p] = Self.list(Array(args.dropFirst(i)))
383 i = args.count
384 } else if i < args.count {
385 bindings[p] = args[i]
386 i += 1
387 } else if mode == "&optional" {
388 bindings[p] = .nil
389 } else {
390 throw Signal(message: "Wrong number of arguments")
391 }
392 }
393 if i < args.count { throw Signal(message: "Wrong number of arguments") }
394 return try binding(bindings) { try progn(items.dropFirst(2)) }
506 // Under lexical binding, a lambda list runs outside the caller's local frames.
507 return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: lexical ? [] : nil)
395508 default:
396509 throw Signal(message: "Invalid function: \(function.description)")
397510 }
398511 }
399512
513 /// Binds `parameters` to `args` and runs `body`, in `scope`'s frames instead of the
514 /// caller's when given.
515 private func apply(parameters: Sexp, body: ArraySlice<Sexp>, _ args: [Sexp], scope: [Frame]?) throws -> Sexp {
516 var bindings: [String: Sexp] = [:]
517 var mode = "required"
518 var i = 0
519 for parameter in try Self.elements(parameters) {
520 guard case .symbol(let p) = parameter else { throw Signal(message: "Bad lambda list") }
521 if p == "&optional" || p == "&rest" {
522 mode = p
523 continue
524 }
525 if mode == "&rest" {
526 bindings[p] = Self.list(Array(args.dropFirst(i)))
527 i = args.count
528 } else if i < args.count {
529 bindings[p] = args[i]
530 i += 1
531 } else if mode == "&optional" {
532 bindings[p] = .nil
533 } else {
534 throw Signal(message: "Wrong number of arguments")
535 }
536 }
537 if i < args.count { throw Signal(message: "Wrong number of arguments") }
538 guard let scope else { return try binding(bindings) { try progn(body) } }
539 let caller = scopes
540 hiddenScopes.append(caller)
541 scopes = [scopes[0]] + scope
542 defer {
543 scopes = caller
544 hiddenScopes.removeLast()
545 }
546 return try binding(bindings) { try progn(body) }
547 }
548
400549 func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp {
401550 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
551 inPlaceVariable = nil
402552 return try function(self, args)
403553 }
404554
Sources/OrgCore/Config/ElispForms.swift +8 −8
@@ -26,8 +26,8 @@ extension Elisp {
2626 var body = Array(args.dropFirst(2))
2727 if body.count > 1, case .string = body[0] { body.removeFirst() }
2828 while let head = body.first?.head, head == "declare" || head == "interactive" { body.removeFirst() }
29 let lambda = Sexp.list([.symbol("lambda"), args[1]] + body)
30 define(name) { lisp, values in try lisp.call(lambda, values) }
29 let function = closure(.list([.symbol("lambda"), args[1]] + body))
30 define(name) { lisp, values in try lisp.call(function, values) }
3131 return .symbol(name)
3232 }
3333
@@ -35,7 +35,8 @@ extension Elisp {
3535 func defineVariable(_ args: [Sexp], constant: Bool) throws -> Sexp {
3636 guard case .symbol(let name)? = args.first, args.count <= 3 else { throw Signal(message: "Malformed \(constant ? "defconst" : "defvar")") }
3737 if constant, args.count < 2 { throw Signal(message: "Wrong number of arguments: defconst, 1") }
38 if args.count > 1, constant || scopes[0][name] == nil { scopes[0][name] = try eval(args[1]) }
38 specials.insert(name)
39 if args.count > 1, constant || scopes[0].vars[name] == nil { scopes[0].vars[name] = try eval(args[1]) }
3940 return .symbol(name)
4041 }
4142
@@ -121,9 +122,8 @@ extension Elisp {
121122 case .list(let items) where items.count == 2 && items[0] == .symbol("\\`"):
122123 return try backquoted(items[1], value, &bindings)
123124 case .list(let items) where items.count == 2 && items[0] == .symbol("pred") && (items[1].symbol != nil || items[1].head == "lambda"):
124 let function = items[1]
125125 let soFar = bindings
126 return !Self.isNil(try binding(soFar) { try call(function, [value]) })
126 return !Self.isNil(try binding(soFar) { try call(closure(items[1]), [value]) })
127127 default:
128128 throw Unsupported(what: "pcase pattern \(pattern.description)")
129129 }
@@ -162,7 +162,7 @@ extension Elisp {
162162 // What each `in` clause has left.
163163 var lists: [Int: Sexp] = [:]
164164 var actions: [(kind: String, forms: [Sexp])] = []
165 scopes.append([:])
165 scopes.append(Frame())
166166 defer { scopes.removeLast() }
167167 var i = 0
168168 func next() throws -> Sexp {
@@ -178,10 +178,10 @@ extension Elisp {
178178 switch try next() {
179179 case .symbol("in"):
180180 lists[iterators.count] = try eval(try next())
181 scopes[scopes.count - 1][variable] = .nil
181 scopes[scopes.count - 1].vars[variable] = .nil
182182 iterators.append(.list(variable))
183183 case .symbol("from"):
184 scopes[scopes.count - 1][variable] = try eval(try next())
184 scopes[scopes.count - 1].vars[variable] = try eval(try next())
185185 var limit: Sexp?
186186 if i < args.count, args[i] == .symbol("to") {
187187 i += 1
Sources/OrgCore/Config/ElispLibrary.swift +17 −3
@@ -100,7 +100,9 @@ extension Elisp {
100100 lisp.define("string-pad") { _, args in
101101 try arity(args, 2...4, "string-pad")
102102 let s = try string(args[0])
103 let pad = try int(args[1]) - s.unicodeScalars.count
103 let length = try int(args[1])
104 guard length >= 0 else { throw Signal(message: "Wrong type argument: natnump, \(length)") }
105 let pad = length - s.unicodeScalars.count
104106 guard pad > 0 else { return .string(s) }
105107 guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") }
106108 let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad)
@@ -157,6 +159,12 @@ extension Elisp {
157159 }
158160 }
159161
162 /// Refuses `name` on a first argument that another value may share, when it changes it in
163 /// place.
164 static func refuseShared(_ lisp: Elisp, _ name: String, _ args: [Sexp], variable: String?) throws {
165 if afterInPlace(name, args, .nil) != nil { try lisp.refuseShared(args[0], variable: variable, name) }
166 }
167
160168 /// Keyword arguments `args` after the first `count`, of which only `allowed` are known.
161169 static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] {
162170 let rest = Array(args.dropFirst(count))
@@ -242,12 +250,16 @@ extension Elisp {
242250 guard n > 0 else { return args[0] }
243251 return list(Array(try elements(args[0]).dropLast(n)))
244252 }
245 lisp.define("delete-dups") { _, args in
253 lisp.define("delete-dups") { lisp, args in
254 let variable = lisp.takeInPlaceVariable()
246255 try arity(args, 1...1, "delete-dups")
256 try refuseShared(lisp, "delete-dups", args, variable: variable)
247257 return list(uniqueEqual(try elements(args[0])))
248258 }
249 lisp.define("nreverse") { _, args in
259 lisp.define("nreverse") { lisp, args in
260 let variable = lisp.takeInPlaceVariable()
250261 try arity(args, 1...1, "nreverse")
262 try refuseShared(lisp, "nreverse", args, variable: variable)
251263 switch args[0] {
252264 case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed())))
253265 case .vector(let items): return .vector(items.reversed())
@@ -255,6 +267,7 @@ extension Elisp {
255267 }
256268 }
257269 lisp.define("sort") { lisp, args in
270 let variable = lisp.takeInPlaceVariable()
258271 try arity(args, 1...Int.max, "sort")
259272 var key = Sexp.nil
260273 var lessp = Sexp.nil
@@ -274,6 +287,7 @@ extension Elisp {
274287 case .string: throw Unsupported(what: "sort on a string")
275288 default: items = try elements(args[0])
276289 }
290 try refuseShared(lisp, "sort", args, variable: variable)
277291 let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) }
278292 func less(_ a: Sexp, _ b: Sexp) throws -> Bool {
279293 isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b]))
Sources/OrgCore/Config/ElispRegex.swift +56 −44
@@ -1,9 +1,29 @@
11import Foundation
22
3/// An Emacs regexp as an `NSRegularExpression`, with the syntax table of an Org buffer, where
4/// table formulas and Emacs Lisp blocks run. A construct it can't translate exactly throws
5/// `Elisp.Unsupported`, and so do subjects where ICU's tables could differ from Emacs's:
6/// syntax classes against text past ASCII, and case folding with letters past ASCII.
3/// `char-syntax` of each ASCII character in a syntax table.
4struct ElispSyntax: Equatable {
5 let classes: [Character]
6
7 /// `org-mode-syntax-table`, where table formulas run.
8 static let org = ElispSyntax(classes: Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_."))
9 /// `lisp-interaction-mode`'s table, which `emacs -Q --batch -l` evaluates Emacs Lisp
10 /// blocks with, in `*scratch*`.
11 static let emacsLisp = ElispSyntax(classes: Array("_________ >_ ___________________ _\"'___'()__'___wwwwwwwwww_<_____wwwwwwwwwwwwwwwwwwwwwwwwww(\\)__'wwwwwwwwwwwwwwwwwwwwwwwwww_____"))
12
13 func codes(_ syntaxClass: Character) -> [UInt32] {
14 classes.indices.filter { classes[$0] == syntaxClass }.map(UInt32.init)
15 }
16
17 var word: [UInt32] { codes("w") }
18 var symbol: [UInt32] { word + codes("_") }
19
20 func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && classes[Int(c.value)] == "w" }
21}
22
23/// An Emacs regexp as an `NSRegularExpression`, with the syntax table of the buffer it runs
24/// in. A construct it can't translate exactly throws `Elisp.Unsupported`, and so do subjects
25/// where ICU's tables could differ from Emacs's: syntax classes against text past ASCII, and
26/// case folding with letters past ASCII.
727struct ElispRegex {
828 let pattern: String
929 let groups: Int
@@ -16,28 +36,18 @@ struct ElispRegex {
1636 let plain: NSRegularExpression
1737 let folded: NSRegularExpression
1838
19 /// `char-syntax` of each ASCII character in `org-mode-syntax-table`.
20 static let syntax = Array("......... . .................. .\".ww_w()__._._wwwwwwwwww..(_)..wwwwwwwwwwwwwwwwwwwwwwwwww(_)._.wwwwwwwwwwwwwwwwwwwwwwwwww(_)_.")
21
22 static func codes(_ syntaxClass: Character) -> [UInt32] {
23 syntax.indices.filter { syntax[$0] == syntaxClass }.map(UInt32.init)
24 }
25
2639 static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" }
2740
2841 static func set(_ codes: [UInt32], negated: Bool = false) -> String {
2942 "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]"
3043 }
3144
32 static let word = codes("w")
33 static let symbol = word + codes("_")
34
3545 /// A letter with case, which case folding changes.
3646 static func isLetter(_ c: UInt32) -> Bool {
3747 (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false
3848 }
3949
40 init(_ pattern: String) throws {
50 init(_ pattern: String, syntax: ElispSyntax = .org) throws {
4151 self.pattern = pattern
4252 let p = Array(pattern.unicodeScalars)
4353 var out = ""
@@ -137,12 +147,12 @@ struct ElispRegex {
137147 case "cntrl": ("\\x{0}-\\x{1f}", false, false)
138148 case "ascii": ("\\x{0}-\\x{7f}", false, false)
139149 case "nonascii": ("\\x{80}-\\x{10ffff}", false, false)
140 case "space": (Self.codes(" ").map(Self.hex).joined(), true, false)
150 case "space": (syntax.codes(" ").map(Self.hex).joined(), true, false)
141151 case "blank": ("\\x{9}\\x{20}", true, false)
142152 case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false)
143153 case "graph": ("\\x{21}-\\x{7e}", true, false)
144154 case "print": ("\\x{20}-\\x{7e}", true, false)
145 case "word": (Self.word.map(Self.hex).joined(), true, false)
155 case "word": (syntax.word.map(Self.hex).joined(), true, false)
146156 default: throw unsupported("[:\(name):]")
147157 }
148158 text += ascii.0
@@ -215,7 +225,7 @@ struct ElispRegex {
215225 atom("(?:\\\(n))")
216226 case "w", "W":
217227 asciiClasses = true
218 atom(Self.set(Self.word, negated: e == "W"))
228 atom(Self.set(syntax.word, negated: e == "W"))
219229 case "s", "S":
220230 guard i < p.count else { throw unsupported("\\s") }
221231 let code: Character = switch p[i] {
@@ -225,10 +235,11 @@ struct ElispRegex {
225235 }
226236 i += 1
227237 asciiClasses = true
228 atom(Self.set(Self.codes(code), negated: e == "S"))
238 let codes = syntax.codes(code)
239 atom(codes.isEmpty ? (e == "S" ? "[\\s\\S]" : "[^\\s\\S]") : Self.set(codes, negated: e == "S"))
229240 case "b", "B", "<", ">":
230241 asciiClasses = true
231 let w = Self.set(Self.word)
242 let w = Self.set(syntax.word)
232243 let text = switch e {
233244 case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))"
234245 case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))"
@@ -239,7 +250,7 @@ struct ElispRegex {
239250 case "_":
240251 guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") }
241252 asciiClasses = true
242 let s = Self.set(Self.symbol)
253 let s = Self.set(syntax.symbol)
243254 assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))")
244255 i += 1
245256 case "`":
@@ -312,7 +323,7 @@ extension Elisp {
312323
313324 func regex(_ pattern: String) throws -> ElispRegex {
314325 if let cached = regexes[pattern] { return cached }
315 let compiled = try ElispRegex(pattern)
326 let compiled = try ElispRegex(pattern, syntax: syntax)
316327 regexes[pattern] = compiled
317328 return compiled
318329 }
@@ -350,6 +361,8 @@ extension Elisp {
350361 switch chars.next() {
351362 case "&": text += try Self.substring(s, matchData[0]!)
352363 case "\\": text += "\\"
364 // Kept as is, for `query-replace-regexp`.
365 case "?": text += "\\?"
353366 case let d? where ("1"..."9").contains(d):
354367 let n = Int(d.value) - 48
355368 if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) }
@@ -367,7 +380,7 @@ extension Elisp {
367380 }
368381 } else if !fixedCase {
369382 // How `replace-match` decides to change the replacement's case from the replaced text.
370 func isWord(_ c: Unicode.Scalar) -> Bool { c.isASCII && ElispRegex.syntax[Int(c.value)] == "w" }
383 let isWord = syntax.isWord
371384 var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false)
372385 var previous: Unicode.Scalar = "\n"
373386 for c in old.unicodeScalars {
@@ -485,38 +498,37 @@ extension Elisp {
485498 func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil }
486499 let s = try string(args[0])
487500 let length = s.unicodeScalars.count
488 let keepNulls = isNil(optional(1)) ? false : isNil(optional(2))
501 let keepEmpty = !isNil(optional(1)) && isNil(optional(2))
489502 let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1))
490503 let trim = isNil(optional(3)) ? nil : try string(optional(3))
491504 var list: [Sexp] = []
492 func push(_ from: Int, _ to: Int) throws {
493 var from = from
494 if let trim, let data = try lisp.stringMatch(trim, s, start: .integer(from)) {
495 lisp.matchData = data
496 if data[0]!.lowerBound == from { from = data[0]!.upperBound }
505 // The loop of Emacs 31's `split-string`, empty separator matches included.
506 func push(_ item: String, last: Bool) throws {
507 guard let trim else {
508 if !last || keepEmpty || !item.isEmpty { list.append(.string(item)) }
509 return
497510 }
498 guard keepNulls || from < to else { return }
499 guard from <= to else { throw Signal(message: "Args out of range") }
500 var this = try substring(s, from..<to)
501 if let trim, let data = try lisp.stringMatch(trim + "\\'", this) {
511 let count = item.unicodeScalars.count
512 var begin = 0
513 if let data = try lisp.stringMatch("\\`\\(?:" + trim + "\\)", item) {
502514 lisp.matchData = data
503 if data[0]!.lowerBound < this.unicodeScalars.count { this = try substring(this, 0..<data[0]!.lowerBound) }
515 begin = data[0]!.upperBound
504516 }
505 if keepNulls || !this.isEmpty { list.append(.string(this)) }
517 let end = try lisp.stringMatch("\\(?:" + trim + "\\)\\'", item, start: .integer(begin))?[0]!.lowerBound ?? count
518 let trimmed = begin > 0 || end < count ? try substring(item, begin..<end) : item
519 if keepEmpty || (last ? !trimmed.isEmpty : begin < end) { list.append(.string(trimmed)) }
506520 }
521 var next = 0
507522 var start = 0
508 var notFirst = false
509 while true {
510 let from = notFirst && start == lisp.matchData.first??.lowerBound && start < length ? start + 1 : start
511 guard let data = try lisp.stringMatch(separators, s, start: .integer(from)) else { break }
523 while let data = try lisp.stringMatch(separators, s, start: .integer(next)) {
512524 lisp.matchData = data
525 let separator = data[0]!
526 if keepEmpty || start < separator.lowerBound { try push(try substring(s, start..<separator.lowerBound), last: false) }
527 next = max(next + 1, separator.upperBound)
528 start = separator.upperBound
513529 guard start < length else { break }
514 notFirst = true
515 let thisStart = start
516 start = data[0]!.upperBound
517 try push(thisStart, data[0]!.lowerBound)
518530 }
519 try push(start, length)
531 try push(try substring(s, start..<length), last: true)
520532 return Elisp.list(list)
521533 }
522534 }
Sources/OrgCore/Config/ElispTime.swift +35 −12
@@ -75,12 +75,31 @@ extension Elisp {
7575 return parts
7676 }
7777
78 /// `encode-time` of a local date and time.
78 /// Days from 1 January 1970 to absolute day 1, 1 January of year 1.
79 static let epochDay = 719163
80
81 /// `encode-time` of a local date and time, in the proleptic Gregorian calendar as Emacs
82 /// counts. Foundation's Gregorian calendar is Julian before 15 October 1582, so earlier
83 /// dates are counted here, where no daylight saving time applies.
7984 static func encode(_ parts: [Int], calendar: Calendar) throws -> Time {
80 guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: parts.count > 5 ? parts[5] : 0)) else {
81 throw Unsupported(what: "date \(parts)")
85 let second = parts.count > 5 ? parts[5] : 0
86 if parts[0] >= 1583 {
87 guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: second)) else {
88 throw Unsupported(what: "date \(parts)")
89 }
90 return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down)))
8291 }
83 return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down)))
92 let local = (Days.absolute(year: parts[0], month: parts[1], day: parts[2]) - epochDay) * 86400 + parts[3] * 3600 + parts[4] * 60 + second
93 func offset(_ seconds: Int) -> Int { calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) }
94 return Time(seconds: local - offset(local - offset(local)))
95 }
96
97 /// The local date and time of `seconds` in the proleptic Gregorian calendar: the absolute
98 /// day, and the seconds into it.
99 static func civil(_ seconds: Int, calendar: Calendar) -> (day: Int, second: Int) {
100 let local = seconds + calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds)))
101 let day = local >= 0 ? local / 86400 : -((-local - 1) / 86400) - 1
102 return (day + epochDay, local - day * 86400)
84103 }
85104
86105 /// `date-to-time` for ISO 8601 dates, with or without a time.
@@ -94,17 +113,21 @@ extension Elisp {
94113 }
95114
96115 static func days(_ seconds: Int, calendar: Calendar) -> Int {
97 Days.absolute(Date(timeIntervalSince1970: Double(seconds)), calendar: calendar)
116 civil(seconds, calendar: calendar).day
98117 }
99118
100119 /// `format-time-string` with the conversions that don't depend on the locale, without
101120 /// flags or widths.
102121 static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String {
103 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: Date(timeIntervalSince1970: Double(seconds)))
104 let (year, month, day, hour, minute, second) = (c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!)
122 let (absolute, secondOfDay) = civil(seconds, calendar: calendar)
123 let (year, month, day) = Days.date(absolute)
124 let (hour, minute, second) = (secondOfDay / 3600, secondOfDay % 3600 / 60, secondOfDay % 60)
105125 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
106126 let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
107 let weekday = c.weekday! - 1
127 let weekday = Days.weekday(absolute)
128 // Four digits with the sign, and the last two digits of the year without it.
129 let yearText = year < 0 ? String(format: "-%03d", -year) : String(format: "%04d", year)
130 let shortYear = abs(year) % 100
108131 let hour12 = hour % 12 == 0 ? 12 : hour % 12
109132 var out = ""
110133 var chars = format.makeIterator()
@@ -115,8 +138,8 @@ extension Elisp {
115138 }
116139 guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") }
117140 switch f {
118 case "Y": out += String(year)
119 case "y": out += String(format: "%02d", year % 100)
141 case "Y": out += yearText
142 case "y": out += String(format: "%02d", shortYear)
120143 case "m": out += String(format: "%02d", month)
121144 case "d": out += String(format: "%02d", day)
122145 case "e": out += String(format: "%2d", day)
@@ -134,8 +157,8 @@ extension Elisp {
134157 case "u": out += String(weekday == 0 ? 7 : weekday)
135158 case "w": out += String(weekday)
136159 case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0))
137 case "F": out += String(format: "%d-%02d-%02d", year, month, day)
138 case "D": out += String(format: "%02d/%02d/%02d", month, day, year % 100)
160 case "F": out += yearText + String(format: "-%02d-%02d", month, day)
161 case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear)
139162 case "R": out += String(format: "%02d:%02d", hour, minute)
140163 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second)
141164 case "s": out += String(seconds)
Tests/OrgCoreTests/BabelTests.swift +41
@@ -292,6 +292,47 @@ struct BabelTests {
292292 }
293293 }
294294
295 /// Blocks whose result depends on how Emacs runs them: lexical binding, and the syntax table
296 /// of `*scratch*`.
297 static let runnerCases = [
298 "(list (string-match \"\\\\w\" \"'a\") (string-match \"\\\\s(\" \"<\") (string-match \"\\\\_<b\" \"a\\\\b\") (replace-regexp-in-string \"\\\\w+\" \"X\" \"it's\"))",
299 "(list (split-string \"a b\\nc\" \"[[:space:]]\") (string-match \"\\\\s-\" \"a\\nb\") (string-match \"\\\\s.\" \"a,b\"))",
300 "(progn (defun adder (n) (lambda (x) (+ x n))) (funcall (adder 3) 4))",
301 "(progn (defun g () y) (let ((y 5)) (g)))",
302 "(let ((fs nil)) (dolist (i '(1 2)) (push (lambda () i) fs)) (mapcar #'funcall fs))",
303 "(let ((fs nil)) (dotimes (i 2) (push (lambda () i) fs)) (mapcar #'funcall fs))",
304 "(mapcar #'funcall (cl-loop for i in '(1 2) collect (lambda () i)))",
305 "(let ((x 1)) (let ((f (lambda () x))) (let ((x 2)) (funcall f))))",
306 "(let* ((x 1) (f (lambda () x)) (x 2)) (funcall f))",
307 "(let ((n 0)) (let ((inc (lambda () (setq n (1+ n))))) (funcall inc) (funcall inc) n))",
308 "(progn (defvar orgstar-special 1) (defun orgstar-read () orgstar-special) (let ((orgstar-special 2)) (orgstar-read)))",
309 "(let ((x 5)) (defun orgstar-gx () x) (orgstar-gx))",
310 "(let ((x 1)) (funcall '(lambda () x)))",
311 "(let ((x 3)) (mapcar (lambda (y) (* x y)) '(1 2)))",
312 "(let ((k 1)) (pcase 2 ((pred (lambda (v) (> v k))) 'big)))",
313 ].map { "#+begin_src emacs-lisp\n\($0)\n#+end_src\n" }
314
315 /// Natively as with `emacs -Q --batch -l`, the way the app runs Emacs Lisp blocks.
316 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
317 func lispRunsNativelyLikeTheEmacsRunner() throws {
318 let folder = FileManager.default.temporaryDirectory
319 for text in Self.runnerCases {
320 let caret = (text as NSString).range(of: "#+begin_src").location + 2
321 let emacs = try TestBabelRunner.execute(text, caret: caret, directory: folder)
322 do {
323 let ours = try TestBabelRunner.execute(text, caret: caret, directory: folder, native: true)
324 // A Lisp error: Emacs's backtrace becomes the result here, and the run fails in the app.
325 if emacs.text.contains("#+begin_example\n\nError: ") {
326 #expect(ours.failure != nil && ours.text == text, "\(text)\nours: \(ours.text)")
327 continue
328 }
329 #expect(ours.text == emacs.text, "\(text)\nours (\(ours.failure ?? "")):\n\(ours.text)\nemacs (\(emacs.failure ?? "")):\n\(emacs.text)")
330 } catch is NativeUnsupported {
331 Issue.record("not run natively:\n\(text)")
332 }
333 }
334 }
335
295336 @Test func referencedQueryBlocksAskEveryTime() {
296337 let text = "#+begin_src sh :var x=gen\necho $x\n#+end_src\n\n#+NAME: gen\n#+begin_src sh :eval query\necho 1\n#+end_src\n"
297338 guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else {
Tests/OrgCoreTests/ElispTests.swift +27 −4
@@ -93,6 +93,10 @@ struct ElispTests {
9393 #"(split-string "a1b22c" "[0-9]+")"#, #"(split-string " a b " " +")"#, #"(split-string "a,b,,c" "," t)"#,
9494 #"(split-string " a , b " "," t " ")"#, #"(split-string "abc" "")"#, #"(split-string "abc" "" t)"#, #"(split-string "a-b_c" "\\W")"#,
9595 #"(split-string "a,b" "," nil "\\s-*")"#, #"(split-string "a b" nil)"#, #"(split-string " two words " "[ ]+" t)"#,
96 #"(split-string "a\nb" "$")"#, #"(split-string "a\nb\nc" "^")"#, #"(split-string "foo bar" "\\>")"#, #"(split-string "foo bar" "\\<")"#,
97 #"(split-string "foo bar" "\\b")"#, #"(split-string "a\nb" "$" t)"#, #"(split-string " a ,, b " "," nil " +")"#, #"(split-string " a ,, b " "," t " +")"#,
98 #"(replace-regexp-in-string "a" "\\?" "a")"#, #"(let ((s "abc")) (string-match "b" s) (replace-match "\\?" nil nil s))"#,
99 #"(string-pad "ab" -1)"#, "(let* ((a (list 3 1 2)) (b (list 4 5))) (sort a #'<) (list a b))",
96100 "(last '(1 2 3))", "(last '(1 2 3) 2)", "(last '(1 2 3) 0)", "(last '(1 2 . 3))", "(last nil)", "(butlast '(1 2 3))",
97101 "(butlast '(1 2 3) 2)", "(butlast '(1 2 3) 0)", "(butlast nil)", "(butlast '(1 2 . 3))", #"(delete-dups (list 1 2 1 "a" "a"))"#,
98102 "(nreverse (list 1 2 3))", "(nreverse [1 2 3])", #"(nreverse "abc")"#, "(let ((l (list 1 2 3))) (nreverse l) l)",
@@ -132,6 +136,11 @@ struct ElispTests {
132136 "(pcase 1.0 (1.0 'f))", "(pcase 1 ((or 1 2) 'a))", "(pcase 1 ((pred (< 0)) 'a))", "(cl-loop for x across [1 2] collect x)",
133137 "(cl-loop for i from 1 to 3 sum i collect i)", "(cl-loop repeat 3 collect 1)", "(let ((l (list 1 2))) (cl-incf (car l)))",
134138 "(when-let ((x 1)) x)", "(undefined-orgstar-macro (car 1))", "(undefined-orgstar-macro void-orgstar-variable)",
139 // In-place changes to a list another value may share.
140 "(let* ((a (list 3 1 2)) (b a)) (sort a '<) b)", "(let ((x (list 1 3 2))) (sort (cdr x) '<) x)",
141 "(let* ((a (list 3 1 2)) (b (list a))) (sort a '<) b)", "(let* ((a (list 1 2 3)) (b a)) (nreverse a) b)",
142 "(let* ((a (list 1 1 2)) (b a)) (delete-dups a) b)", "(let ((a (list 3 1 2))) (list a (sort a '<)))",
143 "(let* ((a (list 3 1 2)) (b a)) (funcall #'sort a '<) b)", "(let ((a (list 3 1 2))) (prog1 a (sort a '<)))",
135144 ]
136145
137146 static func strict(_ form: String) -> String {
@@ -162,11 +171,19 @@ struct ElispTests {
162171 #expect(Self.strict("(undefined-orgstar-function (car 1))") == "unsupported")
163172 }
164173
165 /// The syntax classes follow `org-mode-syntax-table`.
174 /// The syntax classes follow `org-mode-syntax-table`, and for Emacs Lisp blocks, the table
175 /// of `*scratch*` in `emacs -Q --batch -l`.
166176 @Test(.enabled(if: oracle))
167 func syntaxTableMatchesOrgMode() throws {
168 let emacs = try EmacsOracle.evaluate("", "(list (let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r))))")
169 #expect(emacs == [String(ElispRegex.syntax)])
177 func syntaxTablesMatchEmacs() throws {
178 let classes = "(let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r)))"
179 let emacs = try EmacsOracle.evaluate("", "(list \(classes))")
180 #expect(emacs == [String(ElispSyntax.org.classes)])
181 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-syntax-\(UUID().uuidString)")
182 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
183 defer { try? FileManager.default.removeItem(at: folder) }
184 let script = folder.appendingPathComponent("syntax.el")
185 try ";;; -*- lexical-binding: t -*-\n(princ \(classes))\n".write(to: script, atomically: true, encoding: .utf8)
186 #expect(try EmacsOracle.run(["-Q", "--batch", "-l", script.path]) == String(ElispSyntax.emacsLisp.classes))
170187 }
171188
172189 static let timeForms = [
@@ -189,6 +206,12 @@ struct ElispTests {
189206 #"(let ((s (format-time-string "%Y-%m-%d"))) (string-match "\\`[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\'" s))"#,
190207 "(let ((t0 (current-time))) (and (consp t0) (= (length t0) 4) (< (abs (- (float-time t0) (float-time))) 5)))",
191208 "(> (time-to-days (current-time)) 739000)",
209 // Proleptic Gregorian dates, before 1582 and before year 1.
210 #"(org-time-string-to-time "<1500-01-01>")"#, #"(org-time-string-to-time "<0099-01-01>")"#, #"(date-to-time "1582-10-10")"#,
211 #"(format-time-string "%F %a" (date-to-time "1500-01-01"))"#, #"(format-time-string "%F" -15000000000)"#,
212 #"(format-time-string "%Y" -100000000000)"#, #"(format-time-string "%Y %y %D %F %j %a" -62200000000)"#,
213 #"(format-time-string "%Y %F" -62135596800)"#, "(time-to-days -100000000000)", #"(time-to-days (date-to-time "1500-01-01"))"#,
214 #"(days-between "1500-01-01" "1600-01-01")"#,
192215 ]
193216
194217 static let unsupportedTime = [
docs/manual/guide/10-tables.org +4 −3
@@ -457,7 +457,7 @@ The evaluator supports:
457457 =unless=, =cond=, =and=, =or=, =let=, =let*=, =setq=, =push=, =pop=, =while=,
458458 =dolist=, =dotimes=, =with-output-to-string=, =ignore-errors=, =condition-case=,
459459 =save-match-data=, =defun=, =defvar=, =defconst=, =let-alist=, =cl-incf= and =cl-decf=
460 on a variable;
460 on a variable, with dynamic binding, as Org evaluates formulas;
461461- =pcase= with literal, symbol, quoted, backquoted and =pred= patterns, where =pred=
462462 takes a function name or a lambda;
463463- =cl-loop= with =for VAR in LIST=, =for VAR from START to END=, and one kind of
@@ -473,7 +473,8 @@ The evaluator supports:
473473 =append=, =length=, =reverse=, =number-sequence=, =memq=, =member=, =memql=, =assoc=,
474474 =assq=, =delq=, =delete=, =mapcar=, =mapc=, =mapconcat=, =funcall=, =apply=,
475475 =identity=, =ignore=, =last=, =butlast=, =delete-dups=, =nreverse=, =sort= (both
476 calling conventions), =seq-reduce=, =seq-filter=, =seq-remove=, =seq-map=, =seq-uniq=,
476 calling conventions; these three need Emacs when they would change a list that
477 another variable, list or argument may share), =seq-reduce=, =seq-filter=, =seq-remove=, =seq-map=, =seq-uniq=,
477478 =cl-reduce= (with =:initial-value=), =cl-remove-if=, =cl-remove-if-not=, =cl-find= and
478479 =cl-position= (with =:test=);
479480- strings: =concat=, =format=, =format-message=, ~string=~, =string-equal=, =string<=,
@@ -488,7 +489,7 @@ The evaluator supports:
488489- time: =current-time=, =format-time-string=, =float-time=, =time-add=, =time-subtract=,
489490 =time-to-days=, =date-to-time=, =days-between=, =org-time-string-to-time=,
490491 =org-time-string-to-absolute= and the =calendar-= functions that diary sexps use, in
491 the local time zone;
492 the local time zone and the proleptic Gregorian calendar;
492493- output and errors: =princ=, =prin1=, =print=, =terpri=, =message=, =error=,
493494 =user-error=;
494495- Org's lookup functions =org-lookup-first=, =org-lookup-last= and =org-lookup-all=.
docs/manual/guide/11-code-blocks.org +1 −1
@@ -620,7 +620,7 @@ An inline call, =call_double(n=6)=, has the same parts as a =#+CALL:= line: =cal
620620
621621On the Mac, an =emacs-lisp= or =elisp= block runs in a new =emacs -Q --batch= for each run, with lexical binding on. =-Q= means your init file and packages are not loaded, and nothing carries over between runs. orgstar looks for Emacs at =ORGSTAR_EMACS=, then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and =/usr/bin/emacs=. Without Emacs, the block runs in orgstar's own Emacs Lisp interpreter, and a block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed."
622622
623On iOS, Emacs Lisp blocks run in orgstar's own Emacs Lisp interpreter. It has the forms and functions listed under Lisp formulas in [[file:10-tables.org][Tables]]: list, string, number and control forms, regular expressions on strings, =defun=, =pcase=, =cl-loop=, the =seq-= and =cl-= sequence functions, time functions, =princ= and =message=. It binds variables dynamically, and it has no buffers. A block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, on the Mac." A Lisp error fails the run, as it does in Emacs.
623On iOS, Emacs Lisp blocks run in orgstar's own Emacs Lisp interpreter. It has the forms and functions listed under Lisp formulas in [[file:10-tables.org][Tables]]: list, string, number and control forms, regular expressions on strings, =defun=, =pcase=, =cl-loop=, the =seq-= and =cl-= sequence functions, time functions, =princ= and =message=. Like =emacs -Q --batch=, it uses lexical binding, with dynamic binding for variables declared with =defvar=, and the syntax table of Emacs Lisp mode for regular expressions. It has no buffers. A block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, on the Mac." A Lisp error fails the run, as it does in Emacs.
624624
625625In the [[file:../install.org][Mac App Store version]], Emacs Lisp blocks run in the same interpreter as on iOS. A block that uses something it does not have fails with "This block uses Emacs Lisp that runs only in Emacs."
626626