Tests/OrgCoreTests/AgendaTests.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Tests/OrgCoreTests/AgendaTests.swift history · blame · raw

722 lines · 33329 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// Runs `org-agenda-list` over files in `emacs -Q --batch` with the clock frozen.
  6enum AgendaOracle {
  7    struct Line: Codable {
  8        var line: String
  9        var type: String?
 10        var category: String?
 11        var tod: Int?
 12        var extra: String?
 13        var urgency: Int?
 14        var file: String?
 15        var pos: Int?
 16    }
 17
 18    struct Day: Codable {
 19        var header: String
 20        var items: [Line]
 21    }
 22
 23    static let keywords = "TODO PROJ LOOP STRT WAIT HOLD IDEA | DONE KILL"
 24
 25    static func script(files: [String], form: String, seconds: Int) -> String {
 26        let fileList = files.map { "\"\($0)\"" }.joined(separator: " ")
 27        let words = keywords.split(separator: " ").map { "\"\($0)\"" }.joined(separator: " ")
 28        return #"""
 29        ;;; -*- lexical-binding: t -*-
 30        (require 'org)
 31        (require 'org-agenda)
 32        (require 'org-habit)
 33        (require 'json)
 34        (setq org-todo-keywords '((sequence \#(words)))
 35              org-agenda-files '(\#(fileList)))
 36        (add-to-list 'auto-mode-alist '("\\.org_archive\\'" . org-mode))
 37        (defun orgstar-dump ()
 38          (let (days header items)
 39            (goto-char (point-min))
 40            (while (not (eobp))
 41              (let* ((p (line-beginning-position))
 42                     (line (buffer-substring-no-properties p (line-end-position)))
 43                     (hd (get-text-property p 'org-hd-marker)))
 44                (cond
 45                 ((get-text-property p 'org-agenda-date-header)
 46                  (when header (push `((header . ,header) (items . ,(vconcat (nreverse items)))) days))
 47                  (setq header line items nil))
 48                 ((get-text-property p 'org-filter-type))
 49                 ((or header hd)
 50                  (push `((line . ,line)
 51                          (type . ,(get-text-property p 'type))
 52                          (category . ,(get-text-property p 'org-category))
 53                          (tod . ,(get-text-property p 'time-of-day))
 54                          (extra . ,(get-text-property p 'extra))
 55                          (urgency . ,(get-text-property p 'urgency))
 56                          (file . ,(and hd (buffer-file-name (marker-buffer hd))))
 57                          (pos . ,(and hd (marker-position hd))))
 58                        items))))
 59              (forward-line 1))
 60            (when (or header items) (push `((header . ,(or header "")) (items . ,(vconcat (nreverse items)))) days))
 61            (vconcat (nreverse days))))
 62        \#(frozenClock(seconds, """
 63          (progn
 64            \(form)
 65            (let ((result (with-current-buffer org-agenda-buffer-name (orgstar-dump))))
 66              (let ((coding-system-for-write 'utf-8-unix))
 67                (with-temp-file (getenv "ORACLE_OUTPUT")
 68                  (insert (json-encode result))))))
 69        """))
 70        """#
 71    }
 72
 73    static func run(files: [(name: String, text: String)], form: String, today: Int, hour: Int, minute: Int) throws -> [Day] {
 74        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-agenda-\(UUID().uuidString)")
 75        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 76        defer { try? FileManager.default.removeItem(at: folder) }
 77        var paths: [String] = []
 78        for file in files {
 79            let url = folder.appendingPathComponent(file.name)
 80            try file.text.write(to: url, atomically: true, encoding: .utf8)
 81            paths.append(url.resolvingSymlinksInPath().path)
 82        }
 83        let seconds = (today - 719163) * 86400 + hour * 3600 + minute * 60
 84        let scriptURL = folder.appendingPathComponent("agenda.el")
 85        let output = folder.appendingPathComponent("output.json")
 86        try script(files: paths, form: form, seconds: seconds)
 87            .write(to: scriptURL, atomically: true, encoding: .utf8)
 88        let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_OUTPUT": output.path, "TZ": "UTC"])
 89        guard let data = try? Data(contentsOf: output) else { throw OracleError(log: log) }
 90        let days = try JSONDecoder().decode([Day].self, from: data)
 91        // Positions as UTF-16 offsets, files by name.
 92        return days.map { day in
 93            Day(header: day.header, items: day.items.map { line in
 94                var line = line
 95                if let file = line.file, let pos = line.pos, let index = paths.firstIndex(of: URL(fileURLWithPath: file).resolvingSymlinksInPath().path) {
 96                    line.file = files[index].name
 97                    line.pos = EmacsOracle.offset(pos, in: files[index].text)
 98                }
 99                return line
100            })
101        }
102    }
103
104    struct OracleError: Error { let log: String }
105
106    /// Tags realigned to one space, as their column depends on the window.
107    static func normalize(_ line: String) -> String {
108        line.replacingOccurrences(of: "[ \\t]+(:[^ \\t]+:)[ \\t]*$", with: " $1", options: .regularExpression)
109    }
110
111    /// `org-agenda-prefix-format` as Lisp.
112    static func prefixLisp(_ formats: [String: String]) -> String {
113        "'(" + formats.sorted { $0.key < $1.key }.map { "(\($0.key) . \"\($0.value)\")" }.joined(separator: " ") + ")"
114    }
115
116    static func compare(
117        files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30,
118        prefix: [String: String]? = nil, logMode: Bool = false, logItems: Set<String>? = nil, skipIfDone: Bool = false
119    ) throws {
120        let date = Days.date(start)
121        var form = "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))"
122        if let prefix { form = "(let ((org-agenda-prefix-format \(prefixLisp(prefix)))) \(form))" }
123        if logMode { form = "(let ((org-agenda-start-with-log-mode t)) \(form))" }
124        if let logItems { form = "(let ((org-agenda-log-mode-items '(\(logItems.sorted().joined(separator: " "))))) \(form))" }
125        if skipIfDone { form = "(let ((org-agenda-skip-scheduled-if-done t) (org-agenda-skip-deadline-if-done t)) \(form))" }
126        let emacs = try run(files: files, form: form, today: today, hour: hour, minute: minute)
127        let defaults = OrgSettings.default.withTodoKeywords(keywords)!
128        let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) }
129        var options = AgendaOptions.terminal
130        if let prefix { options.prefixFormat = prefix }
131        options.logMode = logMode
132        if let logItems { options.logItems = logItems }
133        options.skipScheduledIfDone = skipIfDone
134        options.skipDeadlineIfDone = skipIfDone
135        let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: options)
136        #expect(ours.count == emacs.count)
137        for (o, e) in zip(ours, emacs) {
138            #expect(o.header == e.header)
139            #expect(describe(o.items, today: today) == describe(e.items), "\(e.header) today \(Days.date(today))")
140        }
141    }
142
143    static func describe(_ items: [Line]) -> [String] {
144        items.map { item in
145            "\(normalize(item.line)) | \(item.type ?? "-") \(item.category ?? "") \(item.tod.map(String.init) ?? "-") [\(item.extra ?? "")] \(item.urgency ?? 0) \(item.file ?? "-")@\(item.pos.map(String.init) ?? "-")"
146        }
147    }
148
149    static func describe(_ items: [AgendaItem], today: Int = 0) -> [String] {
150        items.map { item in
151            let line = item.habit.map { Habit.insertGraph($0.graph(today: today), into: item.line) } ?? item.line
152            let type: String = switch item.kind {
153            case .timeGrid, .currentTime: "-"
154            default: item.tsType
155            }
156            return "\(normalize(line)) | \(type) \(item.category) \(item.timeOfDay.map(String.init) ?? "-") [\(item.extra)] \(item.urgency) \(item.headingOffset == nil ? "-" : item.path ?? "-")@\(item.headingOffset.map(String.init) ?? "-")"
157        }
158    }
159
160    /// A TODO list or tags view: `form` runs it in Emacs, `ours` builds ours from the sources.
161    static func compareList(files: [(name: String, text: String)], form: String, today: Int, settings: (inout OrgSettings) -> Void = { _ in },
162                            _ ours: ([AgendaSource]) -> [AgendaItem]) throws {
163        let emacs = try run(files: files, form: form, today: today, hour: 9, minute: 30)
164        var defaults = OrgSettings.default.withTodoKeywords(keywords)!
165        settings(&defaults)
166        let mine = ours(files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) })
167        #expect(describe(mine) == describe(emacs.first?.items ?? []), "\(form)")
168    }
169}
170
171struct AgendaTests {
172    @Test func days() {
173        #expect(Days.absolute(year: 1970, month: 1, day: 1) == 719163)
174        #expect(Days.absolute(year: 2026, month: 10, day: 5) - Days.absolute(year: 2026, month: 9, day: 30) == 5)
175        #expect(Days.weekday(Days.absolute(year: 2026, month: 10, day: 5)) == 1)
176        #expect(Days.isoWeek(Days.absolute(year: 2026, month: 10, day: 5)) == 41)
177        #expect(Days.isoWeek(Days.absolute(year: 2027, month: 1, day: 1)) == 53)
178        let wednesday = Days.absolute(year: 2026, month: 10, day: 7)
179        #expect(Days.weekStart(wednesday, on: 1) == Days.absolute(year: 2026, month: 10, day: 5))
180        #expect(Days.weekStart(wednesday, on: 0) == Days.absolute(year: 2026, month: 10, day: 4))
181        #expect(Days.weekStart(wednesday, on: 3) == wednesday)
182        #expect(Days.weekStart(wednesday, on: 4) == Days.absolute(year: 2026, month: 10, day: 1))
183        #expect(Days.weekStart(wednesday, on: nil) == wednesday)
184        let d = Days.date(Days.absolute(year: 2024, month: 2, day: 29))
185        #expect(d.year == 2024 && d.month == 2 && d.day == 29)
186        #expect(Days.date(Days.absolute(year: 2026, month: 2, day: 31)) == (2026, 3, 3))
187        #expect(Days.date(Days.absolute(year: 2026, month: 13, day: 1)) == (2027, 1, 1))
188    }
189
190    static let synthetic = """
191    #+TODO: TODO NEXT | DONE
192    #+FILETAGS: :ft:
193    Before the first heading <2026-10-05 Mon>.
194    * TODO [#A] Pay rent :home:
195    SCHEDULED: <2026-10-01 Thu>
196    * Meeting 10:00 with Bob
197    <2026-10-05 Mon 14:00-15:00>
198    * DONE Old
199    DEADLINE: <2026-10-03 Sat>
200    * NEXT Report :work:
201    DEADLINE: <2026-10-12 Mon -3d>
202    * NEXT Soon
203    DEADLINE: <2026-10-09 Fri>
204    * TODO Overdue
205    DEADLINE: <2026-09-20 Sun 08:15>
206    * Trip
207    <2026-10-04 Sun>--<2026-10-07 Wed>
208    * Same day range
209    <2026-10-06 Tue 10:00>--<2026-10-06 Tue 12:30>
210    * Gym
211    <2026-09-01 Tue 07:00 +1w>
212    ** Child
213    :PROPERTIES:
214    :CATEGORY: kid
215    :END:
216    SCHEDULED: <2026-10-06 Tue>
217    *** Grandchild :x:
218    <2026-10-07 Wed 9am>
219    * TODO Water plants
220    SCHEDULED: <2026-09-28 Mon .+2d>
221    * TODO Monthly
222    SCHEDULED: <2026-08-31 Mon +1m>
223    * TODO Yearly
224    DEADLINE: <2025-10-08 Wed +1y>
225    * TODO Delayed
226    SCHEDULED: <2026-10-02 Fri -2d>
227    * Archived :ARCHIVE:
228    SCHEDULED: <2026-10-05 Mon>
229    <2026-10-05 Mon>
230    ** TODO Under archived
231    DEADLINE: <2026-10-05 Mon>
232    * COMMENT Commented
233    DEADLINE: <2026-10-05 Mon>
234    <2026-10-05 Mon>
235    * Blocks
236    #+begin_src sh
237    echo <2026-10-05 Mon>
238    #+end_src
239    # <2026-10-05 Mon>
240    =<2026-10-06 Tue>= and [[https://example.com][<2026-10-06 Tue>]]
241    * [#C] Low priority <2026-10-06 Tue>
242    * TODO Late meeting 23:30
243    SCHEDULED: <2026-10-05 Mon>
244    * Props
245    :PROPERTIES:
246    :WHEN: <2026-10-06 Tue 16:00>
247    :END:
248    * TODO   Spaces   :a:b:
249    <2026-10-06 Tue 11:00>
250    * Ünïcode tïtle :tag:
251    <2026-10-05 Mon 08:00>
252    * Range with times <2026-10-05 Mon 10:00-11:00>
253    * Hourly
254    <2026-10-04 Sun 22:00 +12h>
255    """
256
257    static let second = """
258    #+CATEGORY: other
259    * WAIT Second file
260    DEADLINE: <2026-10-05 Mon>
261    * Two stamps
262    <2026-10-05 Mon 13:00> and <2026-10-06 Tue>
263    """
264
265    static let third = """
266    #+FILETAGS: :proj:
267    * TODO Alpha :work:urgent:
268    :PROPERTIES:
269    :EFFORT: 2:00
270    :SIZE: 3
271    :OWNER: alice
272    :DUE: <2026-10-10 Sat>
273    :END:
274    ** NEXT Beta :boss:
275    :PROPERTIES:
276    :SIZE: 10
277    :END:
278    *** Gamma :work:
279    * DONE Delta :home:
280    CLOSED: [2026-10-01 Thu 10:00] SCHEDULED: <2026-09-30 Wed>
281    * WAIT [#A] Epsilon 10:30
282    :PROPERTIES:
283    :OWNER: Bob
284    :END:
285    <2026-10-03 Sat> [2026-10-02 Fri]
286    * HOLD Zeta :x@y:
287    * Eta with category
288    :PROPERTIES:
289    :CATEGORY: cat
290    :END:
291    ** KILL Theta
292    * IDEA [#C] Iota
293    * Archived :ARCHIVE:work:
294    ** TODO Kappa :work:
295    """
296
297    static let matches = [
298        "work", "+work-urgent", "work|home", "proj", "{^w}", "-work", "LEVEL>1", "LEVEL=2+boss", "SIZE>5", "SIZE<5",
299        "OWNER=\"alice\"", "OWNER={^b}", "OWNER<>\"alice\"", "OWNER<\"b\"", "TODO=\"WAIT\"", "PRIORITY=\"A\"",
300        "CATEGORY=\"cat\"", "DUE<\"<2026-10-15>\"", "DUE>\"<today>\"", "SCHEDULED<\"<today>\"", "TIMESTAMP=\"<2026-10-03 Sat>\"",
301        "ITEM={lph}", "work/TODO", "/!", "+work/!TODO|WAIT", "EFFORT>\"1:00\"", "ALLTAGS={proj}", "TAGS=\":work:urgent:\"",
302        "x@y", "/-TODO", "/!{^[HW]}", "work&urgent", "SIZE>=3+SIZE<=3", "LEVEL<>1",
303        // `org-time<>` is `=` in Org 9.8.7.
304        "DUE<>\"<2026-10-10>\"", "DUE<>\"<2026-10-11>\"", "SCHEDULED<>\"<2026-09-30>\"", "TIMESTAMP!=\"<2026-10-03 Sat>\"",
305        "DEADLINE/=\"<2026-10-05>\"", "DEADLINE<>\"<2026-10-07>\"",
306    ]
307
308    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
309    func listsMatchEmacs() throws {
310        let files = [("a.org", Self.synthetic), ("b.org", Self.second), ("c.org", Self.third)]
311        let today = Days.absolute(year: 2026, month: 10, day: 5)
312        var utc = Calendar(identifier: .gregorian)
313        utc.timeZone = TimeZone(identifier: "UTC")!
314        let now = Date(timeIntervalSince1970: Double((today - 719163) * 86400 + 9 * 3600 + 30 * 60))
315        func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
316        try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
317        for keywords in ["WAIT|HOLD", "DONE", "KILL|TODO"] {
318            try AgendaOracle.compareList(files: files, form: "(org-todo-list \(lisp(keywords)))", today: today) { Agenda.todoList($0, keywords: keywords) }
319        }
320        for match in Self.matches {
321            for todoOnly in [false, true] {
322                try AgendaOracle.compareList(files: files, form: "(org-tags-view \(todoOnly ? "t" : "nil") \(lisp(match)))", today: today) {
323                    Agenda.tagsMatch($0, match: match, todoOnly: todoOnly, now: now, calendar: utc)
324                }
325            }
326        }
327    }
328
329    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
330    func matchesEmacs() throws {
331        let files = [("a.org", Self.synthetic), ("b.org", Self.second)]
332        for today in [(2026, 10, 5), (2026, 10, 1), (2026, 10, 8), (2026, 9, 29)] {
333            let day = Days.absolute(year: today.0, month: today.1, day: today.2)
334            try AgendaOracle.compare(files: files, start: day - 3, span: 10, today: day)
335        }
336        let day = Days.absolute(year: 2026, month: 10, day: 6)
337        try AgendaOracle.compare(files: files, start: day, span: 1, today: day)
338        try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
339    }
340
341    static let doneEntries = """
342        * DONE Scheduled today
343        SCHEDULED: <2026-10-05 Mon>
344        * DONE Due today
345        DEADLINE: <2026-10-05 Mon>
346        * KILL Scheduled earlier
347        SCHEDULED: <2026-10-01 Thu>
348        * DONE Due later
349        DEADLINE: <2026-10-07 Wed>
350        * TODO Still open
351        SCHEDULED: <2026-10-05 Mon> DEADLINE: <2026-10-06 Tue>
352        """
353
354    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
355    func skipsDoneEntriesLikeEmacs() throws {
356        let today = Days.absolute(year: 2026, month: 10, day: 5)
357        for skip in [false, true] {
358            try AgendaOracle.compare(files: [("done.org", Self.doneEntries)], start: today - 4, span: 8, today: today, skipIfDone: skip)
359        }
360    }
361
362    /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
363    /// two dates.
364    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
365    func matchesEmacsOnACorpus() throws {
366        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
367        let files = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
368            .filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
369            .compactMap { url in (try? String(contentsOf: url, encoding: .utf8)).map { (url.lastPathComponent, $0) } }
370        for today in [Days.absolute(Date(), calendar: .current), Days.absolute(year: 2025, month: 3, day: 14)] {
371            try AgendaOracle.compare(files: files, start: today - 3, span: 10, today: today)
372        }
373        let today = Days.absolute(Date(), calendar: .current)
374        try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
375        for match in ["finance|home", "LEVEL=2", "/!", "PRIORITY=\"A\""] {
376            let lisp = "\"" + match.replacingOccurrences(of: "\"", with: "\\\"") + "\""
377            try AgendaOracle.compareList(files: files, form: "(org-tags-view nil \(lisp))", today: today) { Agenda.tagsMatch($0, match: match) }
378        }
379    }
380}
381
382struct ReminderTests {
383    static var utc: Calendar {
384        var calendar = Calendar(identifier: .gregorian)
385        calendar.timeZone = TimeZone(identifier: "UTC")!
386        return calendar
387    }
388
389    static func date(_ day: Int, _ hour: Int, _ minute: Int) -> Date {
390        utc.date(from: DateComponents(year: 2026, month: 10, day: day, hour: hour, minute: minute))!
391    }
392
393    @Test func timedEntriesWithTheirWarnings() {
394        let text = """
395        * TODO Call
396        SCHEDULED: <2026-10-05 Mon 14:00>
397        * Meeting
398        :PROPERTIES:
399        :APPT_WARNTIME: 30
400        :END:
401        <2026-10-06 Tue 10:00-11:00>
402        * DONE Finished
403        SCHEDULED: <2026-10-05 Mon 15:00>
404        * Untimed
405        SCHEDULED: <2026-10-05 Mon>
406        * Earlier
407        <2026-10-05 Mon 08:00>
408        * Soon
409        <2026-10-05 Mon 09:35>
410        * TODO Report due
411        DEADLINE: <2026-10-07 Wed 17:00>
412        """
413        let source = AgendaSource(path: "/n/a.org", text: text)
414        let now = Self.date(5, 9, 30)
415        let reminders = Reminders.upcoming([source], now: now, calendar: Self.utc)
416        #expect(reminders.map(\.title) == ["Soon", "TODO Call", "Meeting", "TODO Report due"])
417        #expect(reminders[0].fireDate == now.addingTimeInterval(1))
418        #expect(reminders[1].fireDate == Self.date(5, 13, 48))
419        #expect(reminders[1].body == "14:00 · Scheduled: · a")
420        #expect(reminders[2].fireDate == Self.date(6, 9, 30))
421        #expect(reminders[3].eventDate == Self.date(7, 17, 0))
422        #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, limit: 2).count == 2)
423        #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, days: 1).map(\.title) == ["Soon", "TODO Call"])
424    }
425
426    @Test func repeatsFillTheWeek() {
427        let source = AgendaSource(path: "/n/a.org", text: "* Standup\n<2026-10-01 Thu 09:00 +1d>\n")
428        let reminders = Reminders.upcoming([source], now: Self.date(5, 9, 30), calendar: Self.utc)
429        #expect(reminders.count == 6)
430        #expect(Set(reminders.map(\.id)).count == 6)
431    }
432}
433
434struct AgendaPrefixFormatTests {
435    static let file = """
436    #+TODO: TODO NEXT | DONE
437    * Projects [1/2] :proj:
438    ** TODO [#A] Write report :work:
439    :PROPERTIES:
440    :Effort:   1:30
441    :END:
442    SCHEDULED: <2026-10-05 Mon 10:00>
443    *** NEXT Outline [[https://x.org][the plan]]
444    DEADLINE: <2026-10-06 Tue>
445    * Errands
446    :PROPERTIES:
447    :CATEGORY: averyverylongcategory
448    :END:
449    ** TODO Groceries 14:00
450    SCHEDULED: <2026-10-05 Mon>
451    """
452
453    static let formats = [
454        "agenda": " %i %-12:c%?-12t%-6e% s%l%b", "todo": " %-8.6c %e %?-4l|", "tags": "%c %?-5:l %b", "search": " %i %-12:c",
455    ]
456
457    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
458    func agendaMatchesEmacs() throws {
459        let today = Days.absolute(year: 2026, month: 10, day: 5)
460        try AgendaOracle.compare(files: [("p.org", Self.file)], start: today, span: 2, today: today, prefix: Self.formats)
461    }
462
463    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
464    func listsMatchEmacs() throws {
465        let today = Days.absolute(year: 2026, month: 10, day: 5)
466        var options = AgendaOptions()
467        options.prefixFormat = Self.formats
468        let lisp = AgendaOracle.prefixLisp(Self.formats)
469        try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-todo-list))", today: today) {
470            Agenda.todoList($0, options: options)
471        }
472        try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-tags-view nil \"work|proj\"))", today: today) {
473            Agenda.tagsMatch($0, match: "work|proj", options: options)
474        }
475    }
476
477    /// `%T` is the last tag: Org's field regexp lists only lower-case keys, but matches it
478    /// under `case-fold-search`.
479    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
480    func lastTagMatchesEmacs() throws {
481        let today = Days.absolute(year: 2026, month: 10, day: 5)
482        let formats = ["agenda": " %-10:c%-8T%?-12t% s", "todo": " %?-6T|", "tags": "%c %-6:T", "search": " %i %-12:c"]
483        try AgendaOracle.compare(files: [("p.org", Self.file)], start: today, span: 2, today: today, prefix: formats)
484        var options = AgendaOptions()
485        options.prefixFormat = formats
486        let lisp = AgendaOracle.prefixLisp(formats)
487        try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-todo-list))", today: today) {
488            Agenda.todoList($0, options: options)
489        }
490        try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-tags-view nil \"work|proj\"))", today: today) {
491            Agenda.tagsMatch($0, match: "work|proj", options: options)
492        }
493    }
494
495    @Test func compilesFields() {
496        let format = PrefixFormat(" %-8.6c|%?-4t%e")
497        #expect(format.render(["c": "category", "e": "1:00"]) == " categ   |1:00")
498        #expect(format.render(["c": "cat", "t": "9:00"]) == " cat     |9:00")
499    }
500}
501
502struct AgendaLogModeTests {
503    static let file = """
504    #+TODO: TODO NEXT | DONE
505    * DONE Ship release :work:
506    CLOSED: [2026-10-05 Mon 16:20] SCHEDULED: <2026-10-05 Mon>
507    :LOGBOOK:
508    - State "DONE"       from "NEXT"       [2026-10-05 Mon 16:20] \\
509      Shipped at last
510    - State "NEXT"       from "TODO"       [2026-10-04 Sun 08:15]
511    CLOCK: [2026-10-05 Mon 14:00]--[2026-10-05 Mon 15:30] =>  1:30
512    - Fixed the build
513    CLOCK: [2026-10-04 Sun 22:00]--[2026-10-05 Mon 01:15] =>  3:15
514    :END:
515    * TODO Writing
516    :LOGBOOK:
517    CLOCK: [2026-10-06 Tue 09:00]--[2026-10-06 Tue 09:45] =>  0:45
518    CLOCK: [2026-10-06 Tue 11:00]
519    :END:
520    ** DONE Draft [1/1]
521    CLOSED: [2026-10-06 Tue]
522    * Archived :ARCHIVE:
523    CLOSED: [2026-10-05 Mon 10:00]
524    * Plain
525    Mentions CLOSED: [2026-10-05 Mon 09:00] in text.
526    """
527
528    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
529    func logModeMatchesEmacs() throws {
530        let today = Days.absolute(year: 2026, month: 10, day: 5)
531        try AgendaOracle.compare(files: [("log.org", Self.file)], start: today - 1, span: 3, today: today, logMode: true)
532        try AgendaOracle.compare(files: [("log.org", Self.file)], start: today - 1, span: 3, today: today, prefix: ["agenda": " %-8:c%?-12t%s %l"], logMode: true)
533        for items: Set<String> in [["closed", "clock", "state"], ["state"], ["closed"]] {
534            try AgendaOracle.compare(files: [("log.org", Self.file)], start: today - 1, span: 3, today: today, logMode: true, logItems: items)
535        }
536    }
537}
538
539struct AgendaFilterTests {
540    static let file = """
541    #+TODO: TODO NEXT | DONE
542    #+CATEGORY: home
543    * TODO Groceries :errand:
544    :PROPERTIES:
545    :Effort:   0:20
546    :END:
547    SCHEDULED: <2026-10-05 Mon>
548    * Work stuff
549    :PROPERTIES:
550    :CATEGORY: work
551    :END:
552    ** TODO Write Report :writing:urgent:
553    :PROPERTIES:
554    :Effort:   2:00
555    :END:
556    SCHEDULED: <2026-10-05 Mon 10:00>
557    ** NEXT Call Bob :phone:
558    DEADLINE: <2026-10-06 Tue>
559    ** TODO Review PR :urgent:
560    :PROPERTIES:
561    :Effort:   1h
562    :END:
563    SCHEDULED: <2026-10-05 Mon>
564    """
565
566    static let filters = ["+urgent", "-urgent", "work", "-work", "+home+work", "<0:30", ">1:00", "=1:00", "/report/", "-/call/", "+work-phone<2:00", "nonexistent", "urgent-writing/review/"]
567
568    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
569    func filtersLikeOrgAgendaFilter() throws {
570        let today = Days.absolute(year: 2026, month: 10, day: 5)
571        let defaults = OrgSettings.default.withTodoKeywords(AgendaOracle.keywords)!
572        let sources = [AgendaSource(path: "f.org", text: Self.file, defaults: defaults)]
573        let days = Agenda.list(sources, start: today, days: 2, today: today, now: (9, 30), options: .terminal)
574        let all = days.flatMap(\.items)
575        let tags = Set(all.flatMap(\.tags))
576        let categories = Set(all.filter { $0.path != nil }.map(\.category))
577        for filterText in Self.filters {
578            let emacs = try AgendaOracle.run(files: [("f.org", Self.file)], form: """
579                (progn
580                  (org-agenda-list nil "2026-10-05" 2)
581                  (with-current-buffer org-agenda-buffer-name
582                    (cl-letf (((symbol-function 'completing-read) (lambda (&rest _) \(lispString(filterText)))))
583                      (org-agenda-filter))))
584                """, today: today, hour: 9, minute: 30)
585            let filter = AgendaFilter().parse(filterText, tags: tags, categories: categories).filter
586            let ours = days.map { day in day.items.filter(filter.keeps) }
587            #expect(ours.map { AgendaOracle.describe($0, today: today) } == emacs.map { AgendaOracle.describe($0.items) }, "\(filterText)")
588        }
589    }
590
591    @Test func parsesAndDescribes() {
592        let (filter, ignored) = AgendaFilter().parse("+work-phone<2:00/rep/ zzz", tags: ["phone"], categories: ["work"])
593        #expect(filter.categories == ["+work"] && filter.tags == ["-phone"] && filter.efforts == ["+<2:00"] && filter.regexps == ["+rep"])
594        #expect(ignored == ["+zzz"])
595        #expect(filter.description == "+work-phone<2:00/rep/")
596        #expect(AgendaFilter.durationMinutes("1h 30min") == 90 && AgendaFilter.durationMinutes("0:45") == 45)
597        let kept = filter.parse("++urgent", tags: ["urgent"], categories: []).filter
598        #expect(kept.tags == ["-phone", "+urgent"])
599    }
600
601    @Test func descriptionRoundTrips() {
602        let tags: Set<String> = ["phone", "urgent"], categories: Set<String> = ["work", "my-cat"]
603        for text in ["-/call/", "-work+phone-<0:10>1:00/a/-/b/", "\"my-cat\"-urgent", "-\"my-cat\""] {
604            let filter = AgendaFilter().parse(text, tags: tags, categories: categories).filter
605            #expect(AgendaFilter().parse(filter.description, tags: tags, categories: categories).filter == filter, "\(text)")
606        }
607        let negative = AgendaFilter().parse("-/call/", tags: [], categories: []).filter
608        #expect(negative.description == "-/call/")
609    }
610}
611
612/// `org-agenda-todo-ignore-*` and `org-agenda-tags-todo-honor-ignore-options`.
613struct TodoIgnoreTests {
614    static let file = """
615    * TODO Sched past
616    SCHEDULED: <2026-10-01 Thu>
617    * TODO Sched today
618    SCHEDULED: <2026-10-05 Mon>
619    * TODO Sched future
620    SCHEDULED: <2026-10-20 Tue>
621    * TODO Deadline near
622    DEADLINE: <2026-10-10 Sat>
623    * TODO Deadline far
624    DEADLINE: <2026-12-01 Tue>
625    * TODO Deadline past
626    DEADLINE: <2026-09-01 Tue>
627    * TODO Deadline then scheduled
628    DEADLINE: <2026-10-06 Tue> SCHEDULED: <2026-10-04 Sun>
629    * TODO Scheduled then deadline
630    SCHEDULED: <2026-10-04 Sun> DEADLINE: <2026-10-06 Tue>
631    * TODO Stamp in heading <2026-11-01 Sun>
632    * TODO Stamp in body
633    Meeting <2026-09-20 Sun>
634    * TODO Inactive only [2026-10-01 Thu]
635    * TODO None :work:
636    * TODO Long warning :work:
637    DEADLINE: <2026-10-30 Fri -30d>
638
639    """
640
641    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
642    func ignoresLikeOrg() throws {
643        let today = Days.absolute(year: 2026, month: 10, day: 5)
644        let files = [("i.org", Self.file)]
645        let settings: [(String, String, (inout AgendaOptions) -> Void)] = [
646            ("org-agenda-todo-ignore-with-date", "t", { $0.todoIgnoreWithDate = true }),
647        ] + ["t", "all", "future", "past", "3", "-3"].map { v in
648            ("org-agenda-todo-ignore-scheduled", v.first!.isNumber || v.first == "-" ? v : "'" + v, { $0.todoIgnoreScheduled = AgendaOptions.TodoIgnore(v)! })
649        } + ["t", "near", "far", "all", "future", "past", "10", "-10"].map { v in
650            ("org-agenda-todo-ignore-deadlines", v.first!.isNumber || v.first == "-" ? v : "'" + v, { $0.todoIgnoreDeadlines = AgendaOptions.TodoIgnore(v, deadlines: true)! })
651        } + ["t", "future", "past", "20"].map { v in
652            ("org-agenda-todo-ignore-timestamp", v.first!.isNumber ? v : "'" + v, { $0.todoIgnoreTimestamp = AgendaOptions.TodoIgnore(v)! })
653        }
654        for (name, value, set) in settings {
655            var options = AgendaOptions()
656            set(&options)
657            try AgendaOracle.compareList(files: files, form: "(let ((\(name) \(value))) (org-todo-list nil))", today: today) {
658                Agenda.todoList($0, options: options, today: today)
659            }
660        }
661        // TODO-only matches honor them only when asked.
662        var utc = Calendar(identifier: .gregorian)
663        utc.timeZone = TimeZone(identifier: "UTC")!
664        let now = Date(timeIntervalSince1970: Double((today - 719163) * 86400 + 9 * 3600 + 30 * 60))
665        for honor in [false, true] {
666            var options = AgendaOptions()
667            options.todoIgnoreDeadlines = .all
668            options.tagsTodoHonorIgnoreOptions = honor
669            try AgendaOracle.compareList(
670                files: files,
671                form: "(let ((org-agenda-todo-ignore-deadlines 'all) (org-agenda-tags-todo-honor-ignore-options \(honor ? "t" : "nil"))) (org-tags-view t \"work\"))",
672                today: today
673            ) { Agenda.tagsMatch($0, match: "work", todoOnly: true, now: now, calendar: utc, options: options) }
674        }
675    }
676}
677
678/// `org-use-tag-inheritance` and `org-tags-exclude-from-inheritance` in tag matches.
679struct TagInheritanceTests {
680    static let file = """
681    #+FILETAGS: :ft:
682    * Project :work:proj:@office:
683    ** TODO Child :home:
684    *** TODO Grandchild
685    * Other :@home:
686    ** TODO Under other
687
688    """
689
690    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
691    func inheritsLikeOrg() throws {
692        let today = Days.absolute(year: 2026, month: 10, day: 5)
693        let cases: [(String, String, SemanticSettings.TagInheritance, Set<String>)] = [
694            ("t", "nil", .all, []),
695            ("nil", "nil", .none, []),
696            ("'(\"work\" \"ft\")", "nil", .only(["work", "ft"]), []),
697            ("\"^@\"", "nil", .matching("^@"), []),
698            ("t", "'(\"proj\" \"ft\")", .all, ["proj", "ft"]),
699            ("\"^[a-z]\"", "'(\"proj\")", .matching("^[a-z]"), ["proj"]),
700        ]
701        for (inherit, exclude, mode, excluded) in cases {
702            for match in ["work", "proj", "ft", "@office|@home", "home"] {
703                try AgendaOracle.compareList(
704                    files: [("t.org", Self.file)],
705                    form: "(let ((org-use-tag-inheritance \(inherit)) (org-tags-exclude-from-inheritance \(exclude))) (org-tags-view nil \"\(match)\"))",
706                    today: today,
707                    settings: { $0.tagInheritance = mode; $0.tagsExcludedFromInheritance = excluded }
708                ) { Agenda.tagsMatch($0, match: match) }
709            }
710        }
711    }
712
713    @Test func tagAlistOffersFastKeys() {
714        let text = "* Task\n"
715        var options = EditingOptions.org
716        options.tagAlist = "work(w) home(h)\n{ @office(o) @home(H) }"
717        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2], options: options)
718        guard case .prompt(let prompt) = SetTags().run(in: context) else { Issue.record("no prompt"); return }
719        #expect(prompt.fast?.items.contains(.option(key: "w", name: "work")) == true)
720        #expect(prompt.fast?.items.contains(.option(key: "H", name: "@home")) == true)
721    }
722}