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 {
127127 }
128128}
129129
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
130138public struct CaptureError: Error, Equatable {
131139 public let message: String
132140 public init(message: String) { self.message = message }
@@ -162,7 +170,8 @@ extension DocumentSession {
162170 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
163171 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
164172 }
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()
166175 let answers = Capture.questions(chosen.template, context: context).map { _ in "" }
167176 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
168177 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 {
120120 public var tagsColumn: Int
121121 /// `org-store-link-plist` as org-protocol sets it, for `%:link`, `%:description` and others.
122122 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 }
123127
124128 public init(
125129 now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "",
@@ -318,9 +322,40 @@ public enum Capture {
318322 return n % 2 == 1
319323 }
320324
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
321355 /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…), with `%^` prompts and `%\N`
322356 /// left in place.
323357 static func expand(_ template: String, _ context: CaptureContext) -> Result<String, Failure> {
358 let template = insertFiles(template, context)
324359 func stamp(_ active: Bool, _ withTime: Bool) -> String {
325360 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
326361 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
@@ -410,8 +445,6 @@ public enum Capture {
410445 consumed = j - i
411446 case "(":
412447 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."))
415448 default:
416449 text.append(c)
417450 consumed = 1
Sources/Orgstar/CaptureView.swift +1
@@ -151,6 +151,7 @@ struct CaptureView: View {
151151 allTags: (try? workspace.index.tags()) ?? [],
152152 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
153153 )
154 context.readsTemplateFiles()
154155 }
155156
156157 /// 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 {
9898 allTags: (try? workspace.index.tags()) ?? []
9999 )
100100 context.linkProperties = request.properties
101 context.readsTemplateFiles()
101102 // `%^g` offers the target file's tags.
102103 let path = DocumentSession.resolve(template.target.file, root: workspace.rootPaths.first)
103104 if !template.target.file.isEmpty,
Tests/OrgCoreTests/CaptureTests.swift +30 −4
@@ -274,11 +274,32 @@ struct CaptureEscapeTests {
274274
275275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
276276 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 {
277298 let seconds = 1_789_000_000
278299 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fill-\(UUID().uuidString)")
279300 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
280301 defer { try? FileManager.default.removeItem(at: folder) }
281 let forms = Self.cases.map { c in
302 let forms = cases.map { c in
282303 """
283304 (let ((answers (list \(c.answers.map(CaptureTests.lisp).joined(separator: " ")))))
284305 (cl-letf* ((next (lambda (default) (let ((a (pop answers))) (if (or (null a) (equal a "")) (or default "") a))))
@@ -306,6 +327,7 @@ struct CaptureEscapeTests {
306327 (require 'cl-lib)
307328 (setq org-adapt-indentation nil)
308329 (kill-new "Clip")
330 \(directory.map { "(setq default-directory \(CaptureTests.lisp($0.path + "/")))" } ?? "")
309331 (defvar results nil)
310332 \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
311333 (with-temp-file \(CaptureTests.lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
@@ -315,16 +337,20 @@ struct CaptureEscapeTests {
315337 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
316338 var utc = Calendar(identifier: .gregorian)
317339 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",
319341 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) {
321347 #expect(Capture.questions(c.template, context: context).count == c.answers.count, "\(c.template.debugDescription)")
322348 guard case .success(let filled) = Capture.fill(c.template, context: context, answers: c.answers) else {
323349 Issue.record("fill failed for \(c.template.debugDescription)")
324350 continue
325351 }
326352 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)) }
328354 #expect(mine == expected, "\(c.template.debugDescription)\nours: \(mine.debugDescription)\nemacs: \(expected.debugDescription)")
329355 }
330356 }
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
184184| =%U= | Inactive timestamp with the current time |
185185| =%<…>= | The current time formatted with a =format-time-string= pattern, such as =%<%Y-%m-%d %H:%M>= |
186186| =%:name= | A link property; see below |
187| =%[file]= | The contents of the file; see below |
187188
188189From 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.
189190
190191=%<…>= 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.
191192
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
192195=%: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.
193196
194197** Prompts
@@ -214,7 +217,7 @@ After the prompts are answered, =%\1=, =%\2= and so on insert the answer to the
214217
215218Put 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.
216219
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.
218221
219222* Date trees
220223