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