Tests/OrgCoreTests/CaptureTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgCoreTests/CaptureTests.swift history · blame · raw

431 lines · 27444 bytes

18 symbols in this file
  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct CaptureTests {
  6    struct Case {
  7        var file: String
  8        var template: CaptureTemplate
  9        var typed: String
 10    }
 11
 12    static func lisp(_ s: String) -> String {
 13        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 14    }
 15
 16    /// Captures each case in `emacs --batch`: the target file afterwards.
 17    static func emacs(_ cases: [Case], seconds: Int) throws -> [String] {
 18        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-capture-\(UUID().uuidString)")
 19        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 20        defer { try? FileManager.default.removeItem(at: folder) }
 21        var forms: [String] = []
 22        for (i, c) in cases.enumerated() {
 23            let path = folder.appendingPathComponent("target\(i).org").path
 24            try c.file.write(toFile: path, atomically: true, encoding: .utf8)
 25            let target: String
 26            var properties = c.template.prepend ? " :prepend t" : ""
 27            let o = c.template.options
 28            if let n = o.emptyLines { properties += " :empty-lines \(n)" }
 29            if let n = o.emptyLinesBefore { properties += " :empty-lines-before \(n)" }
 30            if let n = o.emptyLinesAfter { properties += " :empty-lines-after \(n)" }
 31            if let pos = o.tableLinePos { properties += " :table-line-pos \(lisp(pos))" }
 32            switch c.template.target {
 33            case .file: target = "(file \(lisp(path)))"
 34            case .headline(_, let h): target = "(file+headline \(lisp(path)) \(lisp(h)))"
 35            case .outline(_, let p): target = "(file+olp \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
 36            case .datetree(_, let p, let tree):
 37                target = "(file+olp+datetree \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
 38                properties += " :tree-type \(tree.lisp)"
 39            case .regexp(_, let r): target = "(file+regexp \(lisp(path)) \(lisp(r)))"
 40            case .id(let id): target = "(id \(lisp(id)))"
 41            case .clock, .heading: target = "(clock)"
 42            }
 43            forms.append("""
 44            (condition-case nil
 45            (let ((org-capture-templates '(("x" "case" \(c.template.kind.rawValue) \(target) \(lisp(c.template.template))\(properties))))
 46                  (path \(lisp(path))))
 47              (cl-letf (((symbol-function 'org-id-find)
 48                         (lambda (id &rest _)
 49                           (with-current-buffer (find-file-noselect path)
 50                             (save-excursion
 51                               (goto-char (point-min))
 52                               (when (re-search-forward (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$") nil t)
 53                                 (org-back-to-heading t)
 54                                 (cons path (point))))))))
 55                (org-capture nil "x"))
 56              (insert \(lisp(c.typed)))
 57              (org-capture-finalize)
 58              (with-current-buffer (find-buffer-visiting \(lisp(path)))
 59                (push (buffer-substring-no-properties (point-min) (point-max)) results)))
 60            (error (push "failed" results)))
 61            """)
 62        }
 63        let output = folder.appendingPathComponent("out.json")
 64        let script = folder.appendingPathComponent("capture.el")
 65        try """
 66        ;;; -*- lexical-binding: t -*-
 67        (require 'org)
 68        (require 'org-capture)
 69        (require 'org-id)
 70        (require 'json)
 71        (setq org-adapt-indentation nil)
 72        (defvar results nil)
 73        \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
 74        (with-temp-file \(lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
 75        """.write(to: script, atomically: true, encoding: .utf8)
 76        let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
 77        guard FileManager.default.fileExists(atPath: output.path) else { throw EmacsOracle.EvaluateError(log: log) }
 78        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
 79    }
 80
 81    static func ours(_ c: Case, now: Date) -> String {
 82        var utcCalendar = Calendar(identifier: .gregorian)
 83        utcCalendar.timeZone = TimeZone(identifier: "UTC")!
 84        var utc = Calendar(identifier: .gregorian)
 85        utc.timeZone = TimeZone(identifier: "UTC")!
 86        guard case .success(let filled) = Capture.fill(c.template.template, context: CaptureContext(now: now, calendar: utc)) else { return "fill failed" }
 87        var text = filled.text
 88        let index = String.Index(utf16Offset: filled.cursor, in: text)
 89        text.insert(contentsOf: c.typed, at: index)
 90        switch Capture.place(text, template: c.template, in: c.file, now: now, calendar: utcCalendar) {
 91        case .success(let result): return result
 92        case .failure(.message(let message)): return "failed: \(message)"
 93        }
 94    }
 95
 96    static let files = [
 97        "#+TITLE: Todo\n* Inbox\n** TODO Old\n* Later\nText\n",
 98        "* Inbox\n\n** TODO Old\n\n* Later\n",
 99        "* Inbox\n",
100        "* Inbox",
101        "",
102        "Preamble\n* Other\n",
103        "* Inbox\nSome notes.\n- one\n- two\n\n** Child\n",
104        "* Projects\n** Work\n*** Active\n** Home\n",
105        "* Inbox\n:PROPERTIES:\n:ID: x\n:END:\nBody\n",
106    ]
107
108    static let templates: [CaptureTemplate] = [
109        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
110        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
111        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?", prepend: true),
112        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Missing"), template: "* %?"),
113        CaptureTemplate(key: "x", name: "", target: .file(""), template: "* Note %U\n%?"),
114        CaptureTemplate(key: "x", name: "", target: .file(""), template: "** Deep %?", prepend: true),
115        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "Plain %? text", ),
116        CaptureTemplate(key: "x", name: "", kind: .plain, target: .headline(file: "", headline: "Inbox"), template: "Plain line %?"),
117        CaptureTemplate(key: "x", name: "", kind: .plain, target: .file(""), template: "%<%Y-%m-%d>: %?"),
118        CaptureTemplate(key: "x", name: "", kind: .item, target: .headline(file: "", headline: "Inbox"), template: "%?"),
119        CaptureTemplate(key: "x", name: "", kind: .checkitem, target: .headline(file: "", headline: "Inbox"), template: "[ ] %?"),
120        CaptureTemplate(key: "x", name: "", target: .outline(file: "", path: ["Projects", "Work"]), template: "* TODO %?\n  Added %T"),
121    ]
122
123    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
124    func matchesEmacs() throws {
125        let seconds = 1_789_000_000
126        var cases: [Case] = []
127        for template in Self.templates {
128            for file in Self.files {
129                if case .outline = template.target, !file.contains("Projects") { continue }
130                if template.kind == .item || template.kind == .checkitem, !file.contains("Inbox") { continue }
131                cases.append(Case(file: file, template: template, typed: "Buy milk"))
132            }
133        }
134        let emacs = try Self.emacs(cases, seconds: seconds)
135        let now = Date(timeIntervalSince1970: Double(seconds))
136        for (c, expected) in zip(cases, emacs) {
137            let mine = Self.ours(c, now: now)
138            #expect(mine == expected, "\(c.template.template.debugDescription) \(c.template.kind) prepend \(c.template.prepend) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
139        }
140    }
141
142    static let tableFiles = [
143        "* Inbox\n| a | b |\n|---+---|\n| 1 | 2 |\n* Later\n",
144        "* Inbox\nText first.\n\n| a | b |\n|---+---|\n| 1 | 2 |\n|---+---|\n| total | |\n\nAfter.\n* Later\n",
145        "* Inbox\nNo table here.\n* Later\n",
146        "* Inbox\n",
147        "| x |\n| 1 |\n",
148        "* Inbox\n| n | sq |\n|---+----|\n| 2 |  4 |\n| 3 | 9 |\n#+TBLFM: $2=$1^2::@2$1=@3$1-1\n* Later\n",
149    ]
150
151    static let tableTemplates: [CaptureTemplate] = [
152        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| %? | new |"),
153        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| %? |", prepend: true),
154        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "%? | plain",
155                        options: .init(tableLinePos: "II-1")),
156        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| first %? |\n| second |",
157                        options: .init(tableLinePos: "I+1")),
158        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .file(""), template: "| %? |"),
159        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| far %? |",
160                        options: .init(tableLinePos: "I-9")),
161    ]
162
163    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
164    func tableLinesMatchEmacs() throws {
165        let seconds = 1_789_000_000
166        var cases: [Case] = []
167        for template in Self.tableTemplates {
168            for file in Self.tableFiles {
169                if case .headline = template.target, !file.contains("Inbox") { continue }
170                if template.options.tableLinePos == "II-1", !file.contains("total") { continue }
171                // Text in a computed column: Calc's symbolic result goes to Emacs.
172                if template.template.contains("first"), file.contains("TBLFM") { continue }
173                cases.append(Case(file: file, template: template, typed: "7"))
174            }
175        }
176        let emacs = try Self.emacs(cases, seconds: seconds)
177        let now = Date(timeIntervalSince1970: Double(seconds))
178        for (c, expected) in zip(cases, emacs) {
179            let mine = Self.ours(c, now: now)
180            #expect(mine == expected, "\(c.template.template.debugDescription) prepend \(c.template.prepend) pos \(c.template.options.tableLinePos ?? "-") into \(c.file.debugDescription)\nours:\n\(mine)\nemacs:\n\(expected)")
181        }
182    }
183
184    static let datetreeFiles = [
185        "",
186        "#+TITLE: Journal\n",
187        "* 2026\n** 2026-09 September\n*** 2026-09-01 Tuesday\nOld\n*** 2026-09-30 Wednesday\n** 2026-11 November\n* 2027\n",
188        "* 2025\n\n** 2025-01 January\n\n*** 2025-01-01 Wednesday\n\nNew year\n\n* Other\n",
189        "Notes before.\n\n* Journal\n** 2026\n*** 2026-09 September\n* Tasks\n** TODO Thing\n",
190        "* Journal\n:PROPERTIES:\n:ID: journal-id\n:END:\n* Tasks\n",
191        "* 2026\n** 2026-W36\n*** 2026-09-01 Tuesday\n** 2026-W38\n",
192    ]
193
194    static let datetreeTemplates: [CaptureTemplate] = [
195        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .day), template: "* %?"),
196        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .week), template: "* %U %?"),
197        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .month), template: "* %?"),
198        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: ["Journal"], tree: .day), template: "* %?"),
199        CaptureTemplate(key: "x", name: "", kind: .plain, target: .datetree(file: "", path: [], tree: .day), template: "%U %?"),
200        CaptureTemplate(key: "x", name: "", kind: .item, target: .datetree(file: "", path: [], tree: .day), template: "%?"),
201        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .day), template: "* %?", options: .init(prepend: true)),
202    ]
203
204    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: [1_789_000_000, 1_798_804_800])
205    func datetreesMatchEmacs(seconds: Int) throws {
206        var cases: [Case] = []
207        for template in Self.datetreeTemplates {
208            for file in Self.datetreeFiles {
209                if case .datetree(_, let path, _) = template.target, !path.isEmpty, !file.contains("* Journal") { continue }
210                cases.append(Case(file: file, template: template, typed: "Entry"))
211            }
212        }
213        let emacs = try Self.emacs(cases, seconds: seconds)
214        let now = Date(timeIntervalSince1970: Double(seconds))
215        for (c, expected) in zip(cases, emacs) {
216            let mine = Self.ours(c, now: now)
217            #expect(mine == expected, "\(c.template.target) \(c.template.kind) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
218        }
219    }
220
221    static let groupings = ["year", "year quarter", "year quarter month", "year quarter week", "year quarter month week day", "year month week",
222                            "year week", "month day", "quarter", "week day", "day"]
223
224    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil),
225          arguments: [1_789_000_000, 1_798_804_800, 1_767_139_200, 1_609_459_200, 1_664_582_400])
226    func treeGroupingsMatchEmacs(seconds: Int) throws {
227        let files = ["", "* 2026\n** 2026-Q1\n* 2027\n", "* Journal\n** 2025\n*** 2025-W40\n"]
228        var cases: [Case] = []
229        for grouping in Self.groupings {
230            for file in files {
231                let tree = CaptureTemplate.TreeType(rawValue: grouping)!
232                cases.append(Case(file: file, template: CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: tree), template: "* %?"), typed: "Entry"))
233            }
234        }
235        let emacs = try Self.emacs(cases, seconds: seconds)
236        let now = Date(timeIntervalSince1970: Double(seconds))
237        for (c, expected) in zip(cases, emacs) {
238            let mine = Self.ours(c, now: now)
239            #expect(mine == expected, "\(c.template.target) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
240        }
241    }
242
243    static let regexpTemplates: [CaptureTemplate] = [
244        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "^\\* Inbox"), template: "* %?"),
245        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "^\\* inbox"), template: "* %?", options: .init(prepend: true)),
246        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "notes\\."), template: "* %?"),
247        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "notes\\."), template: "* %?", options: .init(prepend: true)),
248        CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "notes\\."), template: "Plain %?"),
249        CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "^Some"), template: "Plain %?", options: .init(prepend: true)),
250        CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "Inbox$"), template: "Plain %?"),
251        CaptureTemplate(key: "x", name: "", kind: .plain, target: .regexp(file: "", regexp: "Inbox$"), template: "Plain %?", options: .init(prepend: true)),
252        CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "notes\\."), template: "%?"),
253        CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "Inbox"), template: "%?"),
254        CaptureTemplate(key: "x", name: "", kind: .item, target: .regexp(file: "", regexp: "^- two"), template: "%?", options: .init(prepend: true)),
255        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .regexp(file: "", regexp: "Table"), template: "| %? |"),
256        CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .regexp(file: "", regexp: "notes"), template: "| %? |"),
257        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "\\(Child\\|Later\\)"), template: "** %?"),
258        CaptureTemplate(key: "x", name: "", target: .regexp(file: "", regexp: "Missing"), template: "* %?"),
259    ]
260
261    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
262    func regexpTargetsMatchEmacs() throws {
263        let files = ["* Inbox\nSome notes.\n- one\n- two\n\n** Child\n* Later\n", "Preamble notes.\n* Inbox\n", "* Table\n| a |\n|---|\n| 1 |\n* Inbox\n"]
264        var cases: [Case] = []
265        for template in Self.regexpTemplates {
266            for file in files { cases.append(Case(file: file, template: template, typed: "Entry")) }
267        }
268        let seconds = 1_789_000_000
269        let emacs = try Self.emacs(cases, seconds: seconds)
270        for (c, expected) in zip(cases, emacs) {
271            var mine = Self.ours(c, now: Date(timeIntervalSince1970: Double(seconds)))
272            if mine.hasPrefix("failed:") { mine = "failed" }
273            #expect(mine == expected, "\(c.template.target) \(c.template.kind) \(c.template.options) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
274        }
275    }
276
277    static let optionTemplates: [CaptureTemplate] = [
278        CaptureTemplate(key: "x", name: "", target: .id("journal-id"), template: "* %?"),
279        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %?", options: .init(emptyLines: 1)),
280        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %?", options: .init(emptyLinesBefore: 2, emptyLinesAfter: 1)),
281        CaptureTemplate(key: "x", name: "", target: .file(""), template: "* %?", options: .init(prepend: true, emptyLinesAfter: 1)),
282        CaptureTemplate(key: "x", name: "", kind: .plain, target: .headline(file: "", headline: "Inbox"), template: "%?", options: .init(emptyLines: 1)),
283        CaptureTemplate(key: "x", name: "", kind: .item, target: .file(""), template: "%?", options: .init(emptyLines: 1)),
284    ]
285
286    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
287    func targetsAndEmptyLinesMatchEmacs() throws {
288        var cases: [Case] = []
289        let files = ["* Journal\n:PROPERTIES:\n:ID: journal-id\n:END:\nText\n** Old\n* Inbox\n", "* Inbox\n\n** Old\n\n* Later\n", "Preamble\n* Inbox\nBody\n"]
290        for template in Self.optionTemplates {
291            for file in files {
292                if case .id = template.target, !file.contains("journal-id") { continue }
293                cases.append(Case(file: file, template: template, typed: "Entry"))
294            }
295        }
296        let seconds = 1_789_000_000
297        let emacs = try Self.emacs(cases, seconds: seconds)
298        for (c, expected) in zip(cases, emacs) {
299            let mine = Self.ours(c, now: Date(timeIntervalSince1970: Double(seconds)))
300            #expect(mine == expected, "\(c.template.target) \(c.template.kind) \(c.template.options) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
301        }
302    }
303
304    @Test func fillsPrompts() {
305        let template = "* %^{Title|untitled} for %^{Who}\n%\\1 again"
306        #expect(Capture.questions(template) == [
307            Capture.Question(prompt: "Title", defaultValue: "untitled", choices: []),
308            Capture.Question(prompt: "Who", defaultValue: "", choices: []),
309        ])
310        guard case .success(let filled) = Capture.fill(template, context: CaptureContext(), answers: ["", "me"]) else {
311            Issue.record("fill failed")
312            return
313        }
314        #expect(filled.text == "* untitled for me\nuntitled again\n")
315    }
316
317    @Test func embeddedLispFailsClearly() {
318        func failure(_ template: String) -> Capture.Failure? {
319            if case .failure(let failure) = Capture.fill(template, context: CaptureContext()) { failure } else { nil }
320        }
321        #expect(failure("* %(+ 1 2)") == .message("Capture template sexp `(+ 1 2)' must evaluate to string or nil"))
322        #expect(failure("* %(org-id-new)") == .message("Template %(org-id-new) needs function org-id-new, which orgstar's Lisp doesn't have."))
323        #expect(Capture.questions("* %(read-string \"Title: \" \"draft\") %^{More}").map(\.prompt) == ["Title", "More"])
324    }
325}
326
327struct CaptureEscapeTests {
328    /// Templates and the answers to their prompts, in order.
329    static let cases: [(template: String, answers: [String])] = [
330        ("* TODO %^{Task} %^g\n%^{Effort}p%?", ["Call bank", "work:phone", "1:00"]),
331        ("* Meeting %^T\n%^{Who|Ann|Bob} said %\\1, tags %\\*2", ["fri 14:00", ""]),
332        ("* %^{Title} :work:\nSCHEDULED: %^t\n%^u %^U", ["Plan", "+2d", "", "2026-10-01 9:30"]),
333        ("* Link %^L and %^C", ["https://orgmode.org", ""]),
334        ("* %A\n%:annotation %:initial %k%?", ["the page"]),
335        ("\\%a literal and \\\\%a doubled %c", []),
336        ("* Heading %^{Due}t and %^{Seen}U", ["tue", ""]),
337        ("%^{Name}\n- item %^g", ["Bob", "a:b"]),
338        ("* A rather long heading title that goes on %^G", ["x:y"]),
339        ("* Empty tags %^g done", [""]),
340        ("* Prop %^{CATEGORY|home}p\nbody", [""]),
341        ("* %(format-time-string \"%Y-%m-%d %H:%M\") note", []),
342        ("* %(upcase \"%i\") from %(concat \"<\" \"%:annotation\" \">\")", []),
343        ("* %(read-string \"Name: \") met %^{Who}\n%(read-string \"Where? \" nil nil \"home\")", ["Ann", "Bob", ""]),
344        ("* %(if nil \"x\") empty %(mapconcat #'identity (list \"a\" \"b\") \"-\")", []),
345        ("* \\%(concat \"x\") kept and %(concat \"(\" \")\")", []),
346        ("* %(format-time-string \"%Y\" (current-time)) unbalanced %(concat", []),
347    ]
348
349    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
350    func fillsLikeOrgCaptureFillTemplate() throws {
351        try Self.compare(Self.cases)
352    }
353
354    /// `%[file]`, with escapes in the file and a file named in it, a relative path from the
355    /// folder, and an escaped one.
356    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
357    func insertsFilesLikeOrg() throws {
358        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-files-\(UUID().uuidString)")
359        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
360        defer { try? FileManager.default.removeItem(at: folder) }
361        let inner = folder.appendingPathComponent("inner.txt").path
362        try "- inner %t\n".write(toFile: inner, atomically: true, encoding: .utf8)
363        try "** From file %^{Topic}\n%[\(inner)]%?".write(to: folder.appendingPathComponent("entry.org"), atomically: true, encoding: .utf8)
364        try "relative %a".write(to: folder.appendingPathComponent("rel.txt"), atomically: true, encoding: .utf8)
365        try Self.compare([
366            ("* Top\n%[\(folder.path)/entry.org]", ["Lunch"]),
367            ("* Rel %[rel.txt]\n\\%[rel.txt] kept\n%[missing.txt]", []),
368        ], directory: folder)
369    }
370
371    static func compare(_ cases: [(template: String, answers: [String])], directory: URL? = nil) throws {
372        let seconds = 1_789_000_000
373        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fill-\(UUID().uuidString)")
374        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
375        defer { try? FileManager.default.removeItem(at: folder) }
376        let forms = cases.map { c in
377            """
378            (let ((answers (list \(c.answers.map(CaptureTests.lisp).joined(separator: " ")))))
379              (cl-letf* ((next (lambda (default) (let ((a (pop answers))) (if (or (null a) (equal a "")) (or default "") a))))
380                         (ord (symbol-function 'org-read-date))
381                         ((symbol-function 'org-completing-read) (lambda (_p _c &optional _a _b _i _h def &rest _) (funcall next def)))
382                         ((symbol-function 'completing-read-multiple) (lambda (&rest _) (split-string (funcall next "") ":" t)))
383                         ((symbol-function 'read-string) (lambda (_p &optional _i _h def &rest _) (funcall next def)))
384                         ((symbol-function 'org-read-property-value) (lambda (_p &optional _e def) (funcall next def)))
385                         ((symbol-function 'org-read-date)
386                          (lambda (&optional with-time to-time _from prompt &rest _)
387                            (let ((a (pop answers))) (funcall ord with-time to-time (if (equal a "") "." a) prompt)))))
388                (with-temp-buffer
389                  (org-mode)
390                  (setq org-capture-plist (list :buffer (current-buffer) :pos 1))
391                  (push (org-capture-fill-template \(CaptureTests.lisp(c.template)) "Selected" "[[file:~/n.org::*Task][Task]]") results))))
392            """
393        }
394        let output = folder.appendingPathComponent("out.json")
395        let script = folder.appendingPathComponent("fill.el")
396        try """
397        ;;; -*- lexical-binding: t -*-
398        (require 'org)
399        (require 'org-capture)
400        (require 'json)
401        (require 'cl-lib)
402        (setq org-adapt-indentation nil)
403        (kill-new "Clip")
404        \(directory.map { "(setq default-directory \(CaptureTests.lisp($0.path + "/")))" } ?? "")
405        (defvar results nil)
406        \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
407        (with-temp-file \(CaptureTests.lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
408        """.write(to: script, atomically: true, encoding: .utf8)
409        let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
410        guard FileManager.default.fileExists(atPath: output.path) else { throw EmacsOracle.EvaluateError(log: log) }
411        let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
412        var utc = Calendar(identifier: .gregorian)
413        utc.timeZone = TimeZone(identifier: "UTC")!
414        var context = CaptureContext(now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc, initial: "Selected",
415                                     annotation: "[[file:~/n.org::*Task][Task]]", clipboard: "Clip")
416        if let directory {
417            context.directory = directory.path
418            context.readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
419        }
420        for (c, expected) in zip(cases, emacs) {
421            #expect(Capture.questions(c.template, context: context).count == c.answers.count, "\(c.template.debugDescription)")
422            guard case .success(let filled) = Capture.fill(c.template, context: context, answers: c.answers) else {
423                Issue.record("fill failed for \(c.template.debugDescription)")
424                continue
425            }
426            var mine = filled.text
427            if expected.contains("%?") { mine.insert(contentsOf: "%?", at: String.Index(utf16Offset: filled.cursor, in: mine)) }
428            #expect(mine == expected, "\(c.template.debugDescription)\nours:  \(mine.debugDescription)\nemacs: \(expected.debugDescription)")
429        }
430    }
431}