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