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