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