Capture: %(…) through the Lisp subset !250

merged merged by cmc on 2026-10-11 08:27 UTC · krz/orgstar:capture-embedded-lisp into main

4 files changed, +233 −29

Layout: unified · split

Sources/OrgCore/Capture/Capture.swift +72 −28
@@ -182,8 +182,10 @@ public enum Capture {
182 182
183 /// The questions `template` asks, in order. 183 /// The questions `template` asks, in order.
184 public static func questions(_ template: String, context: CaptureContext = CaptureContext()) -> [Question] { 184 public static func questions(_ template: String, context: CaptureContext = CaptureContext()) -> [Question] {
185 guard case .success(let expanded) = expand(template, context) else { return [] } 185 let embedded = Embedded(context, answers: [])
186 return prompts(in: expanded).map { question($0.items, $0.key, context) } 186 guard case .success(let expanded) = expand(template, context, embedded: embedded) else { return [] }
187 // `read-string` in `%(…)` asks first, as Org evaluates those before the prompts.
188 return embedded.questions + prompts(in: expanded).map { question($0.items, $0.key, context) }
187 } 189 }
188 190
189 static func question(_ items: [String]?, _ key: String?, _ context: CaptureContext) -> Question { 191 static func question(_ items: [String]?, _ key: String?, _ context: CaptureContext) -> Question {
@@ -228,10 +230,12 @@ public enum Capture {
228 /// the replies to `questions(template)` in order. 230 /// the replies to `questions(template)` in order.
229 public static func fill(_ template: String, context: CaptureContext, answers: [String] = []) -> Result<(text: String, cursor: Int), Failure> { 231 public static func fill(_ template: String, context: CaptureContext, answers: [String] = []) -> Result<(text: String, cursor: Int), Failure> {
230 let expanded: String 232 let expanded: String
231 switch expand(template, context) { 233 let embedded = Embedded(context, answers: answers)
234 switch expand(template, context, embedded: embedded) {
232 case .failure(let failure): return .failure(failure) 235 case .failure(let failure): return .failure(failure)
233 case .success(let text): expanded = text 236 case .success(let text): expanded = text
234 } 237 }
238 let answers = Array(answers.dropFirst(embedded.used))
235 // Prompts, in order, answered in the text as it stands then, as org does. 239 // Prompts, in order, answered in the text as it stands then, as org does.
236 var options = EditingOptions.org 240 var options = EditingOptions.org
237 options.tagsColumn = context.tagsColumn 241 options.tagsColumn = context.tagsColumn
@@ -352,10 +356,11 @@ public enum Capture {
352 return buffer.string 356 return buffer.string
353 } 357 }
354 358
355 /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…), with `%^` prompts and `%\N` 359 /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…) and then `%(…)`, with `%^`
356 /// left in place. 360 /// prompts and `%\N` left in place. `embedded` evaluates `%(…)`.
357 static func expand(_ template: String, _ context: CaptureContext) -> Result<String, Failure> { 361 static func expand(_ template: String, _ context: CaptureContext, embedded: Embedded? = nil) -> Result<String, Failure> {
358 let template = insertFiles(template, context) 362 let template = insertFiles(template, context)
363 let embedded = embedded ?? Embedded(context, answers: [])
359 func stamp(_ active: Bool, _ withTime: Bool) -> String { 364 func stamp(_ active: Bool, _ withTime: Bool) -> String {
360 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now) 365 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
361 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1] 366 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
@@ -370,8 +375,19 @@ public enum Capture {
370 } 375 }
371 var text = "" 376 var text = ""
372 let chars = Array(template) 377 let chars = Array(template)
378 let sexps = embeddedSexps(chars)
379 // Where the `%(…)` forms being copied end; values put inside one are escaped as in a
380 // Lisp string.
381 var sexpEnds: [Int] = []
382 func put(_ value: String) {
383 text += sexpEnds.isEmpty ? value : value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
384 }
373 var i = 0 385 var i = 0
374 while i < chars.count { 386 while i < chars.count {
387 while sexpEnds.last == i {
388 text += Self.sexpEndMark
389 sexpEnds.removeLast()
390 }
375 let c = chars[i] 391 let c = chars[i]
376 guard c == "%", i + 1 < chars.count else { 392 guard c == "%", i + 1 < chars.count else {
377 text.append(c) 393 text.append(c)
@@ -382,7 +398,7 @@ public enum Capture {
382 var slashes = 0 398 var slashes = 0
383 while slashes < text.count, text.dropLast(slashes).last == "\\" { slashes += 1 } 399 while slashes < text.count, text.dropLast(slashes).last == "\\" { slashes += 1 }
384 let next = chars[i + 1] 400 let next = chars[i + 1]
385 if slashes > 0, "aAcfFikKlLntTuUx:<?".contains(next) { 401 if slashes > 0, "aAcfFikKlLntTuUx:<?(".contains(next) {
386 text.removeLast((slashes + 1) / 2) 402 text.removeLast((slashes + 1) / 2)
387 if slashes % 2 == 1 { 403 if slashes % 2 == 1 {
388 text.append(c) 404 text.append(c)
@@ -394,37 +410,41 @@ public enum Capture {
394 switch next { 410 switch next {
395 case "?": text += cursorMark 411 case "?": text += cursorMark
396 case "i": 412 case "i":
413 if !sexpEnds.isEmpty {
414 put(context.initial)
415 break
416 }
397 // Continuation lines keep the indentation of the line `%i` is on. 417 // Continuation lines keep the indentation of the line `%i` is on.
398 let lead = String(text.split(separator: "\n", omittingEmptySubsequences: false).last ?? "").prefix { $0 == " " || $0 == "\t" } 418 let lead = String(text.split(separator: "\n", omittingEmptySubsequences: false).last ?? "").prefix { $0 == " " || $0 == "\t" }
399 text += context.initial.replacingOccurrences(of: "\n", with: "\n" + lead) 419 text += context.initial.replacingOccurrences(of: "\n", with: "\n" + lead)
400 case "a": text += context.annotation == "[[]]" ? "" : context.annotation 420 case "a": put(context.annotation == "[[]]" ? "" : context.annotation)
401 case "A": 421 case "A":
402 // The link, with its description asked for. 422 // The link, with its description asked for.
403 let ns = context.annotation as NSString 423 let ns = context.annotation as NSString
404 if let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) { 424 if let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) {
405 text += ns.replacingCharacters(in: m.range, with: "[[" + ns.substring(with: m.range(at: 1)) + "][%^{Link description}]]") 425 put(ns.replacingCharacters(in: m.range, with: "[[" + ns.substring(with: m.range(at: 1)) + "][%^{Link description}]]"))
406 } else { 426 } else {
407 text += context.annotation 427 put(context.annotation)
408 } 428 }
409 case "l": text += linkForm("[[$1]]") 429 case "l": put(linkForm("[[$1]]"))
410 case "L": text += linkForm("$1") 430 case "L": put(linkForm("$1"))
411 case "c", "x": text += context.clipboard 431 case "c", "x": put(context.clipboard)
412 case "f": text += (context.file as NSString).lastPathComponent 432 case "f": put((context.file as NSString).lastPathComponent)
413 case "F": text += context.file 433 case "F": put(context.file)
414 case "n": text += context.userName 434 case "n": put(context.userName)
415 case "k": text += context.clockHeading 435 case "k": put(context.clockHeading)
416 case "K": text += context.clockLink 436 case "K": put(context.clockLink)
417 case "t": text += stamp(true, false) 437 case "t": put(stamp(true, false))
418 case "T": text += stamp(true, true) 438 case "T": put(stamp(true, true))
419 case "u": text += stamp(false, false) 439 case "u": put(stamp(false, false))
420 case "U": text += stamp(false, true) 440 case "U": put(stamp(false, true))
421 case "<": 441 case "<":
422 guard let close = chars[(i + 2)...].firstIndex(of: ">"), !chars[(i + 2)..<close].contains("\n") else { 442 guard let close = chars[(i + 2)...].firstIndex(of: ">"), !chars[(i + 2)..<close].contains("\n") else {
423 text.append(c) 443 text.append(c)
424 consumed = 1 444 consumed = 1
425 break 445 break
426 } 446 }
427 text += strftime(String(chars[(i + 2)..<close]), context) 447 put(strftime(String(chars[(i + 2)..<close]), context))
428 consumed = close - i + 1 448 consumed = close - i + 1
429 case ":": 449 case ":":
430 // A link property (`%:annotation`), from org-protocol or the capture's own. 450 // A link property (`%:annotation`), from org-protocol or the capture's own.
@@ -437,23 +457,47 @@ public enum Capture {
437 } 457 }
438 let name = String(chars[(i + 2)..<j]) 458 let name = String(chars[(i + 2)..<j])
439 switch name { 459 switch name {
440 case _ where context.linkProperties[name] != nil: text += context.linkProperties[name]! 460 case _ where context.linkProperties[name] != nil: put(context.linkProperties[name]!)
441 case "annotation": text += context.annotation 461 case "annotation": put(context.annotation)
442 case "initial": text += context.initial 462 case "initial": put(context.initial)
443 default: break 463 default: break
444 } 464 }
445 consumed = j - i 465 consumed = j - i
446 case "(": 466 case "(":
447 return .failure(.message("Template escapes like %( run Emacs Lisp, which orgstar doesn't.")) 467 // The form is copied with the escapes in it expanded, then evaluated.
468 if let end = sexps[i], sexpEnds.isEmpty {
469 text += Self.sexpStartMark
470 sexpEnds.append(end)
471 } else {
472 text.append(c)
473 }
474 consumed = 1
448 default: 475 default:
449 text.append(c) 476 text.append(c)
450 consumed = 1 477 consumed = 1
451 } 478 }
452 i += consumed 479 i += consumed
453 } 480 }
454 return .success(text) 481 if !sexpEnds.isEmpty { text += Self.sexpEndMark }
482 // `%(…)`, in order.
483 var out = ""
484 var rest = Substring(text)
485 while let open = rest.firstIndex(of: Character(Self.sexpStartMark)) {
486 out += rest[..<open]
487 let body = rest[rest.index(after: open)...]
488 let close = body.firstIndex(of: Character(Self.sexpEndMark)) ?? body.endIndex
489 switch embedded.evaluate(String(body[..<close])) {
490 case .success(let value): out += value
491 case .failure(let failure): return .failure(failure)
492 }
493 rest = close == body.endIndex ? "" : body[body.index(after: close)...]
494 }
495 return .success(out + rest)
455 } 496 }
456 497
498 static let sexpStartMark = "\u{E001}"
499 static let sexpEndMark = "\u{E002}"
500
457 static func strftime(_ format: String, _ context: CaptureContext) -> String { 501 static func strftime(_ format: String, _ context: CaptureContext) -> String {
458 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: context.now) 502 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: context.now)
459 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] 503 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
Sources/OrgCore/Capture/CaptureLisp.swift added +142
@@ -0,0 +1,142 @@
1import Foundation
2
3// `%(sexp)` in capture templates (`org-capture-expand-embedded-elisp`), evaluated by the Elisp
4// subset with what capture templates call most: `format-time-string`, `current-time`,
5// `read-string` and `user-full-name`, besides the subset's own functions.
6
7extension Capture {
8 /// Where each `%(` that starts a whole sexp ends, by the index of its `%`: the forms
9 /// `org-capture-expand-embedded-elisp` marks. Escaped ones are left out by the caller.
10 static func embeddedSexps(_ chars: [Character]) -> [Int: Int] {
11 var ends: [Int: Int] = [:]
12 var i = 0
13 while i + 1 < chars.count {
14 if chars[i] == "%", chars[i + 1] == "(", let end = sexpEnd(chars, from: i + 1) {
15 ends[i] = end
16 i = end
17 } else {
18 i += 1
19 }
20 }
21 return ends
22 }
23
24 /// `scan-sexps` over a list starting at `start`: the index after its closing paren.
25 static func sexpEnd(_ chars: [Character], from start: Int) -> Int? {
26 var depth = 0
27 var i = start
28 while i < chars.count {
29 switch chars[i] {
30 case "(": depth += 1
31 case ")":
32 depth -= 1
33 if depth == 0 { return i + 1 }
34 case "\"":
35 i += 1
36 while i < chars.count, chars[i] != "\"" { i += chars[i] == "\\" ? 2 : 1 }
37 guard i < chars.count else { return nil }
38 case "?":
39 // A character: `?a`, `?\)`.
40 i += chars.indices.contains(i + 1) && chars[i + 1] == "\\" ? 2 : 1
41 case "\\":
42 i += 1
43 case ";":
44 while i < chars.count, chars[i] != "\n" { i += 1 }
45 default: break
46 }
47 i += 1
48 }
49 return nil
50 }
51
52 /// `org-capture--expand-keyword-in-embedded-elisp`: symbols such as `%:link` become the
53 /// link property's value.
54 static func expandKeywords(_ sexp: Sexp, _ context: CaptureContext) -> Sexp {
55 switch sexp {
56 case .list(let items): return .list(items.map { expandKeywords($0, context) })
57 case .dotted(let items, let last): return .dotted(items.map { expandKeywords($0, context) }, expandKeywords(last, context))
58 case .symbol(let name):
59 guard let range = name.range(of: "%:") else { return sexp }
60 let key = String(name[range.upperBound...])
61 switch key {
62 case _ where context.linkProperties[key] != nil: return .string(context.linkProperties[key]!)
63 case "annotation": return .string(context.annotation)
64 case "initial": return .string(context.initial)
65 default: return sexp
66 }
67 default: return sexp
68 }
69 }
70
71 /// Evaluates `%(…)` forms, the text from `(` to `)`, in order. `answers` reply to
72 /// `read-string` in order; the questions it asks and the answers it took come back.
73 final class Embedded {
74 let context: CaptureContext
75 var answers: ArraySlice<String>
76 var questions: [Question] = []
77 var used = 0
78 let lisp = Elisp()
79
80 init(_ context: CaptureContext, answers: [String]) {
81 self.context = context
82 self.answers = answers[...]
83 lisp.set("user-full-name", .string(context.userName))
84 lisp.define("user-full-name") { [context] _, _ in .string(context.userName) }
85 lisp.define("current-time") { [context] _, _ in Self.time(context.now) }
86 lisp.define("format-time-string") { [context] _, args in
87 guard let format = args.first?.string else { throw Elisp.Signal(message: "Wrong type argument: stringp, \(args.first?.description ?? "nil")") }
88 let date = try args.count > 1 && !Elisp.isNil(args[1]) ? Self.date(args[1]) : context.now
89 var at = context
90 at.now = date
91 return .string(Capture.strftime(format, at))
92 }
93 lisp.define("read-string") { [unowned self] _, args in
94 let prompt = args.first?.string ?? ""
95 let initial = args.count > 1 ? args[1].string : nil
96 let fallback = args.count > 3 ? args[3].string : nil
97 questions.append(Question(prompt: prompt.replacingOccurrences(of: ":? *$", with: "", options: .regularExpression),
98 defaultValue: fallback ?? initial ?? "", choices: []))
99 guard let answer = self.answers.popFirst() else { return .string(fallback ?? initial ?? "") }
100 used += 1
101 return .string(answer.isEmpty ? fallback ?? initial ?? "" : answer)
102 }
103 }
104
105 /// `(HIGH LOW USEC PSEC)`.
106 static func time(_ date: Date) -> Sexp {
107 let seconds = Int(date.timeIntervalSince1970.rounded(.down))
108 let micro = Int((date.timeIntervalSince1970 - Double(seconds)) * 1_000_000)
109 return .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF), .integer(micro), .integer(0)])
110 }
111
112 static func date(_ time: Sexp) throws -> Date {
113 if let seconds = time.integer { return Date(timeIntervalSince1970: Double(seconds)) }
114 guard let parts = time.elements, parts.count >= 2, let high = parts[0].integer, let low = parts[1].integer else {
115 throw Elisp.Unsupported(what: "time value \(time.description)")
116 }
117 let micro = parts.count > 2 ? Double(parts[2].integer ?? 0) / 1_000_000 : 0
118 return Date(timeIntervalSince1970: Double(high << 16 + low) + micro)
119 }
120
121 /// The value to insert for the form `text`: a string, or "" for nil.
122 func evaluate(_ text: String) -> Result<String, Failure> {
123 let form: Sexp
124 do {
125 guard let read = try LispReader.read(text).first?.sexp else { return .success("") }
126 form = read
127 } catch {
128 return .failure(.message("Can't read the template's \(text): \(error)"))
129 }
130 do {
131 let result = try lisp.eval(expandKeywords(form, context))
132 if Elisp.isNil(result) { return .success("") }
133 guard let string = result.string else { return .failure(.message("Capture template sexp `\(form.description)' must evaluate to string or nil")) }
134 return .success(string)
135 } catch let unsupported as Elisp.Unsupported {
136 return .failure(.message("Template %\(form.description) needs \(unsupported.what), which orgstar's Lisp doesn't have."))
137 } catch {
138 return .failure(.message("Template %\(form.description): \(error)"))
139 }
140 }
141 }
142}
Tests/OrgCoreTests/CaptureTests.swift +15
@@ -254,6 +254,15 @@ struct CaptureTests {
254 } 254 }
255 #expect(filled.text == "* untitled for me\nuntitled again\n") 255 #expect(filled.text == "* untitled for me\nuntitled again\n")
256 } 256 }
257
258 @Test func embeddedLispFailsClearly() {
259 func failure(_ template: String) -> Capture.Failure? {
260 if case .failure(let failure) = Capture.fill(template, context: CaptureContext()) { failure } else { nil }
261 }
262 #expect(failure("* %(+ 1 2)") == .message("Capture template sexp `(+ 1 2)' must evaluate to string or nil"))
263 #expect(failure("* %(org-id-new)") == .message("Template %(org-id-new) needs function org-id-new, which orgstar's Lisp doesn't have."))
264 #expect(Capture.questions("* %(read-string \"Title: \" \"draft\") %^{More}").map(\.prompt) == ["Title", "More"])
265 }
257} 266}
258 267
259struct CaptureEscapeTests { 268struct CaptureEscapeTests {
@@ -270,6 +279,12 @@ struct CaptureEscapeTests {
270 ("* A rather long heading title that goes on %^G", ["x:y"]), 279 ("* A rather long heading title that goes on %^G", ["x:y"]),
271 ("* Empty tags %^g done", [""]), 280 ("* Empty tags %^g done", [""]),
272 ("* Prop %^{CATEGORY|home}p\nbody", [""]), 281 ("* Prop %^{CATEGORY|home}p\nbody", [""]),
282 ("* %(format-time-string \"%Y-%m-%d %H:%M\") note", []),
283 ("* %(upcase \"%i\") from %(concat \"<\" \"%:annotation\" \">\")", []),
284 ("* %(read-string \"Name: \") met %^{Who}\n%(read-string \"Where? \" nil nil \"home\")", ["Ann", "Bob", ""]),
285 ("* %(if nil \"x\") empty %(mapconcat #'identity (list \"a\" \"b\") \"-\")", []),
286 ("* \\%(concat \"x\") kept and %(concat \"(\" \")\")", []),
287 ("* %(format-time-string \"%Y\" (current-time)) unbalanced %(concat", []),
273 ] 288 ]
274 289
275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 290 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
docs/manual/guide/08-capture.org +4 −1
@@ -185,6 +185,7 @@ These follow =org-capture-fill-template=. Escapes that need no answer are filled
185| =%<…>= | The current time formatted with a =format-time-string= pattern, such as =%<%Y-%m-%d %H:%M>= | 185| =%<…>= | The current time formatted with a =format-time-string= pattern, such as =%<%Y-%m-%d %H:%M>= |
186| =%:name= | A link property; see below | 186| =%:name= | A link property; see below |
187| =%[file]= | The contents of the file; see below | 187| =%[file]= | The contents of the file; see below |
188| =%(sexp)= | The value of an Emacs Lisp form; see below |
188 189
189From the Mac capture window, =%a= links to the heading at the cursor in the open file, as =[[file:~/org/work.org::*Heading][Heading]]=, or to the file itself before the first heading. It is empty with no file open. 190From the Mac capture window, =%a= links to the heading at the cursor in the open file, as =[[file:~/org/work.org::*Heading][Heading]]=, or to the file itself before the first heading. It is empty with no file open.
190 191
@@ -192,6 +193,8 @@ From the Mac capture window, =%a= links to the heading at the cursor in the open
192 193
193=%[file]= is replaced by the file's contents before anything else, as in Org, so escapes and prompts in the file work, and so does a =%[…]= in it. A relative path is relative to the configuration folder (the one with =capture.toml=), and =~= is your home folder. The file name runs to the last =]= on the line. A file that can't be read leaves =%![could not insert …]= in the text. 194=%[file]= is replaced by the file's contents before anything else, as in Org, so escapes and prompts in the file work, and so does a =%[…]= in it. A relative path is relative to the configuration folder (the one with =capture.toml=), and =~= is your home folder. The file name runs to the last =]= on the line. A file that can't be read leaves =%![could not insert …]= in the text.
194 195
196=%(sexp)= evaluates the form after the other escapes are expanded, as Org does, and inserts its value: a string as it is, nothing for =nil=; any other value is an error. Escapes inside the form, such as =%i= or =%:link= in a string, are expanded with backslashes and quotes escaped. orgstar evaluates the form with its own Lisp, not Emacs: =concat=, =format=, =upcase=, =substring=, =mapconcat=, =if=, =let= and the other basic functions, plus =format-time-string= (the codes =%<…>= takes, at the capture's time or a =current-time= value), =current-time=, =user-full-name= and =read-string=. =read-string= is asked as a question before the template's =%^= prompts. A form that calls anything else stops the capture with a message naming the function.
197
195=%:name= inserts a property of the link being captured. From org-protocol these are =%:link=, =%:description= (the page title), =%:type= (the link's scheme, such as =https=), =%:annotation= (the same as =%a=) and =%:initial= (the same as =%i=). Without org-protocol, =%:annotation= and =%:initial= still work and other names insert nothing. 198=%:name= inserts a property of the link being captured. From org-protocol these are =%:link=, =%:description= (the page title), =%:type= (the link's scheme, such as =https=), =%:annotation= (the same as =%a=) and =%:initial= (the same as =%i=). Without org-protocol, =%:annotation= and =%:initial= still work and other names insert nothing.
196 199
197** Prompts 200** Prompts
@@ -217,7 +220,7 @@ After the prompts are answered, =%\1=, =%\2= and so on insert the answer to the
217 220
218Put a backslash before =%= to keep it literally: =\%t= inserts =%t= (in a double-quoted TOML string, write =\\%t=). Two backslashes insert one backslash followed by the escape's value. 221Put a backslash before =%= to keep it literally: =\%t= inserts =%t= (in a double-quoted TOML string, write =\\%t=). Two backslashes insert one backslash followed by the escape's value.
219 222
220=%(…)= runs Emacs Lisp in Org and is not supported; a template that contains it fails with a message saying so. Any other =%= sequence is left as it is. 223Any other =%= sequence is left as it is.
221 224
222* Date trees 225* Date trees
223 226