Capture: %[file] escape !249

merged merged by cmc on 2026-10-11 08:22 UTC · krz/orgstar:capture-file-escape into main

6 files changed, +81 −8

Layout: unified · split

Sources/OrgApp/CaptureModel.swift +10 −1
@@ -127,6 +127,14 @@ extension DocumentSession {
127 } 127 }
128} 128}
129 129
130extension CaptureContext {
131 /// `%[file]` reads the file, a relative path from the configuration folder.
132 public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
133 self.directory = directory.path
134 readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
135 }
136}
137
130public struct CaptureError: Error, Equatable { 138public struct CaptureError: Error, Equatable {
131 public let message: String 139 public let message: String
132 public init(message: String) { self.message = message } 140 public init(message: String) { self.message = message }
@@ -162,7 +170,8 @@ extension DocumentSession {
162 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else { 170 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
163 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\"")) 171 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
164 } 172 }
165 let context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? []) 173 var context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? [])
174 context.readsTemplateFiles()
166 let answers = Capture.questions(chosen.template, context: context).map { _ in "" } 175 let answers = Capture.questions(chosen.template, context: context).map { _ in "" }
167 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else { 176 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
168 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\"")) 177 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
Sources/OrgCore/Capture/Capture.swift +35 −2
@@ -120,6 +120,10 @@ public struct CaptureContext: Sendable {
120 public var tagsColumn: Int 120 public var tagsColumn: Int
121 /// `org-store-link-plist` as org-protocol sets it, for `%:link`, `%:description` and others. 121 /// `org-store-link-plist` as org-protocol sets it, for `%:link`, `%:description` and others.
122 public var linkProperties: [String: String] = [:] 122 public var linkProperties: [String: String] = [:]
123 /// `%[file]`: what relative paths are relative to, and the contents of a file by its
124 /// absolute path, nil when it can't be read.
125 public var directory = NSHomeDirectory()
126 public var readFile: @Sendable (String) -> String? = { _ in nil }
123 127
124 public init( 128 public init(
125 now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "", 129 now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "",
@@ -318,9 +322,40 @@ public enum Capture {
318 return n % 2 == 1 322 return n % 2 == 1
319 } 323 }
320 324
325 /// `%[file]`: the file's contents in place of each, as `org-capture-fill-template` inserts
326 /// them before the other escapes, so escapes in the file expand too.
327 static func insertFiles(_ template: String, _ context: CaptureContext) -> String {
328 let buffer = EmacsBuffer(template, point: 0)
329 var inserted = 0
330 // A file that inserts itself would never end; Emacs doesn't stop either.
331 while inserted < 100, let match = buffer.searchForward("%\\[(.+)\\]", caseInsensitive: false, move: true) {
332 let name = buffer.substring(match[1]!.lowerBound, match[1]!.upperBound)
333 let start = buffer.marker(match[0]!.lowerBound)
334 let end = buffer.marker(match[0]!.upperBound)
335 defer {
336 buffer.release(start)
337 buffer.release(end)
338 }
339 if unescape(buffer, at: start.position) { continue }
340 let expanded = name.hasPrefix("~") ? NSHomeDirectory() + name.dropFirst() : name
341 let path = ((expanded as NSString).isAbsolutePath ? expanded : (context.directory as NSString).appendingPathComponent(expanded) as String)
342 let file = (path as NSString).standardizingPath
343 buffer.deleteRegion(start.position, end.position)
344 buffer.point = start.position
345 if let contents = context.readFile(file) {
346 buffer.saveExcursion { buffer.insert(contents) }
347 inserted += 1
348 } else {
349 buffer.insert("%![could not insert \(file): (file-missing Opening input file No such file or directory \(file))]")
350 }
351 }
352 return buffer.string
353 }
354
321 /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…), with `%^` prompts and `%\N` 355 /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…), with `%^` prompts and `%\N`
322 /// left in place. 356 /// left in place.
323 static func expand(_ template: String, _ context: CaptureContext) -> Result<String, Failure> { 357 static func expand(_ template: String, _ context: CaptureContext) -> Result<String, Failure> {
358 let template = insertFiles(template, context)
324 func stamp(_ active: Bool, _ withTime: Bool) -> String { 359 func stamp(_ active: Bool, _ withTime: Bool) -> String {
325 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now) 360 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
326 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1] 361 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
@@ -410,8 +445,6 @@ public enum Capture {
410 consumed = j - i 445 consumed = j - i
411 case "(": 446 case "(":
412 return .failure(.message("Template escapes like %( run Emacs Lisp, which orgstar doesn't.")) 447 return .failure(.message("Template escapes like %( run Emacs Lisp, which orgstar doesn't."))
413 case "[":
414 return .failure(.message("Template escapes like %[file] aren't supported yet."))
415 default: 448 default:
416 text.append(c) 449 text.append(c)
417 consumed = 1 450 consumed = 1
Sources/Orgstar/CaptureView.swift +1
@@ -151,6 +151,7 @@ struct CaptureView: View {
151 allTags: (try? workspace.index.tags()) ?? [], 151 allTags: (try? workspace.index.tags()) ?? [],
152 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77 152 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
153 ) 153 )
154 context.readsTemplateFiles()
154 } 155 }
155 156
156 /// An org-protocol capture: its link properties fill `%a`, `%i` and `%:…`, and its 157 /// An org-protocol capture: its link properties fill `%a`, `%i` and `%:…`, and its
Sources/OrgstarMobile/CaptureScreen.swift +1
@@ -98,6 +98,7 @@ struct CaptureScreen: View {
98 allTags: (try? workspace.index.tags()) ?? [] 98 allTags: (try? workspace.index.tags()) ?? []
99 ) 99 )
100 context.linkProperties = request.properties 100 context.linkProperties = request.properties
101 context.readsTemplateFiles()
101 // `%^g` offers the target file's tags. 102 // `%^g` offers the target file's tags.
102 let path = DocumentSession.resolve(template.target.file, root: workspace.rootPaths.first) 103 let path = DocumentSession.resolve(template.target.file, root: workspace.rootPaths.first)
103 if !template.target.file.isEmpty, 104 if !template.target.file.isEmpty,
Tests/OrgCoreTests/CaptureTests.swift +30 −4
@@ -274,11 +274,32 @@ struct CaptureEscapeTests {
274 274
275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
276 func fillsLikeOrgCaptureFillTemplate() throws { 276 func fillsLikeOrgCaptureFillTemplate() throws {
277 try Self.compare(Self.cases)
278 }
279
280 /// `%[file]`, with escapes in the file and a file named in it, a relative path from the
281 /// folder, and an escaped one.
282 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
283 func insertsFilesLikeOrg() throws {
284 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-files-\(UUID().uuidString)")
285 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
286 defer { try? FileManager.default.removeItem(at: folder) }
287 let inner = folder.appendingPathComponent("inner.txt").path
288 try "- inner %t\n".write(toFile: inner, atomically: true, encoding: .utf8)
289 try "** From file %^{Topic}\n%[\(inner)]%?".write(to: folder.appendingPathComponent("entry.org"), atomically: true, encoding: .utf8)
290 try "relative %a".write(to: folder.appendingPathComponent("rel.txt"), atomically: true, encoding: .utf8)
291 try Self.compare([
292 ("* Top\n%[\(folder.path)/entry.org]", ["Lunch"]),
293 ("* Rel %[rel.txt]\n\\%[rel.txt] kept\n%[missing.txt]", []),
294 ], directory: folder)
295 }
296
297 static func compare(_ cases: [(template: String, answers: [String])], directory: URL? = nil) throws {
277 let seconds = 1_789_000_000 298 let seconds = 1_789_000_000
278 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fill-\(UUID().uuidString)") 299 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fill-\(UUID().uuidString)")
279 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 300 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
280 defer { try? FileManager.default.removeItem(at: folder) } 301 defer { try? FileManager.default.removeItem(at: folder) }
281 let forms = Self.cases.map { c in 302 let forms = cases.map { c in
282 """ 303 """
283 (let ((answers (list \(c.answers.map(CaptureTests.lisp).joined(separator: " "))))) 304 (let ((answers (list \(c.answers.map(CaptureTests.lisp).joined(separator: " ")))))
284 (cl-letf* ((next (lambda (default) (let ((a (pop answers))) (if (or (null a) (equal a "")) (or default "") a)))) 305 (cl-letf* ((next (lambda (default) (let ((a (pop answers))) (if (or (null a) (equal a "")) (or default "") a))))
@@ -306,6 +327,7 @@ struct CaptureEscapeTests {
306 (require 'cl-lib) 327 (require 'cl-lib)
307 (setq org-adapt-indentation nil) 328 (setq org-adapt-indentation nil)
308 (kill-new "Clip") 329 (kill-new "Clip")
330 \(directory.map { "(setq default-directory \(CaptureTests.lisp($0.path + "/")))" } ?? "")
309 (defvar results nil) 331 (defvar results nil)
310 \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")")) 332 \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
311 (with-temp-file \(CaptureTests.lisp(output.path)) (insert (json-encode (vconcat (nreverse results))))) 333 (with-temp-file \(CaptureTests.lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
@@ -315,16 +337,20 @@ struct CaptureEscapeTests {
315 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: output)) 337 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
316 var utc = Calendar(identifier: .gregorian) 338 var utc = Calendar(identifier: .gregorian)
317 utc.timeZone = TimeZone(identifier: "UTC")! 339 utc.timeZone = TimeZone(identifier: "UTC")!
318 let context = CaptureContext(now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc, initial: "Selected", 340 var context = CaptureContext(now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc, initial: "Selected",
319 annotation: "[[file:~/n.org::*Task][Task]]", clipboard: "Clip") 341 annotation: "[[file:~/n.org::*Task][Task]]", clipboard: "Clip")
320 for (c, expected) in zip(Self.cases, emacs) { 342 if let directory {
343 context.directory = directory.path
344 context.readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
345 }
346 for (c, expected) in zip(cases, emacs) {
321 #expect(Capture.questions(c.template, context: context).count == c.answers.count, "\(c.template.debugDescription)") 347 #expect(Capture.questions(c.template, context: context).count == c.answers.count, "\(c.template.debugDescription)")
322 guard case .success(let filled) = Capture.fill(c.template, context: context, answers: c.answers) else { 348 guard case .success(let filled) = Capture.fill(c.template, context: context, answers: c.answers) else {
323 Issue.record("fill failed for \(c.template.debugDescription)") 349 Issue.record("fill failed for \(c.template.debugDescription)")
324 continue 350 continue
325 } 351 }
326 var mine = filled.text 352 var mine = filled.text
327 if c.template.contains("%?") { mine.insert(contentsOf: "%?", at: String.Index(utf16Offset: filled.cursor, in: mine)) } 353 if expected.contains("%?") { mine.insert(contentsOf: "%?", at: String.Index(utf16Offset: filled.cursor, in: mine)) }
328 #expect(mine == expected, "\(c.template.debugDescription)\nours: \(mine.debugDescription)\nemacs: \(expected.debugDescription)") 354 #expect(mine == expected, "\(c.template.debugDescription)\nours: \(mine.debugDescription)\nemacs: \(expected.debugDescription)")
329 } 355 }
330 } 356 }
docs/manual/guide/08-capture.org +4 −1
@@ -184,11 +184,14 @@ These follow =org-capture-fill-template=. Escapes that need no answer are filled
184| =%U= | Inactive timestamp with the current time | 184| =%U= | Inactive timestamp with the current time |
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 188
188From 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. 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.
189 190
190=%<…>= understands =%Y=, =%m=, =%d=, =%e=, =%H=, =%M=, =%S=, =%a=, =%A=, =%b=, =%B=, =%F=, =%R= and =%%=, with English day and month names. Other =format-time-string= codes are left in the text as they are. 191=%<…>= understands =%Y=, =%m=, =%d=, =%e=, =%H=, =%M=, =%S=, =%a=, =%A=, =%b=, =%B=, =%F=, =%R= and =%%=, with English day and month names. Other =format-time-string= codes are left in the text as they are.
191 192
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
192=%: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. 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.
193 196
194** Prompts 197** Prompts
@@ -214,7 +217,7 @@ After the prompts are answered, =%\1=, =%\2= and so on insert the answer to the
214 217
215Put 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. 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.
216 219
217=%(…)= runs Emacs Lisp in Org and is not supported; a template that contains it fails with a message saying so. =%[file]= (insert a file's contents) is not supported either. Any other =%= sequence is left as it is. 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.
218 221
219* Date trees 222* Date trees
220 223