Tests/OrgCoreTests/AgendaTests.swift

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