Commit fa7dd01882

fa7dd01882a224af7e5797c7e8e1eaa9273d4c4f

parent: 47dd021371

Verified · cmc

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

Match Emacs in native Lisp: capitalize, closures, quoted lambdas, error data

capitalize follows the syntax table. Builtins refuse to look inside a
closure. A quoted lambda runs with dynamic binding under lexical binding.
condition-case binds the error symbol and data and matches specific
conditions. %F prints + for years past 9999. The reader reads \a, \b,
\d, \e, \f, \r, \v, \s and backslash-space as Emacs does.

Layout: unified · split

Sources/OrgApp/TableReason.swift +8
@@ -28,6 +28,8 @@ public enum TableReason {
28 let comment: StaticString = "Why a table needs Emacs: something a Lisp formula does" 28 let comment: StaticString = "Why a table needs Emacs: something a Lisp formula does"
29 switch what { 29 switch what {
30 case "integer size": return fixed(what) 30 case "integer size": return fixed(what)
31 case "a closure as a list": return String(localized: "a closure as a list", comment: comment)
32 case "capitalize past ASCII": return String(localized: "capitalize past ASCII", comment: comment)
31 case "case folding past ASCII": return String(localized: "case folding past ASCII", comment: comment) 33 case "case folding past ASCII": return String(localized: "case folding past ASCII", comment: comment)
32 case "cl-loop destructuring": return String(localized: "cl-loop destructuring", comment: comment) 34 case "cl-loop destructuring": return String(localized: "cl-loop destructuring", comment: comment)
33 case "cl-loop with collect and sum": return String(localized: "cl-loop with collect and sum", comment: comment) 35 case "cl-loop with collect and sum": return String(localized: "cl-loop with collect and sum", comment: comment)
@@ -42,6 +44,7 @@ public enum TableReason {
42 case "replace-regexp-in-string from the end": return String(localized: "replace-regexp-in-string from the end", comment: comment) 44 case "replace-regexp-in-string from the end": return String(localized: "replace-regexp-in-string from the end", comment: comment)
43 case "seq-uniq with a test": return String(localized: "seq-uniq with a test", comment: comment) 45 case "seq-uniq with a test": return String(localized: "seq-uniq with a test", comment: comment)
44 case "sort on a string": return String(localized: "sort on a string", comment: comment) 46 case "sort on a string": return String(localized: "sort on a string", comment: comment)
47 case "the data of this error": return String(localized: "the data of this error", comment: comment)
45 default: break 48 default: break
46 } 49 }
47 func value(_ prefix: String) -> String? { what.hasPrefix(prefix) ? String(what.dropFirst(prefix.count)) : nil } 50 func value(_ prefix: String) -> String? { what.hasPrefix(prefix) ? String(what.dropFirst(prefix.count)) : nil }
@@ -58,6 +61,7 @@ public enum TableReason {
58 if let zone = value("format-time-string zone ") { return String(localized: "format-time-string zone \(zone)", comment: comment) } 61 if let zone = value("format-time-string zone ") { return String(localized: "format-time-string zone \(zone)", comment: comment) }
59 if let code = value("format-time-string ") { return String(localized: "format-time-string \(code)", comment: comment) } 62 if let code = value("format-time-string ") { return String(localized: "format-time-string \(code)", comment: comment) }
60 if let clause = value("cl-loop ") { return String(localized: "cl-loop \(clause)", comment: comment) } 63 if let clause = value("cl-loop ") { return String(localized: "cl-loop \(clause)", comment: comment) }
64 if let names = value("condition-case on ") { return String(localized: "condition-case on \(names)", comment: comment) }
61 if let pattern = value("pcase pattern ") { return String(localized: "pcase pattern \(pattern)", comment: comment) } 65 if let pattern = value("pcase pattern ") { return String(localized: "pcase pattern \(pattern)", comment: comment) }
62 if let name = value("let-alist ") { return String(localized: "let-alist \(name)", comment: comment) } 66 if let name = value("let-alist ") { return String(localized: "let-alist \(name)", comment: comment) }
63 if let text = value("string-width of ") { return String(localized: "string-width of \(text)", comment: comment) } 67 if let text = value("string-width of ") { return String(localized: "string-width of \(text)", comment: comment) }
@@ -71,6 +75,10 @@ public enum TableReason {
71 let name = String(what.dropLast(" on a place".count)) 75 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") 76 return String(localized: "\(name) on a place", comment: "Why a table needs Emacs: a Lisp function used on a variable")
73 } 77 }
78 if what.hasSuffix(" on a closure") {
79 let name = String(what.dropLast(" on a closure".count))
80 return String(localized: "\(name) on a closure", comment: "Why a table needs Emacs: a Lisp function that looks inside a closure")
81 }
74 if what.hasSuffix(" on a list another value shares") { 82 if what.hasSuffix(" on a list another value shares") {
75 let name = String(what.dropLast(" on a list another value shares".count)) 83 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") 84 return String(localized: "\(name) on a list another value shares", comment: "Why a table needs Emacs: a Lisp function that changes a shared list")
Sources/OrgCore/Config/Elisp.swift +103 −21
@@ -11,9 +11,28 @@ public final class Elisp {
11 11
12 public struct Signal: Error, Equatable, CustomStringConvertible { 12 public struct Signal: Error, Equatable, CustomStringConvertible {
13 public let message: String 13 public let message: String
14 /// The error symbol, by default from the message, and its data when known: what
15 /// `condition-case` binds.
16 public let symbol: String?
17 public let data: [Sexp]?
14 public var description: String { message } 18 public var description: String { message }
19
20 public init(message: String, symbol: String? = nil, data: [Sexp]? = nil) {
21 self.message = message
22 self.symbol = symbol ?? Self.symbols.first(where: { message.hasPrefix($0.prefix) })?.symbol
23 self.data = data ?? (message == "Arithmetic error" ? [] : nil)
24 }
25
26 static let symbols: [(prefix: String, symbol: String)] = [
27 ("Arithmetic error", "arith-error"), ("Args out of range", "args-out-of-range"), ("Invalid function", "invalid-function"),
28 ("Symbol’s value as variable is void", "void-variable"), ("Wrong number of arguments", "wrong-number-of-arguments"),
29 ("Wrong type argument", "wrong-type-argument"),
30 ]
15 } 31 }
16 32
33 /// What `condition-case` binds its variable to for an error whose data isn't known.
34 static let unknownError = Sexp.symbol("\u{0}error")
35
17 public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp 36 public typealias Builtin = (Elisp, [Sexp]) throws -> Sexp
18 37
19 /// A set of bindings, shared by the closures created while it is in scope. 38 /// A set of bindings, shared by the closures created while it is in scope.
@@ -29,6 +48,11 @@ public final class Elisp {
29 public var lexical = false 48 public var lexical = false
30 /// Variables bound dynamically when `lexical` is set. 49 /// Variables bound dynamically when `lexical` is set.
31 var specials: Set<String> = [] 50 var specials: Set<String> = []
51 /// Under lexical binding, running a lambda list, which Emacs evaluates with dynamic binding:
52 /// every variable is bound dynamically and lambdas aren't closures.
53 private var dynamicOnly = false
54 /// The functions `defun` defined, which may take closures.
55 var defined: Set<String> = []
32 /// Each closure's captured frames, by the id in its `(closure ID ARGS . BODY)` value. 56 /// Each closure's captured frames, by the id in its `(closure ID ARGS . BODY)` value.
33 var closures: [[Frame]] = [] 57 var closures: [[Frame]] = []
34 /// The scopes of the callers of running closures, and the global values that dynamic 58 /// The scopes of the callers of running closures, and the global values that dynamic
@@ -78,8 +102,12 @@ public final class Elisp {
78 } 102 }
79 103
80 public func value(_ name: String) throws -> Sexp { 104 public func value(_ name: String) throws -> Sexp {
81 for scope in scopes.reversed() { if let v = scope.vars[name] { return v } } 105 for scope in scopes.reversed() {
82 throw Signal(message: "Symbol’s value as variable is void: \(name)") 106 guard let v = scope.vars[name] else { continue }
107 if v == Self.unknownError { throw Unsupported(what: "the data of this error") }
108 return v
109 }
110 throw Signal(message: "Symbol’s value as variable is void: \(name)", data: [.symbol(name)])
83 } 111 }
84 112
85 /// Evaluates `body` with `bindings` added: in a new frame, or for special variables under 113 /// Evaluates `body` with `bindings` added: in a new frame, or for special variables under
@@ -89,7 +117,7 @@ public final class Elisp {
89 } 117 }
90 118
91 func binding<T>(_ frame: Frame, _ body: () throws -> T) rethrows -> T { 119 func binding<T>(_ frame: Frame, _ body: () throws -> T) rethrows -> T {
92 let dynamic = lexical ? frame.vars.keys.filter(specials.contains) : [] 120 let dynamic = dynamicOnly ? Array(frame.vars.keys) : lexical ? frame.vars.keys.filter(specials.contains) : []
93 var saved: [(String, Sexp?)] = [] 121 var saved: [(String, Sexp?)] = []
94 for name in dynamic { 122 for name in dynamic {
95 saved.append((name, scopes[0].vars[name])) 123 saved.append((name, scopes[0].vars[name]))
@@ -118,7 +146,7 @@ public final class Elisp {
118 /// A lambda as `function` makes it: a closure over the local frames under lexical 146 /// A lambda as `function` makes it: a closure over the local frames under lexical
119 /// binding, else the list itself. 147 /// binding, else the list itself.
120 func closure(_ lambda: Sexp) -> Sexp { 148 func closure(_ lambda: Sexp) -> Sexp {
121 guard lexical, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda } 149 guard lexical, !dynamicOnly, case .list(let items) = lambda, items.first == .symbol("lambda"), items.count >= 2 else { return lambda }
122 closures.append(Array(scopes.dropFirst())) 150 closures.append(Array(scopes.dropFirst()))
123 return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst()) 151 return .list([.symbol("closure"), .integer(closures.count - 1)] + items.dropFirst())
124 } 152 }
@@ -128,6 +156,29 @@ public final class Elisp {
128 return false 156 return false
129 } 157 }
130 158
159 /// Builtins that may take closures as arguments, from the given position on: those that
160 /// call them or only hold them. Emacs's closures aren't lists, as they are here.
161 static let closureArguments: [String: Int] = [
162 "funcall": 0, "apply": 0, "mapcar": 0, "mapc": 0, "mapconcat": 0, "seq-map": 0, "seq-filter": 0, "seq-remove": 0,
163 "seq-reduce": 0, "cl-reduce": 0, "cl-remove-if": 0, "cl-remove-if-not": 0, "cl-find": 1, "cl-position": 1, "sort": 0,
164 "replace-regexp-in-string": 1, "list": 0, "identity": 0, "ignore": 0, "null": 0, "not": 0,
165 ]
166 /// Builtins that compare or print what lists hold.
167 static let closureInspectors: Set<String> = [
168 "equal", "eq", "eql", "member", "memq", "memql", "assoc", "assq", "delete", "delq", "delete-dups", "seq-uniq",
169 "format", "format-message", "message", "error", "user-error", "prin1-to-string", "princ", "prin1", "print",
170 ]
171
172 /// Refuses a builtin call that would look inside a closure.
173 func refuseClosures(_ name: String, _ args: [Sexp]) throws {
174 guard !closures.isEmpty, !defined.contains(name) else { return }
175 for (i, arg) in args.enumerated() {
176 if Self.isClosure(arg) ? i < Self.closureArguments[name] ?? .max : Self.closureInspectors.contains(name) && Self.containsClosure(arg) {
177 throw Unsupported(what: "\(name) on a closure")
178 }
179 }
180 }
181
131 /// Whether `v` contains a closure, which Emacs prints in a form this evaluator doesn't. 182 /// Whether `v` contains a closure, which Emacs prints in a form this evaluator doesn't.
132 static func containsClosure(_ v: Sexp) -> Bool { 183 static func containsClosure(_ v: Sexp) -> Bool {
133 switch v { 184 switch v {
@@ -199,25 +250,28 @@ public final class Elisp {
199 } 250 }
200 251
201 static func car(_ v: Sexp) throws -> Sexp { 252 static func car(_ v: Sexp) throws -> Sexp {
202 switch v { 253 if isClosure(v) { throw Unsupported(what: "car on a closure") }
254 return switch v {
203 case .list(let items): items.first ?? .nil 255 case .list(let items): items.first ?? .nil
204 case .dotted(let items, _): items[0] 256 case .dotted(let items, _): items[0]
205 case _ where isNil(v): .nil 257 case _ where isNil(v): .nil
206 default: throw Signal(message: "Wrong type argument: listp, \(v.description)") 258 default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v])
207 } 259 }
208 } 260 }
209 261
210 static func cdr(_ v: Sexp) throws -> Sexp { 262 static func cdr(_ v: Sexp) throws -> Sexp {
211 switch v { 263 if isClosure(v) { throw Unsupported(what: "cdr on a closure") }
264 return switch v {
212 case .list(let items): list(Array(items.dropFirst())) 265 case .list(let items): list(Array(items.dropFirst()))
213 case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last) 266 case .dotted(let items, let last): items.count == 1 ? last : .dotted(Array(items.dropFirst()), last)
214 case _ where isNil(v): .nil 267 case _ where isNil(v): .nil
215 default: throw Signal(message: "Wrong type argument: listp, \(v.description)") 268 default: throw Signal(message: "Wrong type argument: listp, \(v.description)", data: [.symbol("listp"), v])
216 } 269 }
217 } 270 }
218 271
219 /// A proper list's elements. 272 /// A proper list's elements.
220 static func elements(_ v: Sexp) throws -> [Sexp] { 273 static func elements(_ v: Sexp) throws -> [Sexp] {
274 if isClosure(v) { throw Unsupported(what: "a closure as a list") }
221 if case .list(let items) = v { return items } 275 if case .list(let items) = v { return items }
222 if isNil(v) { return [] } 276 if isNil(v) { return [] }
223 throw Signal(message: "Wrong type argument: listp, \(v.description)") 277 throw Signal(message: "Wrong type argument: listp, \(v.description)")
@@ -328,6 +382,7 @@ public final class Elisp {
328 defer { pending.removeLast() } 382 defer { pending.removeLast() }
329 for arg in args { pending[pending.count - 1].append(try eval(arg)) } 383 for arg in args { pending[pending.count - 1].append(try eval(arg)) }
330 let values = pending[pending.count - 1] 384 let values = pending[pending.count - 1]
385 try refuseClosures(name, values)
331 var variable: String? 386 var variable: String?
332 if case .symbol(let s)? = args.first, s != "nil", s != "t", !s.hasPrefix(":") { variable = s } 387 if case .symbol(let s)? = args.first, s != "nil", s != "t", !s.hasPrefix(":") { variable = s }
333 inPlaceVariable = variable 388 inPlaceVariable = variable
@@ -440,6 +495,7 @@ public final class Elisp {
440 assign(variable, try Self.cdr(list)) 495 assign(variable, try Self.cdr(list))
441 return try Self.car(list) 496 return try Self.car(list)
442 } 497 }
498 if Self.isClosure(list) { throw Unsupported(what: "push on a closure") }
443 let pushed = Self.cons(try eval(args[0]), list) 499 let pushed = Self.cons(try eval(args[0]), list)
444 assign(variable, pushed) 500 assign(variable, pushed)
445 return pushed 501 return pushed
@@ -481,12 +537,20 @@ public final class Elisp {
481 do { 537 do {
482 return try eval(args[1]) 538 return try eval(args[1])
483 } catch let signal as Signal { 539 } catch let signal as Signal {
540 // Every error has the `error` condition as well as its own.
541 let conditions = ["error", "t"] + (signal.symbol.map { [$0] } ?? [])
484 for handler in args.dropFirst(2) { 542 for handler in args.dropFirst(2) {
485 let parts = try Self.elements(handler) 543 let parts = try Self.elements(handler)
486 guard let condition = parts.first else { continue } 544 guard let condition = parts.first else { continue }
487 let names = (try? Self.elements(condition)) ?? [condition] 545 let names = ((try? Self.elements(condition)) ?? [condition]).compactMap(\.symbol)
488 guard names.contains(.symbol("error")) || names.contains(.symbol("t")) else { continue } 546 guard names.contains(where: conditions.contains) else {
489 let bindings: [String: Sexp] = args[0].symbol.map { $0 == "nil" ? [:] : [$0: .list([.symbol("error"), .string(signal.message)])] } ?? [:] 547 if signal.symbol == nil, !names.isEmpty { throw Unsupported(what: "condition-case on \(names.joined(separator: " "))") }
548 continue
549 }
550 var bindings: [String: Sexp] = [:]
551 if let variable = args[0].symbol, variable != "nil" {
552 bindings[variable] = signal.symbol.flatMap { symbol in signal.data.map { .list([.symbol(symbol)] + $0) } } ?? Self.unknownError
553 }
490 return try binding(bindings) { try progn(parts.dropFirst()) } 554 return try binding(bindings) { try progn(parts.dropFirst()) }
491 } 555 }
492 throw signal 556 throw signal
@@ -501,10 +565,19 @@ public final class Elisp {
501 switch function { 565 switch function {
502 case .symbol(let name): return try callNamed(name, args) 566 case .symbol(let name): return try callNamed(name, args)
503 case .list(let items) where Self.isClosure(function): 567 case .list(let items) where Self.isClosure(function):
568 guard closures.indices.contains(items[1].integer!) else { throw Unsupported(what: "a closure as a list") }
569 let saved = dynamicOnly
570 dynamicOnly = false
571 defer { dynamicOnly = saved }
504 return try apply(parameters: items[2], body: items.dropFirst(3), args, scope: closures[items[1].integer!]) 572 return try apply(parameters: items[2], body: items.dropFirst(3), args, scope: closures[items[1].integer!])
505 case .list(let items) where items.first == .symbol("lambda") && items.count >= 2: 573 case .list(let items) where items.first == .symbol("lambda") && items.count >= 2:
506 // Under lexical binding, a lambda list runs outside the caller's local frames. 574 guard lexical else { return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: nil) }
507 return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: lexical ? [] : nil) 575 // Under lexical binding, a lambda list runs outside the caller's local frames, with
576 // dynamic binding.
577 let saved = dynamicOnly
578 dynamicOnly = true
579 defer { dynamicOnly = saved }
580 return try apply(parameters: items[1], body: items.dropFirst(2), args, scope: [])
508 default: 581 default:
509 throw Signal(message: "Invalid function: \(function.description)") 582 throw Signal(message: "Invalid function: \(function.description)")
510 } 583 }
@@ -548,6 +621,7 @@ public final class Elisp {
548 621
549 func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp { 622 func callNamed(_ name: String, _ args: [Sexp]) throws -> Sexp {
550 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") } 623 guard let function = functions[name] else { throw Unsupported(what: "function \(name)") }
624 try refuseClosures(name, args)
551 inPlaceVariable = nil 625 inPlaceVariable = nil
552 return try function(self, args) 626 return try function(self, args)
553 } 627 }
@@ -831,12 +905,11 @@ public final class Elisp {
831 try arity(args, 2...2, "delete") 905 try arity(args, 2...2, "delete")
832 return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) }) 906 return list(try elements(args[1]).filter { normalized($0) != normalized(args[0]) })
833 } 907 }
834 lisp.define("error") { _, args in 908 for name in ["error", "user-error"] {
835 let message = args.isEmpty ? "" : try format(args) 909 lisp.define(name) { _, args in
836 throw Signal(message: message) 910 let message = args.isEmpty ? "" : try format(args)
837 } 911 throw Signal(message: message, symbol: name, data: [.string(message)])
838 lisp.define("user-error") { _, args in 912 }
839 throw Signal(message: args.isEmpty ? "" : try format(args))
840 } 913 }
841 914
842 // Printing. 915 // Printing.
@@ -890,9 +963,18 @@ public final class Elisp {
890 if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).lowercased().unicodeScalars.first!.value)) } 963 if case .integer(let c) = args[0] { return .integer(Int(String(try scalar(c)).lowercased().unicodeScalars.first!.value)) }
891 return .string(try string(args[0]).lowercased()) 964 return .string(try string(args[0]).lowercased())
892 } 965 }
893 lisp.define("capitalize") { _, args in 966 // A letter is upcased after a character without word syntax, downcased after one with it.
967 lisp.define("capitalize") { lisp, args in
894 try arity(args, 1...1, "capitalize") 968 try arity(args, 1...1, "capitalize")
895 return .string(try string(args[0]).capitalized) 969 let s = try string(args[0])
970 guard s.unicodeScalars.allSatisfy(\.isASCII) else { throw Unsupported(what: "capitalize past ASCII") }
971 var inWord = false
972 var out = ""
973 for c in s.unicodeScalars {
974 out += inWord ? String(c).lowercased() : String(c).uppercased()
975 inWord = lisp.syntax.isWord(c)
976 }
977 return .string(out)
896 } 978 }
897 lisp.define("substring") { _, args in 979 lisp.define("substring") { _, args in
898 try arity(args, 1...3, "substring") 980 try arity(args, 1...3, "substring")
Sources/OrgCore/Config/ElispForms.swift +1
@@ -28,6 +28,7 @@ extension Elisp {
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 function = closure(.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(function, values) } 30 define(name) { lisp, values in try lisp.call(function, values) }
31 defined.insert(name)
31 return .symbol(name) 32 return .symbol(name)
32 } 33 }
33 34
Sources/OrgCore/Config/ElispTime.swift +1 −1
@@ -157,7 +157,7 @@ extension Elisp {
157 case "u": out += String(weekday == 0 ? 7 : weekday) 157 case "u": out += String(weekday == 0 ? 7 : weekday)
158 case "w": out += String(weekday) 158 case "w": out += String(weekday)
159 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))
160 case "F": out += yearText + String(format: "-%02d-%02d", month, day) 160 case "F": out += (year > 9999 ? "+" : "") + yearText + String(format: "-%02d-%02d", month, day)
161 case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear) 161 case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear)
162 case "R": out += String(format: "%02d:%02d", hour, minute) 162 case "R": out += String(format: "%02d:%02d", hour, minute)
163 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second) 163 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second)
Sources/OrgCore/Config/Lisp.swift +6 −8
@@ -115,6 +115,9 @@ public enum LispReader {
115 115
116 func error(_ message: String) -> ReadError { ReadError(line: line, message: message) } 116 func error(_ message: String) -> ReadError { ReadError(line: line, message: message) }
117 117
118 /// What `\a` and the other one-letter escapes in strings and characters stand for.
119 static let escapes: [Unicode.Scalar: Unicode.Scalar] = ["a": "\u{7}", "b": "\u{8}", "d": "\u{7F}", "e": "\u{1B}", "f": "\u{C}", "n": "\n", "r": "\r", "s": " ", "t": "\t", "v": "\u{B}"]
120
118 static let delimiters: Set<Unicode.Scalar> = ["(", ")", "[", "]", "\"", "'", "`", ",", ";"] 121 static let delimiters: Set<Unicode.Scalar> = ["(", ")", "[", "]", "\"", "'", "`", ",", ";"]
119 122
120 mutating func form() throws -> Sexp { 123 mutating func form() throws -> Sexp {
@@ -177,10 +180,8 @@ public enum LispReader {
177 case "\\": 180 case "\\":
178 guard let e = next() else { break } 181 guard let e = next() else { break }
179 switch e { 182 switch e {
180 case "n": out += "\n" 183 case "\n", " ": break
181 case "t": out += "\t" 184 default: out.unicodeScalars.append(Self.escapes[e] ?? e)
182 case "\n": break
183 default: out.unicodeScalars.append(e)
184 } 185 }
185 default: 186 default:
186 out.unicodeScalars.append(c) 187 out.unicodeScalars.append(c)
@@ -194,10 +195,7 @@ public enum LispReader {
194 guard c == "\\" else { return Int(c.value) } 195 guard c == "\\" else { return Int(c.value) }
195 guard let e = next() else { throw error("bad character") } 196 guard let e = next() else { throw error("bad character") }
196 switch e { 197 switch e {
197 case "n": return 10 198 case _ where Self.escapes[e] != nil: return Int(Self.escapes[e]!.value)
198 case "t": return 9
199 case "s": return 32
200 case "e": return 27
201 case "C", "M", "S", "H", "A": 199 case "C", "M", "S", "H", "A":
202 if peek == "-" { _ = next(); return try character() } 200 if peek == "-" { _ = next(); return try character() }
203 return Int(e.value) 201 return Int(e.value)
Tests/OrgCoreTests/BabelTests.swift +23
@@ -310,6 +310,14 @@ struct BabelTests {
310 "(let ((x 1)) (funcall '(lambda () x)))", 310 "(let ((x 1)) (funcall '(lambda () x)))",
311 "(let ((x 3)) (mapcar (lambda (y) (* x y)) '(1 2)))", 311 "(let ((x 3)) (mapcar (lambda (y) (* x y)) '(1 2)))",
312 "(let ((k 1)) (pcase 2 ((pred (lambda (v) (> v k))) 'big)))", 312 "(let ((k 1)) (pcase 2 ((pred (lambda (v) (> v k))) 'big)))",
313 "(list (capitalize \"it's o'neil\") (capitalize \"o'neil x_y 3d\"))",
314 "(progn (defun h () y) (funcall '(lambda (y) (h)) 3))",
315 "(progn (defun h3 () zz) (mapcar '(lambda (zz) (h3)) '(1 2)))",
316 "(progn (defun h2 () yy) (let ((f '(lambda (yy) (h2)))) (funcall f 8)))",
317 "(progn (defun h4 () w) (funcall '(lambda () (let ((w 4)) (h4)))))",
318 "(let ((x 2)) (funcall '(lambda (f) (funcall f)) (lambda () x)))",
319 "(let ((f (lambda (x) (* 2 x)))) (list (funcall f 2) (apply f '(3)) (car (list 5 f)) (length (list f f))))",
320 "(let ((x 1)) (condition-case err (car x) (error (funcall (lambda () (list x (car err)))))))",
313 ].map { "#+begin_src emacs-lisp\n\($0)\n#+end_src\n" } 321 ].map { "#+begin_src emacs-lisp\n\($0)\n#+end_src\n" }
314 322
315 /// Natively as with `emacs -Q --batch -l`, the way the app runs Emacs Lisp blocks. 323 /// Natively as with `emacs -Q --batch -l`, the way the app runs Emacs Lisp blocks.
@@ -333,6 +341,21 @@ struct BabelTests {
333 } 341 }
334 } 342 }
335 343
344 /// Emacs's closures aren't lists: blocks that look inside one are refused.
345 @Test func refusesLookingInsideClosures() throws {
346 let folder = FileManager.default.temporaryDirectory
347 for form in [
348 "(listp (lambda () 1))", "(let ((f (lambda () 1))) (consp f))", "(car (lambda () 1))", "(equal (lambda () 1) (lambda () 1))",
349 "(functionp (lambda () 1))", "(let ((f (lambda () 1))) (eq f f))", "(let ((f (lambda () 1))) (length f))",
350 "(let ((f (lambda () 1))) (dolist (x f) x))", "(let ((f (lambda () 1))) (push 1 f) (length f))",
351 "(let ((f (lambda () 1))) (format \"%S\" (list f)))", "(let ((f (lambda () 1))) (and (memq f (list f)) t))",
352 "(funcall '(closure 99 () 1))",
353 ] {
354 let text = "#+begin_src emacs-lisp\n\(form)\n#+end_src\n"
355 #expect(throws: NativeUnsupported.self, "\(form)") { try TestBabelRunner.execute(text, caret: 2, directory: folder, native: true) }
356 }
357 }
358
336 @Test func referencedQueryBlocksAskEveryTime() { 359 @Test func referencedQueryBlocksAskEveryTime() {
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" 360 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"
338 guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else { 361 guard case .success(let job) = Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])) else {
Tests/OrgCoreTests/ElispTests.swift +10 −1
@@ -25,6 +25,12 @@ struct ElispTests {
25 "(string-prefix-p \"ab\" \"abc\")", "(condition-case nil (/ 1 0) (error 'caught))", "(ignore-errors (car 1))", "(car 1)", 25 "(string-prefix-p \"ab\" \"abc\")", "(condition-case nil (/ 1 0) (error 'caught))", "(ignore-errors (car 1))", "(car 1)",
26 "(let ((x 0)) (while (< x 5) (setq x (1+ x))) x)", "(elt [1 2 3] 1)", "(aref \"abc\" 1)", "(length [1 2])", "(nthcdr 1 '(1 2 3))", 26 "(let ((x 0)) (while (< x 5) (setq x (1+ x))) x)", "(elt [1 2 3] 1)", "(aref \"abc\" 1)", "(length [1 2])", "(nthcdr 1 '(1 2 3))",
27 "(delq nil '(1 nil 2))", "(cadr '(1 2 3))", "(identity \"x\")", "(capitalize \"hello world\")", "(string-trim \" x \")", 27 "(delq nil '(1 nil 2))", "(cadr '(1 2 3))", "(identity \"x\")", "(capitalize \"hello world\")", "(string-trim \" x \")",
28 "(capitalize \"it's o'neil x_y 3d foo-bar\")",
29 #"(aref "\f" 0)"#, #"(string-match "\\s-" "\f")"#, #"(append "\a\b\d\e\f\n\r\s\t\v\ x" nil)"#, #"(list ?\a ?\b ?\d ?\e ?\f ?\r ?\s ?\v)"#,
30 "(condition-case err (car 1) (error (car err)))", "(condition-case err (cdr 'a) (error err))", "(condition-case err (/ 1 0) (arith-error err))",
31 "(condition-case err void-orgstar-variable (void-variable err))", "(condition-case nil (car 1) (wrong-type-argument 'w) (error 'e))",
32 "(condition-case nil (car 1) (arith-error 'a))", #"(condition-case err (error "e %d" 1) (error err))"#,
33 #"(condition-case err (user-error "u") (user-error err))"#, "(condition-case nil (aref [1] 5) (args-out-of-range 'r))",
28 ] 34 ]
29 35
30 static func ours(_ form: String) -> String { 36 static func ours(_ form: String) -> String {
@@ -141,6 +147,9 @@ struct ElispTests {
141 "(let* ((a (list 3 1 2)) (b (list a))) (sort a '<) b)", "(let* ((a (list 1 2 3)) (b a)) (nreverse a) b)", 147 "(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 '<)))", 148 "(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 '<)))", 149 "(let* ((a (list 3 1 2)) (b a)) (funcall #'sort a '<) b)", "(let ((a (list 3 1 2))) (prog1 a (sort a '<)))",
150 // Errors whose data, or whose symbol, isn't known here.
151 "(condition-case err (aref [1] 5) (error err))", "(condition-case nil (number-sequence 1 2 0) (wrong-type-argument 1))",
152 #"(capitalize "café")"#,
144 ] 153 ]
145 154
146 static func strict(_ form: String) -> String { 155 static func strict(_ form: String) -> String {
@@ -211,7 +220,7 @@ struct ElispTests {
211 #"(format-time-string "%F %a" (date-to-time "1500-01-01"))"#, #"(format-time-string "%F" -15000000000)"#, 220 #"(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)"#, 221 #"(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"))"#, 222 #"(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")"#, 223 #"(days-between "1500-01-01" "1600-01-01")"#, #"(format-time-string "%Y %F" 300000000000 t)"#,
215 ] 224 ]
216 225
217 static let unsupportedTime = [ 226 static let unsupportedTime = [
docs/manual/guide/10-tables.org +7 −1
@@ -498,7 +498,13 @@ Regular expressions use Emacs's syntax and the syntax table of an Org buffer, an
498=case-fold-search= is on unless the formula binds it to =nil=. These need Emacs: 498=case-fold-search= is on unless the formula binds it to =nil=. These need Emacs:
499numbered groups =\\(?N:=, categories =\\c=, syntax classes and character classes 499numbered groups =\\(?N:=, categories =\\c=, syntax classes and character classes
500such as =\\w=, =\\b= or =[[:alpha:]]= against text with characters past ASCII, 500such as =\\w=, =\\b= or =[[:alpha:]]= against text with characters past ASCII,
501and case folding of a letter past ASCII. =format-time-string= takes =%Y=, =%y=, =%m=, 501and case folding of a letter past ASCII, including =capitalize=. =condition-case=
502binds its variable to the error symbol and data, such as =(wrong-type-argument listp 1)=;
503reading that variable for an error whose data orgstar doesn't know, such as
504=args-out-of-range=, needs Emacs, as does a handler that names a specific condition
505when the error isn't one of =wrong-type-argument=, =args-out-of-range=, =arith-error=,
506=void-variable=, =invalid-function=, =wrong-number-of-arguments=, =error= and
507=user-error=. =format-time-string= takes =%Y=, =%y=, =%m=,
502=%d=, =%e=, =%H=, =%k=, =%I=, =%l=, =%M=, =%S=, =%p=, =%a=, =%A=, =%b=, =%h=, =%B=, =%u=, 508=%d=, =%e=, =%H=, =%k=, =%I=, =%l=, =%M=, =%S=, =%p=, =%a=, =%A=, =%b=, =%h=, =%B=, =%u=,
503=%w=, =%j=, =%F=, =%D=, =%R=, =%T=, =%s=, =%z=, =%n=, =%t= and =%%=, without flags or 509=%w=, =%j=, =%F=, =%D=, =%R=, =%T=, =%s=, =%z=, =%n=, =%t= and =%%=, without flags or
504widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as 510widths; other codes need Emacs, as do float times in =time-add= and =time-subtract=. =date-to-time= and =days-between= read dates as
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=. 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. 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 and =capitalize=. A quoted lambda, ='(lambda ...)=, runs with dynamic binding, as in Emacs. A closure can be called, stored and passed to functions such as =mapcar=; a block that takes one apart as a list, compares it or prints it needs Emacs. 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