Tests/OrgCoreTests/AgendaTests.swift
475 lines · 20817 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 ((or header hd)
49 (push `((line . ,line)
50 (type . ,(get-text-property p 'type))
51 (category . ,(get-text-property p 'org-category))
52 (tod . ,(get-text-property p 'time-of-day))
53 (extra . ,(get-text-property p 'extra))
54 (urgency . ,(get-text-property p 'urgency))
55 (file . ,(and hd (buffer-file-name (marker-buffer hd))))
56 (pos . ,(and hd (marker-position hd))))
57 items))))
58 (forward-line 1))
59 (when (or header items) (push `((header . ,(or header "")) (items . ,(vconcat (nreverse items)))) days))
60 (vconcat (nreverse days))))
61 \#(frozenClock(seconds, """
62 (progn
63 \(form)
64 (let ((result (with-current-buffer org-agenda-buffer-name (orgstar-dump))))
65 (let ((coding-system-for-write 'utf-8-unix))
66 (with-temp-file (getenv "ORACLE_OUTPUT")
67 (insert (json-encode result))))))
68 """))
69 """#
70 }
71
72 static func run(files: [(name: String, text: String)], form: String, today: Int, hour: Int, minute: Int) throws -> [Day] {
73 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-agenda-\(UUID().uuidString)")
74 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
75 defer { try? FileManager.default.removeItem(at: folder) }
76 var paths: [String] = []
77 for file in files {
78 let url = folder.appendingPathComponent(file.name)
79 try file.text.write(to: url, atomically: true, encoding: .utf8)
80 paths.append(url.resolvingSymlinksInPath().path)
81 }
82 let seconds = (today - 719163) * 86400 + hour * 3600 + minute * 60
83 let scriptURL = folder.appendingPathComponent("agenda.el")
84 let output = folder.appendingPathComponent("output.json")
85 try script(files: paths, form: form, seconds: seconds)
86 .write(to: scriptURL, atomically: true, encoding: .utf8)
87 let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_OUTPUT": output.path, "TZ": "UTC"])
88 guard let data = try? Data(contentsOf: output) else { throw OracleError(log: log) }
89 let days = try JSONDecoder().decode([Day].self, from: data)
90 // Positions as UTF-16 offsets, files by name.
91 return days.map { day in
92 Day(header: day.header, items: day.items.map { line in
93 var line = line
94 if let file = line.file, let pos = line.pos, let index = paths.firstIndex(of: URL(fileURLWithPath: file).resolvingSymlinksInPath().path) {
95 line.file = files[index].name
96 line.pos = EmacsOracle.offset(pos, in: files[index].text)
97 }
98 return line
99 })
100 }
101 }
102
103 struct OracleError: Error { let log: String }
104
105 /// Tags realigned to one space, as their column depends on the window.
106 static func normalize(_ line: String) -> String {
107 line.replacingOccurrences(of: "[ \\t]+(:[^ \\t]+:)[ \\t]*$", with: " $1", options: .regularExpression)
108 }
109
110 /// `org-agenda-prefix-format` as Lisp.
111 static func prefixLisp(_ formats: [String: String]) -> String {
112 "'(" + formats.sorted { $0.key < $1.key }.map { "(\($0.key) . \"\($0.value)\")" }.joined(separator: " ") + ")"
113 }
114
115 static func compare(
116 files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30,
117 prefix: [String: String]? = nil, logMode: Bool = false
118 ) throws {
119 let date = Days.date(start)
120 var form = "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))"
121 if let prefix { form = "(let ((org-agenda-prefix-format \(prefixLisp(prefix)))) \(form))" }
122 if logMode { form = "(let ((org-agenda-start-with-log-mode t)) \(form))" }
123 let emacs = try run(files: files, form: form, today: today, hour: hour, minute: minute)
124 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
125 let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) }
126 var options = AgendaOptions.terminal
127 if let prefix { options.prefixFormat = prefix }
128 options.logMode = logMode
129 let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: options)
130 #expect(ours.count == emacs.count)
131 for (o, e) in zip(ours, emacs) {
132 #expect(o.header == e.header)
133 #expect(describe(o.items, today: today) == describe(e.items), "\(e.header) today \(Days.date(today))")
134 }
135 }
136
137 static func describe(_ items: [Line]) -> [String] {
138 items.map { item in
139 "\(normalize(item.line)) | \(item.type ?? "-") \(item.category ?? "") \(item.tod.map(String.init) ?? "-") [\(item.extra ?? "")] \(item.urgency ?? 0) \(item.file ?? "-")@\(item.pos.map(String.init) ?? "-")"
140 }
141 }
142
143 static func describe(_ items: [AgendaItem], today: Int = 0) -> [String] {
144 items.map { item in
145 let line = item.habit.map { Habit.insertGraph($0.graph(today: today), into: item.line) } ?? item.line
146 let type: String = switch item.kind {
147 case .timeGrid, .currentTime: "-"
148 default: item.kind.rawValue
149 }
150 return "\(normalize(line)) | \(type) \(item.category) \(item.timeOfDay.map(String.init) ?? "-") [\(item.extra)] \(item.urgency) \(item.path ?? "-")@\(item.headingOffset.map(String.init) ?? "-")"
151 }
152 }
153
154 /// A TODO list or tags view: `form` runs it in Emacs, `ours` builds ours from the sources.
155 static func compareList(files: [(name: String, text: String)], form: String, today: Int, _ ours: ([AgendaSource]) -> [AgendaItem]) throws {
156 let emacs = try run(files: files, form: form, today: today, hour: 9, minute: 30)
157 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
158 let mine = ours(files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) })
159 #expect(describe(mine) == describe(emacs.first?.items ?? []), "\(form)")
160 }
161}
162
163struct AgendaTests {
164 @Test func days() {
165 #expect(Days.absolute(year: 1970, month: 1, day: 1) == 719163)
166 #expect(Days.absolute(year: 2026, month: 10, day: 5) - Days.absolute(year: 2026, month: 9, day: 30) == 5)
167 #expect(Days.weekday(Days.absolute(year: 2026, month: 10, day: 5)) == 1)
168 #expect(Days.isoWeek(Days.absolute(year: 2026, month: 10, day: 5)) == 41)
169 #expect(Days.isoWeek(Days.absolute(year: 2027, month: 1, day: 1)) == 53)
170 let d = Days.date(Days.absolute(year: 2024, month: 2, day: 29))
171 #expect(d.year == 2024 && d.month == 2 && d.day == 29)
172 #expect(Days.date(Days.absolute(year: 2026, month: 2, day: 31)) == (2026, 3, 3))
173 #expect(Days.date(Days.absolute(year: 2026, month: 13, day: 1)) == (2027, 1, 1))
174 }
175
176 static let synthetic = """
177 #+TODO: TODO NEXT | DONE
178 #+FILETAGS: :ft:
179 Before the first heading <2026-10-05 Mon>.
180 * TODO [#A] Pay rent :home:
181 SCHEDULED: <2026-10-01 Thu>
182 * Meeting 10:00 with Bob
183 <2026-10-05 Mon 14:00-15:00>
184 * DONE Old
185 DEADLINE: <2026-10-03 Sat>
186 * NEXT Report :work:
187 DEADLINE: <2026-10-12 Mon -3d>
188 * NEXT Soon
189 DEADLINE: <2026-10-09 Fri>
190 * TODO Overdue
191 DEADLINE: <2026-09-20 Sun 08:15>
192 * Trip
193 <2026-10-04 Sun>--<2026-10-07 Wed>
194 * Same day range
195 <2026-10-06 Tue 10:00>--<2026-10-06 Tue 12:30>
196 * Gym
197 <2026-09-01 Tue 07:00 +1w>
198 ** Child
199 :PROPERTIES:
200 :CATEGORY: kid
201 :END:
202 SCHEDULED: <2026-10-06 Tue>
203 *** Grandchild :x:
204 <2026-10-07 Wed 9am>
205 * TODO Water plants
206 SCHEDULED: <2026-09-28 Mon .+2d>
207 * TODO Monthly
208 SCHEDULED: <2026-08-31 Mon +1m>
209 * TODO Yearly
210 DEADLINE: <2025-10-08 Wed +1y>
211 * TODO Delayed
212 SCHEDULED: <2026-10-02 Fri -2d>
213 * Archived :ARCHIVE:
214 SCHEDULED: <2026-10-05 Mon>
215 <2026-10-05 Mon>
216 ** TODO Under archived
217 DEADLINE: <2026-10-05 Mon>
218 * COMMENT Commented
219 DEADLINE: <2026-10-05 Mon>
220 <2026-10-05 Mon>
221 * Blocks
222 #+begin_src sh
223 echo <2026-10-05 Mon>
224 #+end_src
225 # <2026-10-05 Mon>
226 =<2026-10-06 Tue>= and [[https://example.com][<2026-10-06 Tue>]]
227 * [#C] Low priority <2026-10-06 Tue>
228 * TODO Late meeting 23:30
229 SCHEDULED: <2026-10-05 Mon>
230 * Props
231 :PROPERTIES:
232 :WHEN: <2026-10-06 Tue 16:00>
233 :END:
234 * TODO Spaces :a:b:
235 <2026-10-06 Tue 11:00>
236 * Ünïcode tïtle :tag:
237 <2026-10-05 Mon 08:00>
238 * Range with times <2026-10-05 Mon 10:00-11:00>
239 * Hourly
240 <2026-10-04 Sun 22:00 +12h>
241 """
242
243 static let second = """
244 #+CATEGORY: other
245 * WAIT Second file
246 DEADLINE: <2026-10-05 Mon>
247 * Two stamps
248 <2026-10-05 Mon 13:00> and <2026-10-06 Tue>
249 """
250
251 static let third = """
252 #+FILETAGS: :proj:
253 * TODO Alpha :work:urgent:
254 :PROPERTIES:
255 :EFFORT: 2:00
256 :SIZE: 3
257 :OWNER: alice
258 :DUE: <2026-10-10 Sat>
259 :END:
260 ** NEXT Beta :boss:
261 :PROPERTIES:
262 :SIZE: 10
263 :END:
264 *** Gamma :work:
265 * DONE Delta :home:
266 CLOSED: [2026-10-01 Thu 10:00] SCHEDULED: <2026-09-30 Wed>
267 * WAIT [#A] Epsilon 10:30
268 :PROPERTIES:
269 :OWNER: Bob
270 :END:
271 <2026-10-03 Sat> [2026-10-02 Fri]
272 * HOLD Zeta :x@y:
273 * Eta with category
274 :PROPERTIES:
275 :CATEGORY: cat
276 :END:
277 ** KILL Theta
278 * IDEA [#C] Iota
279 * Archived :ARCHIVE:work:
280 ** TODO Kappa :work:
281 """
282
283 static let matches = [
284 "work", "+work-urgent", "work|home", "proj", "{^w}", "-work", "LEVEL>1", "LEVEL=2+boss", "SIZE>5", "SIZE<5",
285 "OWNER=\"alice\"", "OWNER={^b}", "OWNER<>\"alice\"", "OWNER<\"b\"", "TODO=\"WAIT\"", "PRIORITY=\"A\"",
286 "CATEGORY=\"cat\"", "DUE<\"<2026-10-15>\"", "DUE>\"<today>\"", "SCHEDULED<\"<today>\"", "TIMESTAMP=\"<2026-10-03 Sat>\"",
287 "ITEM={lph}", "work/TODO", "/!", "+work/!TODO|WAIT", "EFFORT>\"1:00\"", "ALLTAGS={proj}", "TAGS=\":work:urgent:\"",
288 "x@y", "/-TODO", "/!{^[HW]}", "work&urgent", "SIZE>=3+SIZE<=3", "LEVEL<>1",
289 ]
290
291 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
292 func listsMatchEmacs() throws {
293 let files = [("a.org", Self.synthetic), ("b.org", Self.second), ("c.org", Self.third)]
294 let today = Days.absolute(year: 2026, month: 10, day: 5)
295 var utc = Calendar(identifier: .gregorian)
296 utc.timeZone = TimeZone(identifier: "UTC")!
297 let now = Date(timeIntervalSince1970: Double((today - 719163) * 86400 + 9 * 3600 + 30 * 60))
298 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
299 try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
300 for keywords in ["WAIT|HOLD", "DONE", "KILL|TODO"] {
301 try AgendaOracle.compareList(files: files, form: "(org-todo-list \(lisp(keywords)))", today: today) { Agenda.todoList($0, keywords: keywords) }
302 }
303 for match in Self.matches {
304 for todoOnly in [false, true] {
305 try AgendaOracle.compareList(files: files, form: "(org-tags-view \(todoOnly ? "t" : "nil") \(lisp(match)))", today: today) {
306 Agenda.tagsMatch($0, match: match, todoOnly: todoOnly, now: now, calendar: utc)
307 }
308 }
309 }
310 }
311
312 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
313 func matchesEmacs() throws {
314 let files = [("a.org", Self.synthetic), ("b.org", Self.second)]
315 for today in [(2026, 10, 5), (2026, 10, 1), (2026, 10, 8), (2026, 9, 29)] {
316 let day = Days.absolute(year: today.0, month: today.1, day: today.2)
317 try AgendaOracle.compare(files: files, start: day - 3, span: 10, today: day)
318 }
319 let day = Days.absolute(year: 2026, month: 10, day: 6)
320 try AgendaOracle.compare(files: files, start: day, span: 1, today: day)
321 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
322 }
323
324 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
325 /// two dates.
326 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
327 func matchesEmacsOnACorpus() throws {
328 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
329 let files = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
330 .filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
331 .compactMap { url in (try? String(contentsOf: url, encoding: .utf8)).map { (url.lastPathComponent, $0) } }
332 for today in [Days.absolute(Date(), calendar: .current), Days.absolute(year: 2025, month: 3, day: 14)] {
333 try AgendaOracle.compare(files: files, start: today - 3, span: 10, today: today)
334 }
335 let today = Days.absolute(Date(), calendar: .current)
336 try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
337 for match in ["finance|home", "LEVEL=2", "/!", "PRIORITY=\"A\""] {
338 let lisp = "\"" + match.replacingOccurrences(of: "\"", with: "\\\"") + "\""
339 try AgendaOracle.compareList(files: files, form: "(org-tags-view nil \(lisp))", today: today) { Agenda.tagsMatch($0, match: match) }
340 }
341 }
342}
343
344struct ReminderTests {
345 static var utc: Calendar {
346 var calendar = Calendar(identifier: .gregorian)
347 calendar.timeZone = TimeZone(identifier: "UTC")!
348 return calendar
349 }
350
351 static func date(_ day: Int, _ hour: Int, _ minute: Int) -> Date {
352 utc.date(from: DateComponents(year: 2026, month: 10, day: day, hour: hour, minute: minute))!
353 }
354
355 @Test func timedEntriesWithTheirWarnings() {
356 let text = """
357 * TODO Call
358 SCHEDULED: <2026-10-05 Mon 14:00>
359 * Meeting
360 :PROPERTIES:
361 :APPT_WARNTIME: 30
362 :END:
363 <2026-10-06 Tue 10:00-11:00>
364 * DONE Finished
365 SCHEDULED: <2026-10-05 Mon 15:00>
366 * Untimed
367 SCHEDULED: <2026-10-05 Mon>
368 * Earlier
369 <2026-10-05 Mon 08:00>
370 * Soon
371 <2026-10-05 Mon 09:35>
372 * TODO Report due
373 DEADLINE: <2026-10-07 Wed 17:00>
374 """
375 let source = AgendaSource(path: "/n/a.org", text: text)
376 let now = Self.date(5, 9, 30)
377 let reminders = Reminders.upcoming([source], now: now, calendar: Self.utc)
378 #expect(reminders.map(\.title) == ["Soon", "TODO Call", "Meeting", "TODO Report due"])
379 #expect(reminders[0].fireDate == now.addingTimeInterval(1))
380 #expect(reminders[1].fireDate == Self.date(5, 13, 48))
381 #expect(reminders[1].body == "14:00 · Scheduled: · a")
382 #expect(reminders[2].fireDate == Self.date(6, 9, 30))
383 #expect(reminders[3].eventDate == Self.date(7, 17, 0))
384 #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, limit: 2).count == 2)
385 #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, days: 1).map(\.title) == ["Soon", "TODO Call"])
386 }
387
388 @Test func repeatsFillTheWeek() {
389 let source = AgendaSource(path: "/n/a.org", text: "* Standup\n<2026-10-01 Thu 09:00 +1d>\n")
390 let reminders = Reminders.upcoming([source], now: Self.date(5, 9, 30), calendar: Self.utc)
391 #expect(reminders.count == 6)
392 #expect(Set(reminders.map(\.id)).count == 6)
393 }
394}
395
396struct AgendaPrefixFormatTests {
397 static let file = """
398 #+TODO: TODO NEXT | DONE
399 * Projects [1/2] :proj:
400 ** TODO [#A] Write report :work:
401 :PROPERTIES:
402 :Effort: 1:30
403 :END:
404 SCHEDULED: <2026-10-05 Mon 10:00>
405 *** NEXT Outline [[https://x.org][the plan]]
406 DEADLINE: <2026-10-06 Tue>
407 * Errands
408 :PROPERTIES:
409 :CATEGORY: averyverylongcategory
410 :END:
411 ** TODO Groceries 14:00
412 SCHEDULED: <2026-10-05 Mon>
413 """
414
415 static let formats = [
416 "agenda": " %i %-12:c%?-12t%-6e% s%l%b", "todo": " %-8.6c %e %?-4l|", "tags": "%c %?-5:l %b", "search": " %i %-12:c",
417 ]
418
419 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
420 func agendaMatchesEmacs() throws {
421 let today = Days.absolute(year: 2026, month: 10, day: 5)
422 try AgendaOracle.compare(files: [("p.org", Self.file)], start: today, span: 2, today: today, prefix: Self.formats)
423 }
424
425 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
426 func listsMatchEmacs() throws {
427 let today = Days.absolute(year: 2026, month: 10, day: 5)
428 var options = AgendaOptions()
429 options.prefixFormat = Self.formats
430 let lisp = AgendaOracle.prefixLisp(Self.formats)
431 try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-todo-list))", today: today) {
432 Agenda.todoList($0, options: options)
433 }
434 try AgendaOracle.compareList(files: [("p.org", Self.file)], form: "(let ((org-agenda-prefix-format \(lisp))) (org-tags-view nil \"work|proj\"))", today: today) {
435 Agenda.tagsMatch($0, match: "work|proj", options: options)
436 }
437 }
438
439 @Test func compilesFields() {
440 let format = PrefixFormat(" %-8.6c|%?-4t%e")
441 #expect(format.render(["c": "category", "e": "1:00"]) == " categ |1:00")
442 #expect(format.render(["c": "cat", "t": "9:00"]) == " cat |9:00")
443 }
444}
445
446struct AgendaLogModeTests {
447 static let file = """
448 #+TODO: TODO NEXT | DONE
449 * DONE Ship release :work:
450 CLOSED: [2026-10-05 Mon 16:20] SCHEDULED: <2026-10-05 Mon>
451 :LOGBOOK:
452 CLOCK: [2026-10-05 Mon 14:00]--[2026-10-05 Mon 15:30] => 1:30
453 - Fixed the build
454 CLOCK: [2026-10-04 Sun 22:00]--[2026-10-05 Mon 01:15] => 3:15
455 :END:
456 * TODO Writing
457 :LOGBOOK:
458 CLOCK: [2026-10-06 Tue 09:00]--[2026-10-06 Tue 09:45] => 0:45
459 CLOCK: [2026-10-06 Tue 11:00]
460 :END:
461 ** DONE Draft [1/1]
462 CLOSED: [2026-10-06 Tue]
463 * Archived :ARCHIVE:
464 CLOSED: [2026-10-05 Mon 10:00]
465 * Plain
466 Mentions CLOSED: [2026-10-05 Mon 09:00] in text.
467 """
468
469 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
470 func logModeMatchesEmacs() throws {
471 let today = Days.absolute(year: 2026, month: 10, day: 5)
472 try AgendaOracle.compare(files: [("log.org", Self.file)], start: today - 1, span: 3, today: today, logMode: true)
473 try AgendaOracle.compare(files: [("log.org", Self.file)], start: today - 1, span: 3, today: today, prefix: ["agenda": " %-8:c%?-12t%s %l"], logMode: true)
474 }
475}