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 {
71 let name = String(what.dropLast(" on a place".count)) 71 let name = String(what.dropLast(" on a place".count))
72 return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable") 72 return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable")
73 } 73 }
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 }
74 if what.hasSuffix(" in a buffer") { 78 if what.hasSuffix(" in a buffer") {
75 let name = String(what.dropLast(" in a buffer".count)) 79 let name = String(what.dropLast(" in a buffer".count))
76 return String(localized: "\(name) in a buffer", comment: comment) 80 return String(localized: "\(name) in a buffer", comment: comment)
Sources/OrgCore/Compute/BabelLanguages.swift +5
@@ -92,11 +92,16 @@ extension Babel {
92 /// doesn't have. 92 /// doesn't have.
93 public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? { 93 public static func evaluateNatively(_ job: BabelJob) throws(Failure) -> BabelOutput? {
94 guard let form = job.lispForm, let sexp = try? LispReader.readFirst(form).sexp else { return nil } 94 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*`.
95 let lisp = Elisp() 96 let lisp = Elisp()
97 lisp.lexical = true
98 lisp.syntax = .emacsLisp
96 lisp.standardTime() 99 lisp.standardTime()
97 let result: Sexp 100 let result: Sexp
98 do { 101 do {
99 result = try lisp.eval(sexp) 102 result = try lisp.eval(sexp)
103 // Emacs prints closures as `#[ARGS BODY ENV]`.
104 if Elisp.containsClosure(result) { return nil }
100 } catch is Elisp.Unsupported { 105 } catch is Elisp.Unsupported {
101 return nil 106 return nil
102 } catch { 107 } catch {
Sources/OrgCore/Config/Elisp.swift +210 −60
@@ -1,8 +1,8 @@
1import Foundation 1import Foundation
2 2
3/// A small Emacs Lisp evaluator over `Sexp` values: the special forms and functions diary 3/// 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 4/// sexps and table formulas use, with dynamic binding unless `lexical` is set. A function or
5/// throws `Unsupported`; errors Emacs would signal throw `Signal`. 5/// form it doesn't have throws `Unsupported`; errors Emacs would signal throw `Signal`.
6public final class Elisp { 6public final class Elisp {
7 public struct Unsupported: Error, Equatable, CustomStringConvertible { 7 public struct Unsupported: Error, Equatable, CustomStringConvertible {
8 public let what: String 8 public let what: String
@@ -16,7 +16,33 @@ public final class Elisp {
16 16
17 public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp 17 public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp
18 18
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 }
20 private var functions: [String: Builtin] = [:] 46 private var functions: [String: Builtin] = [:]
21 var steps = 0 47 var steps = 0
22 static let stepLimit = 1_000_000 48 static let stepLimit = 1_000_000
@@ -45,27 +71,114 @@ public final class Elisp {
45 /// Defines or replaces a function. 71 /// Defines or replaces a function.
46 public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function } 72 public func define(_ name: String, _ function: @escaping Builtin) { functions[name] = function }
47 73
48 /// Sets a global variable. 74 /// Sets a global variable, which is special.
49 public func set(_ name: String, _ value: Sexp) { scopes[0][name] = value } 75 public func set(_ name: String, _ value: Sexp) {
76 scopes[0].vars[name] = value
77 specials.insert(name)
78 }
50 79
51 public func value(_ name: String) throws -> Sexp { 80 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 } }
53 throw Signal(message: "Symbol’s value as variable is void: \(name)") 82 throw Signal(message: "Symbol’s value as variable is void: \(name)")
54 } 83 }
55 84
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.
57 public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T { 87 public func binding<T>(_ bindings: [String: Sexp], _ body: () throws -> T) rethrows -> T {
58 scopes.append(bindings) 88 try binding(Frame(bindings), body)
59 defer { scopes.removeLast() } 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 }
60 return try body() 107 return try body()
61 } 108 }
62 109
63 func assign(_ name: String, _ v: Sexp) { 110 func assign(_ name: String, _ v: Sexp) {
64 for i in scopes.indices.reversed() where scopes[i][name] != nil { 111 for scope in scopes.reversed() where scope.vars[name] != nil {
65 scopes[i][name] = v 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:
66 return 164 return
67 } 165 }
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") }
69 } 182 }
70 183
71 // MARK: - Values 184 // MARK: - Values
@@ -202,7 +315,7 @@ public final class Elisp {
202 guard let head = items.first else { return .nil } 315 guard let head = items.first else { return .nil }
203 guard case .symbol(let name) = head else { 316 guard case .symbol(let name) = head else {
204 if case .list(let lambda) = head, lambda.first == .symbol("lambda") { 317 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()))
206 } 319 }
207 throw Signal(message: "Invalid function: \(head.description)") 320 throw Signal(message: "Invalid function: \(head.description)")
208 } 321 }
@@ -211,18 +324,30 @@ public final class Elisp {
211 // The function first, so an unknown one, or a macro this evaluator lacks, is 324 // The function first, so an unknown one, or a macro this evaluator lacks, is
212 // unsupported rather than an error from its arguments. 325 // unsupported rather than an error from its arguments.
213 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } 326 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
215 let result = try function(self, values) 334 let result = try function(self, values)
216 if case .symbol(let variable)? = args.first, variable != "nil", variable != "t", !variable.hasPrefix(":"), 335 inPlaceVariable = nil
217 let after = Self.afterInPlace(name, values, result) { 336 if let variable, let after = Self.afterInPlace(name, values, result) { assign(variable, after) }
218 assign(variable, after)
219 }
220 return result 337 return result
221 case .dotted: throw Signal(message: "Invalid function") 338 case .dotted: throw Signal(message: "Invalid function")
222 default: return form 339 default: return form
223 } 340 }
224 } 341 }
225 342
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
226 func progn(_ body: some Collection<Sexp>) throws -> Sexp { 351 func progn(_ body: some Collection<Sexp>) throws -> Sexp {
227 var result = Sexp.nil 352 var result = Sexp.nil
228 for form in body { result = try eval(form) } 353 for form in body { result = try eval(form) }
@@ -235,16 +360,17 @@ public final class Elisp {
235 case "quote": 360 case "quote":
236 return args.first ?? .nil 361 return args.first ?? .nil
237 case "function": 362 case "function":
238 return args.first ?? .nil 363 return closure(args.first ?? .nil)
239 case "lambda": 364 case "lambda":
240 return .list([.symbol("lambda")] + args) 365 return closure(.list([.symbol("lambda")] + args))
241 case "progn": 366 case "progn":
242 return try progn(args) 367 return try progn(args)
243 case "prog1": 368 case "prog1":
244 guard let first = args.first else { return .nil } 369 guard let first = args.first else { return .nil }
245 let value = try eval(first) 370 pending.append([try eval(first)])
371 defer { pending.removeLast() }
246 _ = try progn(args.dropFirst()) 372 _ = try progn(args.dropFirst())
247 return value 373 return pending[pending.count - 1][0]
248 case "if": 374 case "if":
249 guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") } 375 guard args.count >= 2 else { throw Signal(message: "Wrong number of arguments: if") }
250 return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1]) 376 return Self.isNil(try eval(args[0])) ? try progn(args.dropFirst(2)) : try eval(args[1])
@@ -274,22 +400,29 @@ public final class Elisp {
274 return .nil 400 return .nil
275 case "let", "let*": 401 case "let", "let*":
276 guard let first = args.first else { return .nil } 402 guard let first = args.first else { return .nil }
277 var bindings: [String: Sexp] = [:] 403 var specs: [(String, Sexp?)] = []
278 scopes.append([:])
279 defer { scopes.removeLast() }
280 for binding in try Self.elements(first) { 404 for binding in try Self.elements(first) {
281 let (variable, value): (String, Sexp)
282 if case .symbol(let s) = binding { 405 if case .symbol(let s) = binding {
283 (variable, value) = (s, .nil) 406 specs.append((s, nil))
284 } else { 407 } else {
285 let parts = try Self.elements(binding) 408 let parts = try Self.elements(binding)
286 guard case .symbol(let s)? = parts.first else { throw Signal(message: "Bad binding") } 409 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))
288 } 411 }
289 if name == "let*" { scopes[scopes.count - 1][variable] = value } else { bindings[variable] = value }
290 } 412 }
291 if name == "let" { scopes[scopes.count - 1] = bindings } 413 if name == "let" {
292 return try progn(args.dropFirst()) 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[...])
293 case "setq": 426 case "setq":
294 var value = Sexp.nil 427 var value = Sexp.nil
295 var i = 0 428 var i = 0
@@ -320,17 +453,16 @@ public final class Elisp {
320 let source = try eval(spec[1]) 453 let source = try eval(spec[1])
321 let items = name == "dolist" ? try Self.elements(source) : [] 454 let items = name == "dolist" ? try Self.elements(source) : []
322 let count = name == "dolist" ? items.count : max(0, try Self.int(source)) 455 let count = name == "dolist" ? items.count : max(0, try Self.int(source))
323 scopes.append([:]) 456 pending.append([source])
324 defer { scopes.removeLast() } 457 defer { pending.removeLast() }
458 // A new binding each time round, as closures over the variable see it.
325 for i in 0..<count { 459 for i in 0..<count {
326 steps += 1 460 steps += 1
327 if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") } 461 if steps > Self.stepLimit { throw Signal(message: "Evaluation took too long") }
328 scopes[scopes.count - 1][variable] = name == "dolist" ? items[i] : .integer(i) 462 _ = try binding([variable: name == "dolist" ? items[i] : .integer(i)]) { try progn(args.dropFirst()) }
329 _ = try progn(args.dropFirst())
330 } 463 }
331 if spec.count > 2 { 464 if spec.count > 2 {
332 scopes[scopes.count - 1][variable] = name == "dotimes" ? .integer(count) : .nil 465 return try binding([variable: name == "dotimes" ? .integer(count) : .nil]) { try eval(spec[2]) }
333 return try eval(spec[2])
334 } 466 }
335 return .nil 467 return .nil
336 case "with-output-to-string": 468 case "with-output-to-string":
@@ -368,37 +500,55 @@ public final class Elisp {
368 public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp { 500 public func call(_ function: Sexp, _ args: [Sexp]) throws -> Sexp {
369 switch function { 501 switch function {
370 case .symbol(let name): return try callNamed(name, args) 502 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!])
371 case .list(let items) where items.first == .symbol("lambda") && items.count >= 2: 505 case .list(let items) where items.first == .symbol("lambda") && items.count >= 2:
372 var bindings: [String: Sexp] = [:] 506 // Under lexical binding, a lambda list runs outside the caller's local frames.
373 var mode = "required" 507 return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: lexical ? [] : nil)
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)) }
395 default: 508 default:
396 throw Signal(message: "Invalid function: \(function.description)") 509 throw Signal(message: "Invalid function: \(function.description)")
397 } 510 }
398 } 511 }
399 512
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
400 func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp { 549 func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp {
401 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } 550 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
551 inPlaceVariable = nil
402 return try function(self, args) 552 return try function(self, args)
403 } 553 }
404 554
Sources/OrgCore/Config/ElispForms.swift +8 −8
@@ -26,8 +26,8 @@ extension Elisp {
26 var body = Array(args.dropFirst(2)) 26 var body = Array(args.dropFirst(2))
27 if body.count > 1, case .string = body[0] { body.removeFirst() } 27 if body.count > 1, case .string = body[0] { body.removeFirst() }
28 while let head = body.first?.head, head == "declare" || head == "interactive" { body.removeFirst() } 28 while let head = body.first?.head, head == "declare" || head == "interactive" { body.removeFirst() }
29 let lambda = Sexp.list([.symbol("lambda"), args[1]] + body) 29 let function = closure(.list([.symbol("lambda"), args[1]] + body))
30 define(name) { lisp, values in try lisp.call(lambda, values) } 30 define(name) { lisp, values in try lisp.call(function, values) }
31 return .symbol(name) 31 return .symbol(name)
32 } 32 }
33 33
@@ -35,7 +35,8 @@ extension Elisp {
35 func defineVariable(_ args: [Sexp], constant: Bool) throws -> Sexp { 35 func defineVariable(_ args: [Sexp], constant: Bool) throws -> Sexp {
36 guard case .symbol(let name)? = args.first, args.count <= 3 else { throw Signal(message: "Malformed \(constant ? "defconst" : "defvar")") } 36 guard case .symbol(let name)? = args.first, args.count <= 3 else { throw Signal(message: "Malformed \(constant ? "defconst" : "defvar")") }
37 if constant, args.count < 2 { throw Signal(message: "Wrong number of arguments: defconst, 1") } 37 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]) }
39 return .symbol(name) 40 return .symbol(name)
40 } 41 }
41 42
@@ -121,9 +122,8 @@ extension Elisp {
121 case .list(let items) where items.count == 2 && items[0] == .symbol("\\`"): 122 case .list(let items) where items.count == 2 && items[0] == .symbol("\\`"):
122 return try backquoted(items[1], value, &bindings) 123 return try backquoted(items[1], value, &bindings)
123 case .list(let items) where items.count == 2 && items[0] == .symbol("pred") && (items[1].symbol != nil || items[1].head == "lambda"): 124 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]
125 let soFar = bindings 125 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]) })
127 default: 127 default:
128 throw Unsupported(what: "pcase pattern \(pattern.description)") 128 throw Unsupported(what: "pcase pattern \(pattern.description)")
129 } 129 }
@@ -162,7 +162,7 @@ extension Elisp {
162 // What each `in` clause has left. 162 // What each `in` clause has left.
163 var lists: [Int: Sexp] = [:] 163 var lists: [Int: Sexp] = [:]
164 var actions: [(kind: String, forms: [Sexp])] = [] 164 var actions: [(kind: String, forms: [Sexp])] = []
165 scopes.append([:]) 165 scopes.append(Frame())
166 defer { scopes.removeLast() } 166 defer { scopes.removeLast() }
167 var i = 0 167 var i = 0
168 func next() throws -> Sexp { 168 func next() throws -> Sexp {
@@ -178,10 +178,10 @@ extension Elisp {
178 switch try next() { 178 switch try next() {
179 case .symbol("in"): 179 case .symbol("in"):
180 lists[iterators.count] = try eval(try next()) 180 lists[iterators.count] = try eval(try next())
181 scopes[scopes.count - 1][variable] = .nil 181 scopes[scopes.count - 1].vars[variable] = .nil
182 iterators.append(.list(variable)) 182 iterators.append(.list(variable))
183 case .symbol("from"): 183 case .symbol("from"):
184 scopes[scopes.count - 1][variable] = try eval(try next()) 184 scopes[scopes.count - 1].vars[variable] = try eval(try next())
185 var limit: Sexp? 185 var limit: Sexp?
186 if i < args.count, args[i] == .symbol("to") { 186 if i < args.count, args[i] == .symbol("to") {
187 i += 1 187 i += 1
Sources/OrgCore/Config/ElispLibrary.swift +17 −3
@@ -100,7 +100,9 @@ extension Elisp {
100 lisp.define("string-pad") { _, args in 100 lisp.define("string-pad") { _, args in
101 try arity(args, 2...4, "string-pad") 101 try arity(args, 2...4, "string-pad")
102 let s = try string(args[0]) 102 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
104 guard pad > 0 else { return .string(s) } 106 guard pad > 0 else { return .string(s) }
105 guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") } 107 guard pad <= lengthLimit else { throw Signal(message: "Too long for string-pad") }
106 let padding = String(repeating: String(try scalar(args.count > 2 && !isNil(args[2]) ? try int(args[2]) : 32)), count: pad) 108 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 {
157 } 159 }
158 } 160 }
159 161
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
160 /// Keyword arguments `args` after the first `count`, of which only `allowed` are known. 168 /// Keyword arguments `args` after the first `count`, of which only `allowed` are known.
161 static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] { 169 static func keywords(_ args: [Sexp], after count: Int, allowed: Set<String>, _ name: String) throws -> [String: Sexp] {
162 let rest = Array(args.dropFirst(count)) 170 let rest = Array(args.dropFirst(count))
@@ -242,12 +250,16 @@ extension Elisp {
242 guard n > 0 else { return args[0] } 250 guard n > 0 else { return args[0] }
243 return list(Array(try elements(args[0]).dropLast(n))) 251 return list(Array(try elements(args[0]).dropLast(n)))
244 } 252 }
245 lisp.define("delete-dups") { _, args in 253 lisp.define("delete-dups") { lisp, args in
254 let variable = lisp.takeInPlaceVariable()
246 try arity(args, 1...1, "delete-dups") 255 try arity(args, 1...1, "delete-dups")
256 try refuseShared(lisp, "delete-dups", args, variable: variable)
247 return list(uniqueEqual(try elements(args[0]))) 257 return list(uniqueEqual(try elements(args[0])))
248 } 258 }
249 lisp.define("nreverse") { _, args in 259 lisp.define("nreverse") { lisp, args in
260 let variable = lisp.takeInPlaceVariable()
250 try arity(args, 1...1, "nreverse") 261 try arity(args, 1...1, "nreverse")
262 try refuseShared(lisp, "nreverse", args, variable: variable)
251 switch args[0] { 263 switch args[0] {
252 case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed()))) 264 case .string(let s): return .string(String(String.UnicodeScalarView(s.unicodeScalars.reversed())))
253 case .vector(let items): return .vector(items.reversed()) 265 case .vector(let items): return .vector(items.reversed())
@@ -255,6 +267,7 @@ extension Elisp {
255 } 267 }
256 } 268 }
257 lisp.define("sort") { lisp, args in 269 lisp.define("sort") { lisp, args in
270 let variable = lisp.takeInPlaceVariable()
258 try arity(args, 1...Int.max, "sort") 271 try arity(args, 1...Int.max, "sort")
259 var key = Sexp.nil 272 var key = Sexp.nil
260 var lessp = Sexp.nil 273 var lessp = Sexp.nil
@@ -274,6 +287,7 @@ extension Elisp {
274 case .string: throw Unsupported(what: "sort on a string") 287 case .string: throw Unsupported(what: "sort on a string")
275 default: items = try elements(args[0]) 288 default: items = try elements(args[0])
276 } 289 }
290 try refuseShared(lisp, "sort", args, variable: variable)
277 let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) } 291 let keyed = try items.map { isNil(key) ? ($0, $0) : ($0, try lisp.call(key, [$0])) }
278 func less(_ a: Sexp, _ b: Sexp) throws -> Bool { 292 func less(_ a: Sexp, _ b: Sexp) throws -> Bool {
279 isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b])) 293 isNil(lessp) ? try valueLess(a, b) : !isNil(try lisp.call(lessp, [a, b]))
Sources/OrgCore/Config/ElispRegex.swift +56 −44
@@ -1,9 +1,29 @@
1import Foundation 1import Foundation
2 2
3/// An Emacs regexp as an `NSRegularExpression`, with the syntax table of an Org buffer, where 3/// `char-syntax` of each ASCII character in a syntax table.
4/// table formulas and Emacs Lisp blocks run. A construct it can't translate exactly throws 4struct ElispSyntax: Equatable {
5/// `Elisp.Unsupported`, and so do subjects where ICU's tables could differ from Emacs's: 5 let classes: [Character]
6/// syntax classes against text past ASCII, and case folding with letters past ASCII. 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.
7struct ElispRegex { 27struct ElispRegex {
8 let pattern: String 28 let pattern: String
9 let groups: Int 29 let groups: Int
@@ -16,28 +36,18 @@ struct ElispRegex {
16 let plain: NSRegularExpression 36 let plain: NSRegularExpression
17 let folded: NSRegularExpression 37 let folded: NSRegularExpression
18 38
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
26 static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" } 39 static func hex(_ c: UInt32) -> String { "\\x{" + String(c, radix: 16) + "}" }
27 40
28 static func set(_ codes: [UInt32], negated: Bool = false) -> String { 41 static func set(_ codes: [UInt32], negated: Bool = false) -> String {
29 "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]" 42 "[" + (negated ? "^" : "") + codes.map(hex).joined() + "]"
30 } 43 }
31 44
32 static let word = codes("w")
33 static let symbol = word + codes("_")
34
35 /// A letter with case, which case folding changes. 45 /// A letter with case, which case folding changes.
36 static func isLetter(_ c: UInt32) -> Bool { 46 static func isLetter(_ c: UInt32) -> Bool {
37 (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false 47 (65...90).contains(c) || (97...122).contains(c) || c > 127 && Unicode.Scalar(c).map { $0.properties.changesWhenCaseMapped || $0.properties.changesWhenCaseFolded } ?? false
38 } 48 }
39 49
40 init(_ pattern: String) throws { 50 init(_ pattern: String, syntax: ElispSyntax = .org) throws {
41 self.pattern = pattern 51 self.pattern = pattern
42 let p = Array(pattern.unicodeScalars) 52 let p = Array(pattern.unicodeScalars)
43 var out = "" 53 var out = ""
@@ -137,12 +147,12 @@ struct ElispRegex {
137 case "cntrl": ("\\x{0}-\\x{1f}", false, false) 147 case "cntrl": ("\\x{0}-\\x{1f}", false, false)
138 case "ascii": ("\\x{0}-\\x{7f}", false, false) 148 case "ascii": ("\\x{0}-\\x{7f}", false, false)
139 case "nonascii": ("\\x{80}-\\x{10ffff}", false, false) 149 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)
141 case "blank": ("\\x{9}\\x{20}", true, false) 151 case "blank": ("\\x{9}\\x{20}", true, false)
142 case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false) 152 case "punct": ((33...126).filter { !Self.isLetter($0) && !(48...57).contains($0) }.map(Self.hex).joined(), true, false)
143 case "graph": ("\\x{21}-\\x{7e}", true, false) 153 case "graph": ("\\x{21}-\\x{7e}", true, false)
144 case "print": ("\\x{20}-\\x{7e}", true, false) 154 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)
146 default: throw unsupported("[:\(name):]") 156 default: throw unsupported("[:\(name):]")
147 } 157 }
148 text += ascii.0 158 text += ascii.0
@@ -215,7 +225,7 @@ struct ElispRegex {
215 atom("(?:\\\(n))") 225 atom("(?:\\\(n))")
216 case "w", "W": 226 case "w", "W":
217 asciiClasses = true 227 asciiClasses = true
218 atom(Self.set(Self.word, negated: e == "W")) 228 atom(Self.set(syntax.word, negated: e == "W"))
219 case "s", "S": 229 case "s", "S":
220 guard i < p.count else { throw unsupported("\\s") } 230 guard i < p.count else { throw unsupported("\\s") }
221 let code: Character = switch p[i] { 231 let code: Character = switch p[i] {
@@ -225,10 +235,11 @@ struct ElispRegex {
225 } 235 }
226 i += 1 236 i += 1
227 asciiClasses = true 237 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"))
229 case "b", "B", "<", ">": 240 case "b", "B", "<", ">":
230 asciiClasses = true 241 asciiClasses = true
231 let w = Self.set(Self.word) 242 let w = Self.set(syntax.word)
232 let text = switch e { 243 let text = switch e {
233 case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))" 244 case "b": "(?:(?<=\(w))(?!\(w))|(?<!\(w))(?=\(w)))"
234 case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))" 245 case "B": "(?:(?<=\(w))(?=\(w))|(?<!\(w))(?!\(w)))"
@@ -239,7 +250,7 @@ struct ElispRegex {
239 case "_": 250 case "_":
240 guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") } 251 guard i < p.count, p[i] == "<" || p[i] == ">" else { throw unsupported("\\_") }
241 asciiClasses = true 252 asciiClasses = true
242 let s = Self.set(Self.symbol) 253 let s = Self.set(syntax.symbol)
243 assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))") 254 assertion(p[i] == "<" ? "(?<!\(s))(?=\(s))" : "(?<=\(s))(?!\(s))")
244 i += 1 255 i += 1
245 case "`": 256 case "`":
@@ -312,7 +323,7 @@ extension Elisp {
312 323
313 func regex(_ pattern: String) throws -> ElispRegex { 324 func regex(_ pattern: String) throws -> ElispRegex {
314 if let cached = regexes[pattern] { return cached } 325 if let cached = regexes[pattern] { return cached }
315 let compiled = try ElispRegex(pattern) 326 let compiled = try ElispRegex(pattern, syntax: syntax)
316 regexes[pattern] = compiled 327 regexes[pattern] = compiled
317 return compiled 328 return compiled
318 } 329 }
@@ -350,6 +361,8 @@ extension Elisp {
350 switch chars.next() { 361 switch chars.next() {
351 case "&": text += try Self.substring(s, matchData[0]!) 362 case "&": text += try Self.substring(s, matchData[0]!)
352 case "\\": text += "\\" 363 case "\\": text += "\\"
364 // Kept as is, for `query-replace-regexp`.
365 case "?": text += "\\?"
353 case let d? where ("1"..."9").contains(d): 366 case let d? where ("1"..."9").contains(d):
354 let n = Int(d.value) - 48 367 let n = Int(d.value) - 48
355 if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) } 368 if n < matchData.count, let r = matchData[n] { text += try Self.substring(s, r) }
@@ -367,7 +380,7 @@ extension Elisp {
367 } 380 }
368 } else if !fixedCase { 381 } else if !fixedCase {
369 // How `replace-match` decides to change the replacement's case from the replaced text. 382 // 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
371 var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false) 384 var (multiletter, lower, nonUpperInitial, upper) = (false, false, false, false)
372 var previous: Unicode.Scalar = "\n" 385 var previous: Unicode.Scalar = "\n"
373 for c in old.unicodeScalars { 386 for c in old.unicodeScalars {
@@ -485,38 +498,37 @@ extension Elisp {
485 func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil } 498 func optional(_ i: Int) -> Sexp { i < args.count ? args[i] : .nil }
486 let s = try string(args[0]) 499 let s = try string(args[0])
487 let length = s.unicodeScalars.count 500 let length = s.unicodeScalars.count
488 let keepNulls = isNil(optional(1)) ? false : isNil(optional(2)) 501 let keepEmpty = !isNil(optional(1)) && isNil(optional(2))
489 let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1)) 502 let separators = isNil(optional(1)) ? "[ \u{0C}\t\n\r\u{0B}]+" : try string(optional(1))
490 let trim = isNil(optional(3)) ? nil : try string(optional(3)) 503 let trim = isNil(optional(3)) ? nil : try string(optional(3))
491 var list: [Sexp] = [] 504 var list: [Sexp] = []
492 func push(_ from: Int, _ to: Int) throws { 505 // The loop of Emacs 31's `split-string`, empty separator matches included.
493 var from = from 506 func push(_ item: String, last: Bool) throws {
494 if let trim, let data = try lisp.stringMatch(trim, s, start: .integer(from)) { 507 guard let trim else {
495 lisp.matchData = data 508 if !last || keepEmpty || !item.isEmpty { list.append(.string(item)) }
496 if data[0]!.lowerBound == from { from = data[0]!.upperBound } 509 return
497 } 510 }
498 guard keepNulls || from < to else { return } 511 let count = item.unicodeScalars.count
499 guard from <= to else { throw Signal(message: "Args out of range") } 512 var begin = 0
500 var this = try substring(s, from..<to) 513 if let data = try lisp.stringMatch("\\`\\(?:" + trim + "\\)", item) {
501 if let trim, let data = try lisp.stringMatch(trim + "\\'", this) {
502 lisp.matchData = data 514 lisp.matchData = data
503 if data[0]!.lowerBound < this.unicodeScalars.count { this = try substring(this, 0..<data[0]!.lowerBound) } 515 begin = data[0]!.upperBound
504 } 516 }
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)) }
506 } 520 }
521 var next = 0
507 var start = 0 522 var start = 0
508 var notFirst = false 523 while let data = try lisp.stringMatch(separators, s, start: .integer(next)) {
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 }
512 lisp.matchData = data 524 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
513 guard start < length else { break } 529 guard start < length else { break }
514 notFirst = true
515 let thisStart = start
516 start = data[0]!.upperBound
517 try push(thisStart, data[0]!.lowerBound)
518 } 530 }
519 try push(start, length) 531 try push(try substring(s, start..<length), last: true)
520 return Elisp.list(list) 532 return Elisp.list(list)
521 } 533 }
522 } 534 }
Sources/OrgCore/Config/ElispTime.swift +35 −12
@@ -75,12 +75,31 @@ extension Elisp {
75 return parts 75 return parts
76 } 76 }
77 77
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.
79 static func encode(_ parts: [Int], calendar: Calendar) throws -> Time { 84 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 { 85 let second = parts.count > 5 ? parts[5] : 0
81 throw Unsupported(what: "date \(parts)") 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)))
82 } 91 }
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)
84 } 103 }
85 104
86 /// `date-to-time` for ISO 8601 dates, with or without a time. 105 /// `date-to-time` for ISO 8601 dates, with or without a time.
@@ -94,17 +113,21 @@ extension Elisp {
94 } 113 }
95 114
96 static func days(_ seconds: Int, calendar: Calendar) -> Int { 115 static func days(_ seconds: Int, calendar: Calendar) -> Int {
97 Days.absolute(Date(timeIntervalSince1970: Double(seconds)), calendar: calendar) 116 civil(seconds, calendar: calendar).day
98 } 117 }
99 118
100 /// `format-time-string` with the conversions that don't depend on the locale, without 119 /// `format-time-string` with the conversions that don't depend on the locale, without
101 /// flags or widths. 120 /// flags or widths.
102 static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String { 121 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))) 122 let (absolute, secondOfDay) = civil(seconds, calendar: calendar)
104 let (year, month, day, hour, minute, second) = (c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!) 123 let (year, month, day) = Days.date(absolute)
124 let (hour, minute, second) = (secondOfDay / 3600, secondOfDay % 3600 / 60, secondOfDay % 60)
105 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] 125 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
106 let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 126 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
108 let hour12 = hour % 12 == 0 ? 12 : hour % 12 131 let hour12 = hour % 12 == 0 ? 12 : hour % 12
109 var out = "" 132 var out = ""
110 var chars = format.makeIterator() 133 var chars = format.makeIterator()
@@ -115,8 +138,8 @@ extension Elisp {
115 } 138 }
116 guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") } 139 guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") }
117 switch f { 140 switch f {
118 case "Y": out += String(year) 141 case "Y": out += yearText
119 case "y": out += String(format: "%02d", year % 100) 142 case "y": out += String(format: "%02d", shortYear)
120 case "m": out += String(format: "%02d", month) 143 case "m": out += String(format: "%02d", month)
121 case "d": out += String(format: "%02d", day) 144 case "d": out += String(format: "%02d", day)
122 case "e": out += String(format: "%2d", day) 145 case "e": out += String(format: "%2d", day)
@@ -134,8 +157,8 @@ extension Elisp {
134 case "u": out += String(weekday == 0 ? 7 : weekday) 157 case "u": out += String(weekday == 0 ? 7 : weekday)
135 case "w": out += String(weekday) 158 case "w": out += String(weekday)
136 case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0)) 159 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) 160 case "F": out += yearText + String(format: "-%02d-%02d", month, day)
138 case "D": out += String(format: "%02d/%02d/%02d", month, day, year % 100) 161 case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear)
139 case "R": out += String(format: "%02d:%02d", hour, minute) 162 case "R": out += String(format: "%02d:%02d", hour, minute)
140 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second) 163 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second)
141 case "s": out += String(seconds) 164 case "s": out += String(seconds)
Tests/OrgCoreTests/BabelTests.swift +41
@@ -292,6 +292,47 @@ struct BabelTests {
292 } 292 }
293 } 293 }
294 294
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
295 @Test func referencedQueryBlocksAskEveryTime() { 336 @Test func referencedQueryBlocksAskEveryTime() {
296 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" 337 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"
297 guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else { 338 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 {
93 #"(split-string "a1b22c" "[0-9]+")"#, #"(split-string " a b " " +")"#, #"(split-string "a,b,,c" "," t)"#, 93 #"(split-string "a1b22c" "[0-9]+")"#, #"(split-string " a b " " +")"#, #"(split-string "a,b,,c" "," t)"#,
94 #"(split-string " a , b " "," t " ")"#, #"(split-string "abc" "")"#, #"(split-string "abc" "" t)"#, #"(split-string "a-b_c" "\\W")"#, 94 #"(split-string " a , b " "," t " ")"#, #"(split-string "abc" "")"#, #"(split-string "abc" "" t)"#, #"(split-string "a-b_c" "\\W")"#,
95 #"(split-string "a,b" "," nil "\\s-*")"#, #"(split-string "a b" nil)"#, #"(split-string " two words " "[ ]+" t)"#, 95 #"(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))",
96 "(last '(1 2 3))", "(last '(1 2 3) 2)", "(last '(1 2 3) 0)", "(last '(1 2 . 3))", "(last nil)", "(butlast '(1 2 3))", 100 "(last '(1 2 3))", "(last '(1 2 3) 2)", "(last '(1 2 3) 0)", "(last '(1 2 . 3))", "(last nil)", "(butlast '(1 2 3))",
97 "(butlast '(1 2 3) 2)", "(butlast '(1 2 3) 0)", "(butlast nil)", "(butlast '(1 2 . 3))", #"(delete-dups (list 1 2 1 "a" "a"))"#, 101 "(butlast '(1 2 3) 2)", "(butlast '(1 2 3) 0)", "(butlast nil)", "(butlast '(1 2 . 3))", #"(delete-dups (list 1 2 1 "a" "a"))"#,
98 "(nreverse (list 1 2 3))", "(nreverse [1 2 3])", #"(nreverse "abc")"#, "(let ((l (list 1 2 3))) (nreverse l) l)", 102 "(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 {
132 "(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)", 136 "(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)",
133 "(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)))", 137 "(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)))",
134 "(when-let ((x 1)) x)", "(undefined-orgstar-macro (car 1))", "(undefined-orgstar-macro void-orgstar-variable)", 138 "(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 '<)))",
135 ] 144 ]
136 145
137 static func strict(_ form: String) -> String { 146 static func strict(_ form: String) -> String {
@@ -162,11 +171,19 @@ struct ElispTests {
162 #expect(Self.strict("(undefined-orgstar-function (car 1))") == "unsupported") 171 #expect(Self.strict("(undefined-orgstar-function (car 1))") == "unsupported")
163 } 172 }
164 173
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`.
166 @Test(.enabled(if: oracle)) 176 @Test(.enabled(if: oracle))
167 func syntaxTableMatchesOrgMode() throws { 177 func syntaxTablesMatchEmacs() throws {
168 let emacs = try EmacsOracle.evaluate("", "(list (let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r))))") 178 let classes = "(let (r) (dotimes (c 128) (push (string (char-syntax c)) r)) (apply #'concat (nreverse r)))"
169 #expect(emacs == [String(ElispRegex.syntax)]) 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))
170 } 187 }
171 188
172 static let timeForms = [ 189 static let timeForms = [
@@ -189,6 +206,12 @@ struct ElispTests {
189 #"(let ((s (format-time-string "%Y-%m-%d"))) (string-match "\\`[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\'" s))"#, 206 #"(let ((s (format-time-string "%Y-%m-%d"))) (string-match "\\`[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\'" s))"#,
190 "(let ((t0 (current-time))) (and (consp t0) (= (length t0) 4) (< (abs (- (float-time t0) (float-time))) 5)))", 207 "(let ((t0 (current-time))) (and (consp t0) (= (length t0) 4) (< (abs (- (float-time t0) (float-time))) 5)))",
191 "(> (time-to-days (current-time)) 739000)", 208 "(> (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")"#,
192 ] 215 ]
193 216
194 static let unsupportedTime = [ 217 static let unsupportedTime = [
docs/manual/guide/10-tables.org +4 −3
@@ -457,7 +457,7 @@ The evaluator supports:
457 =unless=, =cond=, =and=, =or=, =let=, =let*=, =setq=, =push=, =pop=, =while=, 457 =unless=, =cond=, =and=, =or=, =let=, =let*=, =setq=, =push=, =pop=, =while=,
458 =dolist=, =dotimes=, =with-output-to-string=, =ignore-errors=, =condition-case=, 458 =dolist=, =dotimes=, =with-output-to-string=, =ignore-errors=, =condition-case=,
459 =save-match-data=, =defun=, =defvar=, =defconst=, =let-alist=, =cl-incf= and =cl-decf= 459 =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;
461- =pcase= with literal, symbol, quoted, backquoted and =pred= patterns, where =pred= 461- =pcase= with literal, symbol, quoted, backquoted and =pred= patterns, where =pred=
462 takes a function name or a lambda; 462 takes a function name or a lambda;
463- =cl-loop= with =for VAR in LIST=, =for VAR from START to END=, and one kind of 463- =cl-loop= with =for VAR in LIST=, =for VAR from START to END=, and one kind of
@@ -473,7 +473,8 @@ The evaluator supports:
473 =append=, =length=, =reverse=, =number-sequence=, =memq=, =member=, =memql=, =assoc=, 473 =append=, =length=, =reverse=, =number-sequence=, =memq=, =member=, =memql=, =assoc=,
474 =assq=, =delq=, =delete=, =mapcar=, =mapc=, =mapconcat=, =funcall=, =apply=, 474 =assq=, =delq=, =delete=, =mapcar=, =mapc=, =mapconcat=, =funcall=, =apply=,
475 =identity=, =ignore=, =last=, =butlast=, =delete-dups=, =nreverse=, =sort= (both 475 =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=,
477 =cl-reduce= (with =:initial-value=), =cl-remove-if=, =cl-remove-if-not=, =cl-find= and 478 =cl-reduce= (with =:initial-value=), =cl-remove-if=, =cl-remove-if-not=, =cl-find= and
478 =cl-position= (with =:test=); 479 =cl-position= (with =:test=);
479- strings: =concat=, =format=, =format-message=, ~string=~, =string-equal=, =string<=, 480- strings: =concat=, =format=, =format-message=, ~string=~, =string-equal=, =string<=,
@@ -488,7 +489,7 @@ The evaluator supports:
488- time: =current-time=, =format-time-string=, =float-time=, =time-add=, =time-subtract=, 489- time: =current-time=, =format-time-string=, =float-time=, =time-add=, =time-subtract=,
489 =time-to-days=, =date-to-time=, =days-between=, =org-time-string-to-time=, 490 =time-to-days=, =date-to-time=, =days-between=, =org-time-string-to-time=,
490 =org-time-string-to-absolute= and the =calendar-= functions that diary sexps use, in 491 =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;
492- output and errors: =princ=, =prin1=, =print=, =terpri=, =message=, =error=, 493- output and errors: =princ=, =prin1=, =print=, =terpri=, =message=, =error=,
493 =user-error=; 494 =user-error=;
494- Org's lookup functions =org-lookup-first=, =org-lookup-last= and =org-lookup-all=. 495- 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
620 620
621On 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." 621On 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."
622 622
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.
624 624
625In 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." 625In 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."
626 626