Tests/OrgCoreTests/CaptureTests.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Tests/OrgCoreTests/CaptureTests.swift

288 lines · 17487 bytes

  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            switch c.template.target {
 32            case .file: target = "(file \(lisp(path)))"
 33            case .headline(_, let h): target = "(file+headline \(lisp(path)) \(lisp(h)))"
 34            case .outline(_, let p): target = "(file+olp \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
 35            case .datetree(_, let p, let tree):
 36                target = "(file+olp+datetree \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
 37                properties += " :tree-type \(tree.rawValue)"
 38            case .id(let id): target = "(id \(lisp(id)))"
 39            case .clock, .heading: target = "(clock)"
 40            }
 41            forms.append("""
 42            (let ((org-capture-templates '(("x" "case" \(c.template.kind.rawValue) \(target) \(lisp(c.template.template))\(properties))))
 43                  (path \(lisp(path))))
 44              (cl-letf (((symbol-function 'org-id-find)
 45                         (lambda (id &rest _)
 46                           (with-current-buffer (find-file-noselect path)
 47                             (save-excursion
 48                               (goto-char (point-min))
 49                               (when (re-search-forward (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$") nil t)
 50                                 (org-back-to-heading t)
 51                                 (cons path (point))))))))
 52                (org-capture nil "x"))
 53              (insert \(lisp(c.typed)))
 54              (org-capture-finalize)
 55              (with-current-buffer (find-buffer-visiting \(lisp(path)))
 56                (push (buffer-substring-no-properties (point-min) (point-max)) results)))
 57            """)
 58        }
 59        let output = folder.appendingPathComponent("out.json")
 60        let script = folder.appendingPathComponent("capture.el")
 61        try """
 62        ;;; -*- lexical-binding: t -*-
 63        (require 'org)
 64        (require 'org-capture)
 65        (require 'org-id)
 66        (require 'json)
 67        (setq org-adapt-indentation nil)
 68        (defvar results nil)
 69        \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
 70        (with-temp-file \(lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
 71        """.write(to: script, atomically: true, encoding: .utf8)
 72        let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
 73        guard FileManager.default.fileExists(atPath: output.path) else { throw EmacsOracle.EvaluateError(log: log) }
 74        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
 75    }
 76
 77    static func ours(_ c: Case, now: Date) -> String {
 78        var utcCalendar = Calendar(identifier: .gregorian)
 79        utcCalendar.timeZone = TimeZone(identifier: "UTC")!
 80        var utc = Calendar(identifier: .gregorian)
 81        utc.timeZone = TimeZone(identifier: "UTC")!
 82        guard case .success(let filled) = Capture.fill(c.template.template, context: CaptureContext(now: now, calendar: utc)) else { return "fill failed" }
 83        var text = filled.text
 84        let index = String.Index(utf16Offset: filled.cursor, in: text)
 85        text.insert(contentsOf: c.typed, at: index)
 86        switch Capture.place(text, template: c.template, in: c.file, now: now, calendar: utcCalendar) {
 87        case .success(let result): return result
 88        case .failure(.message(let message)): return "failed: \(message)"
 89        }
 90    }
 91
 92    static let files = [
 93        "#+TITLE: Todo\n* Inbox\n** TODO Old\n* Later\nText\n",
 94        "* Inbox\n\n** TODO Old\n\n* Later\n",
 95        "* Inbox\n",
 96        "* Inbox",
 97        "",
 98        "Preamble\n* Other\n",
 99        "* Inbox\nSome notes.\n- one\n- two\n\n** Child\n",
100        "* Projects\n** Work\n*** Active\n** Home\n",
101        "* Inbox\n:PROPERTIES:\n:ID: x\n:END:\nBody\n",
102    ]
103
104    static let templates: [CaptureTemplate] = [
105        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
106        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
107        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?", prepend: true),
108        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Missing"), template: "* %?"),
109        CaptureTemplate(key: "x", name: "", target: .file(""), template: "* Note %U\n%?"),
110        CaptureTemplate(key: "x", name: "", target: .file(""), template: "** Deep %?", prepend: true),
111        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "Plain %? text", ),
112        CaptureTemplate(key: "x", name: "", kind: .plain, target: .headline(file: "", headline: "Inbox"), template: "Plain line %?"),
113        CaptureTemplate(key: "x", name: "", kind: .plain, target: .file(""), template: "%<%Y-%m-%d>: %?"),
114        CaptureTemplate(key: "x", name: "", kind: .item, target: .headline(file: "", headline: "Inbox"), template: "%?"),
115        CaptureTemplate(key: "x", name: "", kind: .checkitem, target: .headline(file: "", headline: "Inbox"), template: "[ ] %?"),
116        CaptureTemplate(key: "x", name: "", target: .outline(file: "", path: ["Projects", "Work"]), template: "* TODO %?\n  Added %T"),
117    ]
118
119    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
120    func matchesEmacs() throws {
121        let seconds = 1_789_000_000
122        var cases: [Case] = []
123        for template in Self.templates {
124            for file in Self.files {
125                if case .outline = template.target, !file.contains("Projects") { continue }
126                if template.kind == .item || template.kind == .checkitem, !file.contains("Inbox") { continue }
127                cases.append(Case(file: file, template: template, typed: "Buy milk"))
128            }
129        }
130        let emacs = try Self.emacs(cases, seconds: seconds)
131        let now = Date(timeIntervalSince1970: Double(seconds))
132        for (c, expected) in zip(cases, emacs) {
133            let mine = Self.ours(c, now: now)
134            #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)")
135        }
136    }
137
138    static let datetreeFiles = [
139        "",
140        "#+TITLE: Journal\n",
141        "* 2026\n** 2026-09 September\n*** 2026-09-01 Tuesday\nOld\n*** 2026-09-30 Wednesday\n** 2026-11 November\n* 2027\n",
142        "* 2025\n\n** 2025-01 January\n\n*** 2025-01-01 Wednesday\n\nNew year\n\n* Other\n",
143        "Notes before.\n\n* Journal\n** 2026\n*** 2026-09 September\n* Tasks\n** TODO Thing\n",
144        "* Journal\n:PROPERTIES:\n:ID: journal-id\n:END:\n* Tasks\n",
145        "* 2026\n** 2026-W36\n*** 2026-09-01 Tuesday\n** 2026-W38\n",
146    ]
147
148    static let datetreeTemplates: [CaptureTemplate] = [
149        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .day), template: "* %?"),
150        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .week), template: "* %U %?"),
151        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .month), template: "* %?"),
152        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: ["Journal"], tree: .day), template: "* %?"),
153        CaptureTemplate(key: "x", name: "", kind: .plain, target: .datetree(file: "", path: [], tree: .day), template: "%U %?"),
154        CaptureTemplate(key: "x", name: "", kind: .item, target: .datetree(file: "", path: [], tree: .day), template: "%?"),
155        CaptureTemplate(key: "x", name: "", target: .datetree(file: "", path: [], tree: .day), template: "* %?", options: .init(prepend: true)),
156    ]
157
158    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: [1_789_000_000, 1_798_804_800])
159    func datetreesMatchEmacs(seconds: Int) throws {
160        var cases: [Case] = []
161        for template in Self.datetreeTemplates {
162            for file in Self.datetreeFiles {
163                if case .datetree(_, let path, _) = template.target, !path.isEmpty, !file.contains("* Journal") { continue }
164                cases.append(Case(file: file, template: template, typed: "Entry"))
165            }
166        }
167        let emacs = try Self.emacs(cases, seconds: seconds)
168        let now = Date(timeIntervalSince1970: Double(seconds))
169        for (c, expected) in zip(cases, emacs) {
170            let mine = Self.ours(c, now: now)
171            #expect(mine == expected, "\(c.template.target) \(c.template.kind) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
172        }
173    }
174
175    static let optionTemplates: [CaptureTemplate] = [
176        CaptureTemplate(key: "x", name: "", target: .id("journal-id"), template: "* %?"),
177        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %?", options: .init(emptyLines: 1)),
178        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %?", options: .init(emptyLinesBefore: 2, emptyLinesAfter: 1)),
179        CaptureTemplate(key: "x", name: "", target: .file(""), template: "* %?", options: .init(prepend: true, emptyLinesAfter: 1)),
180        CaptureTemplate(key: "x", name: "", kind: .plain, target: .headline(file: "", headline: "Inbox"), template: "%?", options: .init(emptyLines: 1)),
181        CaptureTemplate(key: "x", name: "", kind: .item, target: .file(""), template: "%?", options: .init(emptyLines: 1)),
182    ]
183
184    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
185    func targetsAndEmptyLinesMatchEmacs() throws {
186        var cases: [Case] = []
187        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"]
188        for template in Self.optionTemplates {
189            for file in files {
190                if case .id = template.target, !file.contains("journal-id") { continue }
191                cases.append(Case(file: file, template: template, typed: "Entry"))
192            }
193        }
194        let seconds = 1_789_000_000
195        let emacs = try Self.emacs(cases, seconds: seconds)
196        for (c, expected) in zip(cases, emacs) {
197            let mine = Self.ours(c, now: Date(timeIntervalSince1970: Double(seconds)))
198            #expect(mine == expected, "\(c.template.target) \(c.template.kind) \(c.template.options) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
199        }
200    }
201
202    @Test func fillsPrompts() {
203        let template = "* %^{Title|untitled} for %^{Who}\n%\\1 again"
204        #expect(Capture.questions(template) == [
205            Capture.Question(prompt: "Title", defaultValue: "untitled", choices: []),
206            Capture.Question(prompt: "Who", defaultValue: "", choices: []),
207        ])
208        guard case .success(let filled) = Capture.fill(template, context: CaptureContext(), answers: ["", "me"]) else {
209            Issue.record("fill failed")
210            return
211        }
212        #expect(filled.text == "* untitled for me\nuntitled again\n")
213    }
214}
215
216struct CaptureEscapeTests {
217    /// Templates and the answers to their prompts, in order.
218    static let cases: [(template: String, answers: [String])] = [
219        ("* TODO %^{Task} %^g\n%^{Effort}p%?", ["Call bank", "work:phone", "1:00"]),
220        ("* Meeting %^T\n%^{Who|Ann|Bob} said %\\1, tags %\\*2", ["fri 14:00", ""]),
221        ("* %^{Title} :work:\nSCHEDULED: %^t\n%^u %^U", ["Plan", "+2d", "", "2026-10-01 9:30"]),
222        ("* Link %^L and %^C", ["https://orgmode.org", ""]),
223        ("* %A\n%:annotation %:initial %k%?", ["the page"]),
224        ("\\%a literal and \\\\%a doubled %c", []),
225        ("* Heading %^{Due}t and %^{Seen}U", ["tue", ""]),
226        ("%^{Name}\n- item %^g", ["Bob", "a:b"]),
227        ("* A rather long heading title that goes on %^G", ["x:y"]),
228        ("* Empty tags %^g done", [""]),
229        ("* Prop %^{CATEGORY|home}p\nbody", [""]),
230    ]
231
232    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
233    func fillsLikeOrgCaptureFillTemplate() throws {
234        let seconds = 1_789_000_000
235        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-fill-\(UUID().uuidString)")
236        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
237        defer { try? FileManager.default.removeItem(at: folder) }
238        let forms = Self.cases.map { c in
239            """
240            (let ((answers (list \(c.answers.map(CaptureTests.lisp).joined(separator: " ")))))
241              (cl-letf* ((next (lambda (default) (let ((a (pop answers))) (if (or (null a) (equal a "")) (or default "") a))))
242                         (ord (symbol-function 'org-read-date))
243                         ((symbol-function 'org-completing-read) (lambda (_p _c &optional _a _b _i _h def &rest _) (funcall next def)))
244                         ((symbol-function 'completing-read-multiple) (lambda (&rest _) (split-string (funcall next "") ":" t)))
245                         ((symbol-function 'read-string) (lambda (_p &optional _i _h def &rest _) (funcall next def)))
246                         ((symbol-function 'org-read-property-value) (lambda (_p &optional _e def) (funcall next def)))
247                         ((symbol-function 'org-read-date)
248                          (lambda (&optional with-time to-time _from prompt &rest _)
249                            (let ((a (pop answers))) (funcall ord with-time to-time (if (equal a "") "." a) prompt)))))
250                (with-temp-buffer
251                  (org-mode)
252                  (setq org-capture-plist (list :buffer (current-buffer) :pos 1))
253                  (push (org-capture-fill-template \(CaptureTests.lisp(c.template)) "Selected" "[[file:~/n.org::*Task][Task]]") results))))
254            """
255        }
256        let output = folder.appendingPathComponent("out.json")
257        let script = folder.appendingPathComponent("fill.el")
258        try """
259        ;;; -*- lexical-binding: t -*-
260        (require 'org)
261        (require 'org-capture)
262        (require 'json)
263        (require 'cl-lib)
264        (setq org-adapt-indentation nil)
265        (kill-new "Clip")
266        (defvar results nil)
267        \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
268        (with-temp-file \(CaptureTests.lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
269        """.write(to: script, atomically: true, encoding: .utf8)
270        let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
271        guard FileManager.default.fileExists(atPath: output.path) else { throw EmacsOracle.EvaluateError(log: log) }
272        let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
273        var utc = Calendar(identifier: .gregorian)
274        utc.timeZone = TimeZone(identifier: "UTC")!
275        let context = CaptureContext(now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc, initial: "Selected",
276                                     annotation: "[[file:~/n.org::*Task][Task]]", clipboard: "Clip")
277        for (c, expected) in zip(Self.cases, emacs) {
278            #expect(Capture.questions(c.template, context: context).count == c.answers.count, "\(c.template.debugDescription)")
279            guard case .success(let filled) = Capture.fill(c.template, context: context, answers: c.answers) else {
280                Issue.record("fill failed for \(c.template.debugDescription)")
281                continue
282            }
283            var mine = filled.text
284            if c.template.contains("%?") { mine.insert(contentsOf: "%?", at: String.Index(utf16Offset: filled.cursor, in: mine)) }
285            #expect(mine == expected, "\(c.template.debugDescription)\nours:  \(mine.debugDescription)\nemacs: \(expected.debugDescription)")
286        }
287    }
288}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form