Tests/OrgAppTests/AppTests.swift
1364 lines · 70227 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5import Testing
6@testable import OrgApp
7
8/// A temporary folder that removes itself.
9final class Folder {
10 let url: URL
11
12 init() throws {
13 url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL
14 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
15 }
16
17 deinit {
18 try? FileManager.default.removeItem(at: url)
19 }
20
21 @discardableResult
22 func write(_ path: String, _ text: String) throws -> URL {
23 let file = url.appendingPathComponent(path)
24 try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
25 try Data(text.utf8).write(to: file)
26 return file.standardizedFileURL
27 }
28}
29
30struct FileTreeTests {
31 @Test func foldersFirstThenFiles() {
32 let files = ["b.org", "a/z.org", "a/y.org", "c.sync-conflict-1.org", "a2.org"].map {
33 FileEntry(path: "/r/" + $0, root: "/r", kind: $0.contains("conflict") ? .conflict : .org)
34 }
35 let tree = FileTreeNode.build(root: "/r", files: files)
36 #expect(tree.children?.map(\.name) == ["a", "a2.org", "b.org", "c.sync-conflict-1.org"])
37 #expect(tree.children?[0].children?.map(\.name) == ["y.org", "z.org"])
38 #expect(tree.children?[1].children == nil)
39 }
40
41 @Test func fuzzyMatching() {
42 #expect(FuzzyMatch.score("wn", "work/notes.org") != nil)
43 #expect(FuzzyMatch.score("xyz", "work/notes.org") == nil)
44 let files = ["work/notes.org", "notes.org", "personal/wine.org"].map { FileEntry(path: "/r/" + $0, root: "/r", kind: .org) }
45 #expect(FuzzyMatch.rank("notes", files).map(\.relativePath) == ["notes.org", "work/notes.org"])
46 #expect(FuzzyMatch.rank("", files).count == 3)
47 }
48}
49
50@MainActor
51struct WorkspaceModelTests {
52 @Test func addSearchRemoveAndPersist() async throws {
53 let notes = try Folder()
54 let support = try Folder()
55 try notes.write("a.org", "* Groceries\nbuy apples\n")
56 try notes.write("sub/b.org", "* Taxes\n")
57 try notes.write("c.sync-conflict-1.org", "* Taxes copy\n")
58
59 let model = try WorkspaceModel(directory: support.url)
60 try await model.addRoot(notes.url)
61 #expect(model.files.count == 3)
62 #expect(model.search("apples").map(\.title) == ["Groceries"])
63 #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
64 let root = try #require(model.rootPaths.first)
65 #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
66
67 let reopened = try WorkspaceModel(directory: support.url)
68 #expect(reopened.roots.count == 1)
69 #expect(reopened.files.count == 3)
70
71 try reopened.removeRoot(path: root)
72 #expect(reopened.roots.isEmpty)
73 #expect(reopened.files.isEmpty)
74 #expect(reopened.search("apples").isEmpty)
75 }
76
77 @Test func aMovedFolderLeavesNoOldRows() async throws {
78 let parent = try Folder()
79 let original = parent.url.appendingPathComponent("notes")
80 try FileManager.default.createDirectory(at: original, withIntermediateDirectories: true)
81 try "* Plumber\n".write(to: original.appendingPathComponent("a.org"), atomically: true, encoding: .utf8)
82 let data = parent.url.appendingPathComponent("data")
83 let model = try WorkspaceModel(directory: data)
84 try await model.addRoot(original)
85 #expect(model.search("plumber").count == 1)
86
87 let moved = parent.url.appendingPathComponent("moved")
88 try FileManager.default.moveItem(at: original, to: moved)
89 let reopened = try WorkspaceModel(directory: data)
90 await reopened.refresh()
91 let found = reopened.search("plumber").map(\.path)
92 #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
93 // Adding it again, under its new path, adds nothing.
94 try await reopened.addRoot(moved)
95 #expect(reopened.roots.count == 1)
96 }
97
98 @Test func listsDownloadsInTheTree() {
99 let files = [FileEntry(path: "/r/a.org", root: "/r", kind: .org)]
100 let tree = FileTreeNode.build(root: "/r", files: files, downloading: ["/r/b.org", "/r/sub/c.org"])
101 #expect(tree.children?.map(\.name) == ["sub", "a.org", "b.org"])
102 #expect(tree.children?[2].isDownloading == true && tree.children?[2].file == nil)
103 #expect(tree.children?[0].children?.map(\.name) == ["c.org"])
104 }
105
106 @Test func findsBacklinks() async throws {
107 let notes = try Folder()
108 try notes.write("a.org", "* Sink\n:PROPERTIES:\n:ID: s-1\n:CUSTOM_ID: sink\n:END:\nsee [[*Taps]]\n* Taps\n")
109 try notes.write("b.org", "* Plumbing\n[[id:s-1][the sink]] and [[file:a.org]]\n* Other\n[[file:a.org::#sink]] [[https://x.org]]\n")
110 // Links before the first heading come from the file itself.
111 try notes.write("c.org", "#+TITLE: C\nAbout [[file:a.org::*Sink]] and [[file:a.org]].\n* Later\n")
112 let model = try WorkspaceModel(directory: nil)
113 try await model.addRoot(notes.url)
114 let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
115 let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
116 let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
117 #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
118 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
119 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
120 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
121 // Each with the line its link is on, the link as it reads.
122 #expect(model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
123 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
124 let fromC = try #require(model.backlinks(to: sink).last)
125 #expect(fromC == .file(c, contentHash: fromC.contentHash))
126 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
127 session.show(fromC)
128 #expect(session.path == c && session.revealRequest?.offset == 0)
129 }
130
131 @Test func createRenameAndTrashFiles() async throws {
132 let notes = try Folder()
133 try notes.write("a.org", "* Alpha\n")
134 let model = try WorkspaceModel(directory: nil)
135 model.trasher = { try FileManager.default.removeItem(at: $0) }
136 try await model.addRoot(notes.url)
137 let root = try #require(model.rootPaths.first)
138
139 let created = try await model.createFile(named: "projects/plan", in: root)
140 #expect(created == root + "/projects/plan.org")
141 #expect(model.files.map(\.path).contains(created))
142 await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
143 await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
144
145 let renamed = try await model.rename(created, to: "roadmap.org")
146 #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
147 let folder = try await model.rename(root + "/projects", to: "work")
148 #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
149
150 try await model.trash(folder + "/roadmap.org")
151 #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
152 #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
153 #expect(model.search("alpha").count == 1)
154 }
155
156 /// Watching starts with no folders (a first launch); a folder added afterwards is
157 /// watched.
158 @Test func foldersAddedLaterAreWatched() async throws {
159 let notes = try Folder()
160 let model = try WorkspaceModel(directory: nil)
161 model.startWatching()
162 try await model.addRoot(notes.url)
163 let file = try notes.write("new.org", "* Fresh heading\n")
164 var found = false
165 for _ in 0..<40 where !found {
166 try await Task.sleep(for: .milliseconds(100))
167 found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
168 }
169 #expect(found)
170 }
171
172 @Test func changedFilesAreReindexed() async throws {
173 let notes = try Folder()
174 let file = try notes.write("a.org", "* Old\n")
175 let model = try WorkspaceModel(directory: nil)
176 try await model.addRoot(notes.url)
177 try notes.write("a.org", "* New\n")
178 await model.filesChanged([file], rescan: [])
179 #expect(model.search("new").count == 1)
180 #expect(model.changedFile?.path == file.path)
181 }
182}
183
184@MainActor
185struct DocumentSessionTests {
186 @Test func openShowAndReload() throws {
187 let notes = try Folder()
188 let file = try notes.write("a.org", "* One\n* Two\n")
189 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
190 session.open(file.path)
191 #expect(session.outline.map(\.title) == ["One", "Two"])
192
193 let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
194 session.show(location)
195 #expect(session.revealRequest?.offset == 6)
196
197 try notes.write("a.org", "intro\n* One\n* Two\n")
198 session.fileChanged(file.path)
199 #expect(session.outline.map(\.start) == [6, 12])
200 session.show(location)
201 #expect(session.revealRequest?.offset == 12)
202 }
203
204 @Test func sameFileByAnotherPathSharesItsBuffer() throws {
205 let notes = try Folder()
206 let file = try notes.write("a.org", "* One\n")
207 let link = notes.url.appendingPathComponent("link")
208 try FileManager.default.createSymbolicLink(at: link, withDestinationURL: notes.url)
209 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
210 session.open(file.path)
211 session.open(link.appendingPathComponent("a.org").path)
212 #expect(session.openPaths == [file.path])
213 #expect(session.path == file.path)
214 }
215
216 @Test func buffersOfTheSameNameShowTheirFolders() throws {
217 let notes = try Folder()
218 let a = try notes.write("x/blog/index.org", "a\n")
219 let b = try notes.write("y/blog/index.org", "b\n")
220 let c = try notes.write("y/other.org", "c\n")
221 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
222 session.open(a.path)
223 #expect(session.bufferName(a.path) == "index.org")
224 session.open(b.path)
225 session.open(c.path)
226 #expect(session.bufferName(a.path) == "index.org<x/blog>")
227 #expect(session.bufferName(b.path) == "index.org<y/blog>")
228 #expect(session.bufferName(c.path) == "other.org")
229 }
230
231 @Test func openReadsSetupFiles() throws {
232 let notes = try Folder()
233 try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
234 let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
235 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
236 session.open(file.path)
237 #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
238 }
239
240
241 @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
242 let notes = try Folder()
243 try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
244 let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
245 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
246 session.open(file.path)
247 #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == false)
248 try notes.write("setup.org", "#+TODO: NEXT WAIT | DONE\n")
249 let text = session.document!.text
250 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
251 guard case .commit(let result) = CtrlCCtrlC().run(in: context) else { Issue.record("no commit"); return }
252 #expect(result.effects.contains(.refreshSetup))
253 session.refreshSetup()
254 #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
255 #expect(session.document?.isDirty == false)
256 }
257
258 @Test func reloadingFromDiskReadsSetupFilesAgain() throws {
259 let notes = try Folder()
260 try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
261 let file = try notes.write("a.org", "* WAIT One\n")
262 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
263 session.open(file.path)
264 try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
265 try notes.write("setup.org", "#+TODO: WAIT | DONE\n")
266 session.fileChanged(file.path)
267 #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
268 }
269
270 @Test func missingFileReportsAnError() {
271 let session = DocumentSession()
272 session.open("/nonexistent/a.org")
273 #expect(session.lastError != nil)
274 #expect(session.document == nil)
275 }
276}
277
278@MainActor
279struct SessionSavingTests {
280 let notes: Folder
281 let file: URL
282 let recovery: FileRecoveryStore
283 let session: DocumentSession
284
285 init() throws {
286 notes = try Folder()
287 file = try notes.write("a.org", "a\nb\nc\n")
288 recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
289 session = DocumentSession(recovery: recovery)
290 session.saveMode = .explicit
291 session.open(file.path)
292 }
293
294 /// Types `text` at `offset`, as the editor would.
295 func type(_ text: String, at offset: Int) throws {
296 let buffer = StateBuffer(session.document!)
297 session.attach(buffer)
298 try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
299 session.bufferChanged()
300 }
301
302 var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
303
304 @Test func saveWritesAndClearsDirty() throws {
305 try type("x", at: 0)
306 #expect(session.isDirty)
307 #expect(session.save())
308 #expect(!session.isDirty)
309 #expect(disk == "xa\nb\nc\n")
310 }
311
312 @Test func automaticModeSavesAfterTheDelay() async throws {
313 session.saveMode = .automatic
314 session.autosaveDelay = .milliseconds(10)
315 try type("x", at: 0)
316 #expect(disk == "a\nb\nc\n")
317 await session.autosave?.value
318 #expect(disk == "xa\nb\nc\n")
319 #expect(!session.isDirty)
320 }
321
322 @Test func explicitModeWaitsForSave() throws {
323 try type("x", at: 0)
324 #expect(session.autosave == nil)
325 }
326
327 @Test func externalChangeMergesIntoEdits() throws {
328 try type("x", at: 0)
329 try notes.write("a.org", "a\nb\nC\n")
330 session.fileChanged(file.path)
331 #expect(session.document?.text == "xa\nb\nC\n")
332 #expect(session.conflict == nil)
333 #expect(session.save())
334 #expect(disk == "xa\nb\nC\n")
335 }
336
337 @Test func conflictKeepMine() throws {
338 try type("x", at: 0)
339 try notes.write("a.org", "z\nb\nc\n")
340 session.fileChanged(file.path)
341 #expect(session.conflict != nil)
342 #expect(!session.save())
343 #expect(disk == "z\nb\nc\n")
344 session.keepMine()
345 #expect(session.conflict == nil)
346 #expect(disk == "xa\nb\nc\n")
347 let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
348 #expect(kept.contains("z\nb\nc\n"))
349 }
350
351 @Test func conflictUseDiskVersion() throws {
352 try type("x", at: 0)
353 try notes.write("a.org", "z\nb\nc\n")
354 #expect(!session.save())
355 #expect(session.conflict != nil)
356 session.useDiskVersion()
357 #expect(session.conflict == nil)
358 #expect(!session.isDirty)
359 #expect(session.document?.text == "z\nb\nc\n")
360 let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
361 #expect(kept.contains("xa\nb\nc\n"))
362 }
363
364 @Test func searchSeesUnsavedHeadings() async throws {
365 let workspace = try WorkspaceModel(directory: nil)
366 try await workspace.addRoot(notes.url)
367 try type("* Unsaved heading\n", at: 0)
368 let overlay = workspace.overlay(path: session.path, document: session.document)
369 #expect(workspace.search("unsaved").isEmpty)
370 #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
371 }
372}
373
374@MainActor
375struct KeymapLoaderTests {
376 @Test func layersTheUserFile() throws {
377 let folder = try Folder()
378 let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
379 #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
380
381 let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
382 let loaded = KeymapLoader.load(.emacs, userFile: file)
383 #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
384 #expect(loaded.problems == ["line 4: bad or missing keys"])
385
386 let broken = try folder.write("broken.toml", "keys = \"x")
387 #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
388 }
389}
390
391@MainActor
392struct MoveSubtreeTests {
393 @Test func refileWithinAndAcrossFiles() async throws {
394 let notes = try Folder()
395 let file = try notes.write("a.org", "* one\nbody\n* two\n")
396 let other = try notes.write("b.org", "* inbox\n")
397 let workspace = try WorkspaceModel(directory: nil)
398 try await workspace.addRoot(notes.url)
399 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
400 session.saveMode = .explicit
401 session.open(file.path)
402 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
403 #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
404
405 #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
406 #expect(session.document?.text == "* two\n** one\nbody\n")
407
408 let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
409 StateBufferCaret.set(session, 6)
410 #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
411 #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
412 #expect(session.document?.text == "* two\n")
413 }
414
415 @Test func copyLeavesTheSubtree() async throws {
416 let notes = try Folder()
417 let file = try notes.write("a.org", "* one\nbody\n* two\n")
418 let other = try notes.write("b.org", "* inbox\n")
419 let workspace = try WorkspaceModel(directory: nil)
420 try await workspace.addRoot(notes.url)
421 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
422 session.saveMode = .explicit
423 session.open(file.path)
424 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
425 #expect(session.refile(to: targets[2], keep: true) == "Copied to a.org/two")
426 #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
427
428 let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
429 StateBufferCaret.set(session, 0)
430 #expect(session.refile(to: inbox, keep: true) == "Copied to b.org/inbox")
431 #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
432 #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
433 }
434
435 @Test func archiveToTheArchiveFile() throws {
436 let notes = try Folder()
437 let file = try notes.write("a.org", "* done\n* keep\n")
438 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
439 session.saveMode = .explicit
440 session.open(file.path)
441 #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
442 #expect(session.document?.text == "* keep\n")
443 let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
444 #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
445 }
446}
447
448@MainActor
449struct AgendaActionTests {
450 /// From the agenda: entries in files that aren't open move and archive on disk, and the
451 /// current buffer stays as it was.
452 @Test func refileAndArchiveFromAnEntry() async throws {
453 let notes = try Folder()
454 let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
455 let other = try notes.write("b.org", "* inbox\n")
456 let shown = try notes.write("c.org", "* shown\n")
457 let workspace = try WorkspaceModel(directory: nil)
458 try await workspace.addRoot(notes.url)
459 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
460 session.saveMode = .explicit
461 session.open(shown.path)
462
463 let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
464 #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
465 #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
466 #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
467
468 let text = try String(contentsOf: file, encoding: .utf8)
469 let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
470 #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
471 #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
472
473 #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
474 #expect(try String(contentsOf: file, encoding: .utf8) == "")
475 #expect(session.path == shown.path && session.document?.text == "* shown\n")
476 }
477
478 @Test func locatesMovedHeadings() throws {
479 let notes = try Folder()
480 let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
481 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
482 #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
483 #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
484 #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
485 #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
486 }
487}
488
489@MainActor
490struct MoveIntoOpenBufferTests {
491 /// A target open with unsaved edits above its heading takes the subtree in its buffer,
492 /// under the right heading, and the disk keeps the saved text.
493 @Test func refileIntoAnOpenBuffer() async throws {
494 let notes = try Folder()
495 let file = try notes.write("a.org", "* task\nbody\n")
496 let other = try notes.write("b.org", "* inbox\n* projects\n")
497 let workspace = try WorkspaceModel(directory: nil)
498 try await workspace.addRoot(notes.url)
499 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
500 session.saveMode = .explicit
501 session.open(other.path)
502 let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
503 _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
504 session.open(file.path)
505 #expect(session.refile(to: projects) == "Refiled to b.org/projects")
506 #expect(session.document?.text == "")
507 #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
508 #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
509 }
510
511 @Test func archiveIntoAnOpenBuffer() throws {
512 let notes = try Folder()
513 let file = try notes.write("a.org", "* done\n* keep\n")
514 let archive = try notes.write("a.org_archive", "* old\n")
515 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
516 session.saveMode = .explicit
517 session.open(archive.path)
518 session.open(file.path)
519 #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
520 #expect(session.document?.text == "* keep\n")
521 let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
522 #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
523 #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
524 }
525}
526
527/// Inserts text at the caret, for tests.
528struct InsertText: OrgCommand {
529 let text: String
530 var id: String { "test.insert" }
531 var title: String { "Insert" }
532 func applies(in context: EditContext) -> Bool { true }
533 func run(in context: EditContext) -> CommandStep {
534 .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
535 }
536}
537
538/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
539@MainActor
540enum StateBufferCaret {
541 static func set(_ session: DocumentSession, _ offset: Int) {
542 let buffer = StateBuffer(session.document!)
543 buffer.selection = [offset..<offset]
544 session.attach(buffer)
545 }
546}
547
548@MainActor
549struct AgendaModelTests {
550 @Test func openBuffersFollowTheirText() async throws {
551 let notes = try Folder()
552 let file = try notes.write("a.org", "* TODO One\n")
553 let model = try WorkspaceModel(directory: nil)
554 try await model.addRoot(notes.url)
555 let agenda = AgendaModel(workspace: model)
556 agenda.mode = .todo(keywords: nil)
557 for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
558 await agenda.refresh(open: [file.path: text])
559 #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
560 }
561 await agenda.refresh(open: [:])
562 #expect(agenda.list.map(\.text) == ["TODO One"])
563 }
564
565 @Test func entriesKnowTheirDoneKeyword() async throws {
566 let notes = try Folder()
567 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
568 try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
569 let plain = try notes.write("b.org", "* WAIT Two\n")
570 let model = try WorkspaceModel(directory: nil)
571 model.settings = .with(todoKeywords: try #require(OrgSettings.default.withTodoKeywords("WAIT | OK")))
572 try await model.addRoot(notes.url)
573 let agenda = AgendaModel(workspace: model)
574 agenda.mode = .todo(keywords: nil)
575 await agenda.refresh(open: [:])
576 #expect(Dictionary(uniqueKeysWithValues: agenda.list.map { ($0.todo ?? "", $0.doneKeyword) }) == ["NEXT": "FINISHED", "WAIT": "OK"])
577 await agenda.refresh(open: [plain.path: "#+TODO: WAIT | GONE\n* WAIT Two\n"])
578 #expect(agenda.list.first { $0.todo == "WAIT" }?.doneKeyword == "GONE")
579 }
580
581 @Test func topLevelFilesAndTheOpenBuffer() async throws {
582 let notes = try Folder()
583 try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
584 try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
585 try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
586 let model = try WorkspaceModel(directory: nil)
587 try await model.addRoot(notes.url)
588 let agenda = AgendaModel(workspace: model)
589 agenda.startOffset = -3
590 var utc = Calendar(identifier: .gregorian)
591 utc.timeZone = TimeZone(identifier: "UTC")!
592 let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
593
594 await agenda.refresh(open: [:], now: now, calendar: utc)
595 #expect(agenda.days.count == 10)
596 #expect(agenda.days[3].isToday)
597 #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
598
599 agenda.includeSubfolders = true
600 await agenda.refresh(open: [:], now: now, calendar: utc)
601 #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
602
603 let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
604 await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
605 #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
606
607 agenda.shift(forward: true, now: now, calendar: utc)
608 await agenda.refresh(open: [:], now: now, calendar: utc)
609 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
610
611 // org-agenda-start-on-weekday: a week starts on Monday by default, from a Wednesday.
612 let wednesday = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 7, hour: 9)))
613 agenda.showToday()
614 agenda.span = 7
615 agenda.startOffset = 0
616 await agenda.refresh(open: [:], now: wednesday, calendar: utc)
617 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 5))
618 agenda.startOnWeekday = 0
619 await agenda.refresh(open: [:], now: wednesday, calendar: utc)
620 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 4))
621 agenda.shift(forward: true, now: wednesday, calendar: utc)
622 await agenda.refresh(open: [:], now: wednesday, calendar: utc)
623 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 11))
624 agenda.showToday()
625 agenda.startOnWeekday = nil
626 await agenda.refresh(open: [:], now: wednesday, calendar: utc)
627 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
628 agenda.startOnWeekday = 1
629 agenda.span = 10
630 await agenda.refresh(open: [:], now: wednesday, calendar: utc)
631 #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
632 }
633
634 @Test func leavesOutArchiveFiles() async throws {
635 let notes = try Folder()
636 try notes.write("todo.org", "#+ARCHIVE: todo_archive.org::* %s\n* TODO Live\nSCHEDULED: <2026-10-05 Mon>\n")
637 try notes.write("todo_archive.org", "* DONE Old\nSCHEDULED: <2026-10-05 Mon>\n")
638 try notes.write("work.org", "* Project\n:PROPERTIES:\n:ARCHIVE: done/work.org::\n:END:\n** TODO Task\nSCHEDULED: <2026-10-05 Mon>\n")
639 try notes.write("self.org", "#+ARCHIVE: ::* Archived\n* TODO Mine\nSCHEDULED: <2026-10-05 Mon>\n")
640 try notes.write("done/work.org", "* DONE Older\nSCHEDULED: <2026-10-05 Mon>\n")
641 let model = try WorkspaceModel(directory: nil)
642 try await model.addRoot(notes.url)
643 let agenda = AgendaModel(workspace: model)
644 agenda.includeSubfolders = true
645 agenda.span = 1
646 var utc = Calendar(identifier: .gregorian)
647 utc.timeZone = TimeZone(identifier: "UTC")!
648 let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
649
650 agenda.excludeArchives = false
651 await agenda.refresh(open: [:], now: now, calendar: utc)
652 #expect(Set(agenda.days[0].items.map(\.text)) == ["TODO Live", "DONE Old", "TODO Task", "TODO Mine", "DONE Older"])
653 agenda.excludeArchives = true
654 await agenda.refresh(open: [:], now: now, calendar: utc)
655 #expect(Set(agenda.days[0].items.map(\.text)) == ["TODO Live", "TODO Task", "TODO Mine"])
656 }
657
658 @Test func leavesOutHiddenFoldersAndTagsReminders() async throws {
659 let work = try Folder()
660 let home = try Folder()
661 try work.write("work.org", "* TODO Report\nSCHEDULED: <2026-10-05 Mon 14:00>\n")
662 try home.write("home.org", "* TODO Groceries\nSCHEDULED: <2026-10-05 Mon 15:00>\n")
663 let model = try WorkspaceModel(directory: nil)
664 try await model.addRoot(work.url)
665 try await model.addRoot(home.url)
666 let workRoot = try #require(model.files.first { $0.name == "work.org" }?.root)
667 let agenda = AgendaModel(workspace: model)
668 agenda.span = 1
669 var utc = Calendar(identifier: .gregorian)
670 utc.timeZone = TimeZone(identifier: "UTC")!
671 let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
672
673 agenda.hiddenFolders = [workRoot]
674 await agenda.refresh(open: [:], now: now, calendar: utc)
675 #expect(agenda.days[0].items.filter { $0.path != nil }.map(\.title) == ["Groceries"])
676
677 // Reminders keep hidden folders' entries and carry their folder for Focus filters.
678 let reminders = await AgendaModel(workspace: model).reminders(open: [:], now: now, calendar: utc)
679 #expect(Set(reminders.map(\.title)) == ["Report", "Groceries"])
680 #expect(reminders.first { $0.title == "Report" }?.folder == workRoot)
681 }
682
683 @Test func hiddenFoldersPersistAndMatchPaths() {
684 let defaults = UserDefaults(suiteName: "hidden-\(UUID().uuidString)")!
685 let folders = HiddenFolders(defaults: defaults)
686 folders.manual = ["/a"]
687 folders.focus = ["/b"]
688 let reloaded = HiddenFolders(defaults: defaults)
689 #expect(reloaded.all == ["/a", "/b"])
690 #expect(HiddenFolders.hides(["/a"], path: "/a/x.org"))
691 #expect(!HiddenFolders.hides(["/a"], path: "/ab/x.org"))
692 let predicate = HiddenFolders.notificationPredicate(hiding: ["/a"])
693 #expect(!predicate.evaluate(with: "/a"))
694 #expect(predicate.evaluate(with: "/b"))
695 }
696}
697
698@MainActor
699struct AgendaCommandTests {
700 @Test func loadsViews() throws {
701 let folder = try Folder()
702 let file = try folder.write("views.toml", """
703 [[view]]
704 name = "Work"
705 type = "match"
706 match = "+work"
707 [[view]]
708 name = "Week"
709 span = 7
710 start = -1
711 [[view]]
712 name = "Waiting"
713 type = "todo"
714 keywords = "WAIT|HOLD"
715 [[view]]
716 name = "Broken"
717 type = "match"
718 """)
719 let loaded = AgendaViewLoader.load(userFile: file)
720 #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Stuck Projects", "Work", "Week", "Waiting"])
721 #expect(loaded.views[3].mode == .match("+work", todoOnly: false))
722 #expect(loaded.views[4].mode == .agenda(span: 7, startOffset: -1))
723 #expect(loaded.views[5].mode == .todo(keywords: "WAIT|HOLD"))
724 #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
725 }
726
727 @Test func viewsSortAndPrefixThemselves() async throws {
728 let notes = try Folder()
729 try notes.write("a.org", "* TODO b\n:PROPERTIES:\n:Effort: 0:30\n:END:\n* TODO [#A] c\n* TODO a\n")
730 let file = try notes.write("views.toml", """
731 [[view]]
732 name = "Alphabetical"
733 type = "todo"
734 sorting-strategy = "alpha-up bogus"
735 prefix-format = "%e"
736 """)
737 let loaded = AgendaViewLoader.load(userFile: file)
738 #expect(loaded.problems == ["views.toml line 1: unknown sorting key bogus"])
739 #expect(loaded.views[3].settings == AgendaViewSettings(prefixFormat: "%e", sortingStrategy: ["alpha-up"]))
740 let model = try WorkspaceModel(directory: nil)
741 try await model.addRoot(notes.url)
742 let agenda = AgendaModel(workspace: model)
743 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
744 agenda.mode = .todo(keywords: nil)
745 await agenda.refresh(open: [:])
746 // `alpha-up` keeps the priority cookie, as Org does.
747 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO a", "TODO b"])
748 #expect(agenda.list.map(\.prefixDetail) == [nil, nil, "0:30"])
749 agenda.mode = .todo(keywords: "TODO")
750 await agenda.refresh(open: [:])
751 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO b", "TODO a"])
752 }
753
754 @Test func stuckProjectViews() async throws {
755 let notes = try Folder()
756 try notes.write("a.org", "* Projects\n** Website\n*** TODO Draft\n** Garden\n*** WAIT Seeds\n")
757 let file = try notes.write("views.toml", """
758 [[view]]
759 name = "Stuck"
760 type = "stuck"
761 [[view]]
762 name = "Waiting counts"
763 type = "stuck"
764 keywords = "TODO WAIT"
765 """)
766 let loaded = AgendaViewLoader.load(userFile: file)
767 #expect(loaded.problems.isEmpty)
768 #expect(loaded.views[3].mode == .stuck(nil))
769 guard case .stuck(let definition?) = loaded.views[4].mode else { Issue.record("no definition"); return }
770 #expect(definition.todo == ["TODO", "WAIT"] && definition.match == "+LEVEL=2/-DONE")
771 let model = try WorkspaceModel(directory: nil)
772 try await model.addRoot(notes.url)
773 let agenda = AgendaModel(workspace: model)
774 agenda.mode = loaded.views[3].mode
775 await agenda.refresh(open: [:])
776 #expect(agenda.list.map(\.text) == ["Garden"])
777 agenda.mode = loaded.views[4].mode
778 await agenda.refresh(open: [:])
779 #expect(agenda.list.isEmpty)
780 }
781
782 @Test func blockViews() async throws {
783 let notes = try Folder()
784 let today = Days.date(Days.absolute(Date(), calendar: .current))
785 let stamp = String(format: "%04d-%02d-%02d", today.year, today.month, today.day)
786 try notes.write("a.org", "#+TODO: TODO NEXT WAIT | DONE\n* TODO Call\nSCHEDULED: <\(stamp)>\n* NEXT Write\n* WAIT Hear back\n* TODO Later :someday:\n")
787 let file = try notes.write("views.toml", """
788 [[view]]
789 name = "Daily"
790 span = 1
791 sorting-strategy = "alpha-up"
792 [[view.block]]
793 type = "agenda"
794 header = "Today"
795 [[view.block]]
796 type = "todo"
797 skip-entry-if = "'scheduled 'regexp \\"someday\\""
798 [[view.block]]
799 type = "match"
800 match = "TODO=\\"WAIT\\""
801 [[view]]
802 name = "Broken skip"
803 type = "todo"
804 skip-entry-if = "'level 2"
805 """)
806 let loaded = AgendaViewLoader.load(userFile: file)
807 #expect(loaded.problems == ["views.toml line 14: skip-entry-if: level isn't supported"])
808 guard case .blocks(let blocks) = loaded.views.last!.mode else { Issue.record("no blocks"); return }
809 #expect(blocks.map(\.mode) == [.agenda(span: 1, startOffset: nil), .todo(keywords: nil), .match("TODO=\"WAIT\"", todoOnly: false)])
810 #expect(blocks.map(\.settings.header) == ["Today", nil, nil])
811 #expect(blocks.allSatisfy { $0.settings.sortingStrategy == ["alpha-up"] })
812 #expect(blocks[1].settings.skip == AgendaSkip(subtree: false, conditions: [.scheduled, .regexp("someday")]))
813 let model = try WorkspaceModel(directory: nil)
814 try await model.addRoot(notes.url)
815 let agenda = AgendaModel(workspace: model)
816 agenda.mode = loaded.views.last!.mode
817 await agenda.refresh(open: [:])
818 #expect(agenda.blocks.map(\.header) == ["Today", "TODO items: all", "Entries matching TODO=\"WAIT\""])
819 #expect(agenda.blocks[0].days.count == 1 && agenda.blocks[0].days[0].items.contains { $0.text == "TODO Call" })
820 #expect(agenda.blocks[1].list.map(\.text) == ["WAIT Hear back", "NEXT Write"])
821 #expect(agenda.blocks[2].list.map(\.text) == ["WAIT Hear back"])
822 #expect(agenda.list.isEmpty && agenda.days.isEmpty)
823 }
824
825 @Test func agendaFilesList() async throws {
826 let notes = try Folder()
827 try notes.write("a.org", "* TODO A\n")
828 try notes.write("b.org", "* TODO B\n")
829 try notes.write(".hidden.org", "* TODO Hidden\n")
830 try notes.write("sub/c.org", "* TODO C\n")
831 try notes.write("sub/d.org", "* TODO D\n")
832 try notes.write("sub/notes.txt", "x\n")
833 try notes.write("list", "sub/d.org\n\n b.org\nmissing.org\nsub/notes.txt\n")
834 let root = notes.url.path
835 #expect(AgendaFiles.resolve(["sub"], base: root) == ["\(root)/sub/c.org", "\(root)/sub/d.org"])
836 #expect(AgendaFiles.resolve([root, "sub/c.org"], base: nil) == ["\(root)/a.org", "\(root)/b.org"])
837 #expect(AgendaFiles.resolve(["list", "a.org"], base: root) == ["\(root)/sub/d.org", "\(root)/b.org", "\(root)/sub/notes.txt", "\(root)/a.org"])
838 let model = try WorkspaceModel(directory: nil)
839 try await model.addRoot(notes.url)
840 let agenda = AgendaModel(workspace: model)
841 agenda.agendaFiles = ["sub/c.org", "b.org"]
842 agenda.mode = .todo(keywords: nil)
843 await agenda.refresh(open: [:])
844 #expect(agenda.list.map(\.text) == ["TODO C", "TODO B"])
845 }
846
847 @Test func todoListMode() async throws {
848 let notes = try Folder()
849 try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
850 let model = try WorkspaceModel(directory: nil)
851 try await model.addRoot(notes.url)
852 let agenda = AgendaModel(workspace: model)
853 agenda.mode = .todo(keywords: nil)
854 await agenda.refresh(open: [:])
855 #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
856 agenda.mode = .match("work", todoOnly: false)
857 await agenda.refresh(open: [:])
858 #expect(agenda.list.map(\.text) == ["TODO One"])
859 }
860
861 @Test func runsCommandsOnClosedAndOpenFiles() throws {
862 let notes = try Folder()
863 let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
864 let b = try notes.write("b.org", "* TODO Three\n")
865 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
866 session.open(a.path)
867
868 // A closed file is changed on disk.
869 let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
870 guard case .commit = closed else { Issue.record("\(closed)"); return }
871 #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
872
873 // The open file changes in its buffer.
874 let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
875 guard case .commit = open else { Issue.record("\(open)"); return }
876 #expect(session.document?.text == "* TODO One\n* DONE Two\n")
877
878 // A heading that moved is refused.
879 let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
880 guard case .failed = stale else { Issue.record("\(stale)"); return }
881 #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
882 }
883}
884
885final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
886 private let lock = NSLock()
887 private var pending: [String] = ["someone.else"]
888 var authorized = true
889 private(set) var added: [String] = []
890
891 func authorize() async -> Bool { authorized }
892 func pendingIDs() async -> [String] { lock.withLock { pending } }
893 var delivered: [String] = []
894 func deliveredIDs() async -> [String] { lock.withLock { delivered } }
895 /// The system showing a notification: no longer pending.
896 func fire(_ id: String, keep: Bool) {
897 lock.withLock {
898 pending.removeAll { $0 == id }
899 if keep { delivered.append(id) }
900 }
901 }
902 func add(_ reminder: Reminder) async throws {
903 lock.withLock {
904 pending.append(reminder.id)
905 added.append(reminder.id)
906 }
907 }
908 func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
909 var ids: [String] { lock.withLock { pending } }
910}
911
912@MainActor
913struct ReminderSchedulerTests {
914 func reminder(_ id: String, _ minutes: Double) -> Reminder {
915 let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
916 return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
917 }
918
919 @Test func reconciles() async {
920 let center = FakeReminderCenter()
921 let scheduler = ReminderScheduler(center: center)
922 await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
923 #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
924 #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
925
926 await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
927 #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
928 #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
929
930 await scheduler.clear()
931 #expect(center.ids == ["someone.else"])
932 #expect(scheduler.scheduledThrough == nil)
933
934 // Fired reminders aren't set again, whether or not they're still in Notification Center.
935 await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
936 center.fire("orgstar.e", keep: false)
937 await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
938 #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
939 let relaunched = ReminderScheduler(center: center)
940 center.fire("orgstar.f", keep: true)
941 await relaunched.reconcile([reminder("f", 6)])
942 #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
943 await scheduler.clear()
944
945 center.authorized = false
946 await scheduler.reconcile([reminder("d", 4)])
947 #expect(!scheduler.isAuthorized)
948 #expect(center.ids == ["someone.else"])
949 }
950}
951
952/// Without `DocumentSession.programs`, only Emacs Lisp runs, natively.
953@MainActor
954struct NativeProgramsTests {
955 @Test func runsOnlyNativeBlocksWithoutARunner() async throws {
956 #expect(DocumentSession.runner == nil)
957 let notes = try Folder()
958 let file = try notes.write("b.org", "#+begin_src sh\necho hi\n#+end_src\n\n#+begin_src emacs-lisp\n(+ 1 2)\n#+end_src\n")
959 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
960 session.open(file.path)
961 guard case .external(.babel(let sh)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil),
962 case .external(.babel(let lisp)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 40, expect: nil) else {
963 Issue.record("not planned")
964 return
965 }
966 #if os(macOS)
967 #expect(await session.runBabel(sh) == "sh blocks don't run in this version of orgstar.")
968 #expect(await session.recalculateInEmacs(table: 0..<1, point: 0, form: "") == "Tables that need Emacs aren't recalculated in this version of orgstar.")
969 #endif
970 #expect(await session.runBabel(lisp) == "Code block evaluation complete.")
971 #expect(session.document?.text.hasSuffix("#+RESULTS:\n: 3\n") == true)
972 }
973}
974
975@MainActor
976struct CaptureAppTests {
977 @Test func loadsTemplates() throws {
978 let folder = try Folder()
979 let file = try folder.write("capture.toml", """
980 [[template]]
981 key = "w"
982 name = "Work"
983 file = "work.org"
984 olp = "Projects/Work"
985 template = "* TODO %?\\n%a"
986 [[template]]
987 key = "j"
988 type = "plain"
989 file = "~/journal.org"
990 template = "%U %?"
991 prepend = true
992 """)
993 let loaded = CaptureTemplates.load(userFile: file)
994 #expect(loaded.problems.isEmpty)
995 #expect(loaded.templates.map(\.key) == ["w", "j"])
996 #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
997 #expect(loaded.templates[0].template == "* TODO %?\n%a")
998 #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
999 try """
1000 [[template]]
1001 key = "d"
1002 file = "journal.org"
1003 datetree = true
1004 olp = "Journal"
1005 tree-type = "month"
1006 template = "* %?"
1007 empty-lines-after = 1
1008 jump-to-captured = true
1009 [[template]]
1010 key = "i"
1011 id = "abc"
1012 template = "* %?"
1013 clock-in = true
1014 clock-resume = true
1015 [[template]]
1016 key = "k"
1017 clock = true
1018 type = "item"
1019 template = "%?"
1020 immediate-finish = true
1021 """.write(to: file, atomically: true, encoding: .utf8)
1022 let targets = CaptureTemplates.load(userFile: file)
1023 #expect(targets.problems.isEmpty)
1024 #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
1025 #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
1026 #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
1027 #expect(targets.templates[2].options.immediateFinish)
1028 #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
1029 }
1030
1031 @Test func loadsGroupsRegexpsAndTreeTypes() throws {
1032 let folder = try Folder()
1033 let file = try folder.write("capture.toml", """
1034 [[template]]
1035 key = "t"
1036 name = "Todo"
1037 file = "todo.org"
1038 template = "* TODO %?"
1039 [[template]]
1040 key = "w"
1041 name = "Work"
1042 [[template]]
1043 key = "wm"
1044 name = "Meeting"
1045 file = "work.org"
1046 regexp = "^\\\\* Meetings"
1047 template = "* %?"
1048 [[template]]
1049 key = "wq"
1050 name = "Quarter"
1051 file = "work.org"
1052 datetree = true
1053 tree-type = "year quarter"
1054 time-prompt = true
1055 template = "* %?"
1056 [[template]]
1057 key = "xy"
1058 name = "Ungrouped"
1059 file = "x.org"
1060 template = "* %?"
1061 """)
1062 let loaded = CaptureTemplates.load(userFile: file)
1063 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
1064 #expect(loaded.groups == [CaptureGroup(key: "w", name: "Work")])
1065 #expect(loaded.templates.map(\.key) == ["t", "wm", "wq", "xy"])
1066 #expect(loaded.templates[1].target == .regexp(file: "work.org", regexp: "^\\* Meetings"))
1067 #expect(loaded.templates[2].target == .datetree(file: "work.org", path: [], tree: CaptureTemplate.TreeType(groups: [.year, .quarter])))
1068 #expect(loaded.templates[2].asksTreeDate && !loaded.templates[0].asksTreeDate)
1069 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "").map(\.key) == ["t", "w", "xy"])
1070 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "w").map(\.key) == ["wm", "wq"])
1071 #expect(CaptureTemplates.label(loaded.templates[1], groups: loaded.groups) == "Work › Meeting")
1072 try "[[template]]\nkey = \"d\"\nfile = \"j.org\"\ndatetree = true\ntree-type = \"year fortnight\"\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
1073 #expect(CaptureTemplates.load(userFile: file).problems.count == 1)
1074 }
1075
1076 @Test func treeDateFollowsOrgCapture() {
1077 var calendar = Calendar(identifier: .gregorian)
1078 calendar.timeZone = TimeZone(identifier: "UTC")!
1079 let now = calendar.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 7, minute: 6, second: 27))!
1080 func text(_ date: Date) -> String {
1081 let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
1082 return String(format: "%04d-%02d-%02d %02d:%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!)
1083 }
1084 #expect(text(Capture.treeDate("", now: now, calendar: calendar)) == "2026-10-11 07:06")
1085 #expect(text(Capture.treeDate("fri", now: now, calendar: calendar)) == "2026-10-16 00:00")
1086 #expect(text(Capture.treeDate("fri 14:00", now: now, calendar: calendar)) == "2026-10-16 14:00")
1087 }
1088
1089 @Test func capturesIntoClosedMissingAndOpenFiles() throws {
1090 let notes = try Folder()
1091 let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
1092 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1093 let template = CaptureTemplates.defaults[0]
1094 let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
1095 #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
1096 #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
1097
1098 _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
1099 #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
1100
1101 session.open(todo.path)
1102 _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
1103 #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
1104
1105 // An ID's file is resolved by the caller.
1106 let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
1107 let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
1108 _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
1109 #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
1110 }
1111}
1112
1113@MainActor
1114struct ClockModelTests {
1115 /// A clock started in Emacs becomes the running one; stopped there, it ends here.
1116 @Test func followsClocksStartedElsewhere() throws {
1117 let notes = try Folder()
1118 let work = try notes.write("work.org", "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 09:00]\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n")
1119 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1120 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
1121 #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 09:00]")
1122 #expect(clock.running?.path == work.path && clock.running?.start == "2026-10-05 Mon 09:00")
1123 #expect(clock.history.first?.title == "Task")
1124 #expect(clock.sync(session, paths: [work.path]) == nil)
1125 // Emacs clocks out.
1126 try "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:00] => 1:00\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n"
1127 .write(to: work, atomically: true, encoding: .utf8)
1128 #expect(clock.sync(session, paths: [work.path]) == "The clock in \"Task\" was stopped elsewhere")
1129 #expect(clock.running == nil)
1130 // The dangling one stays for resolution; a clock Emacs starts later runs.
1131 #expect(clock.sync(session, paths: [work.path]) == nil)
1132 try "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 11:00]\nCLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:00] => 1:00\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n"
1133 .write(to: work, atomically: true, encoding: .utf8)
1134 #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 11:00]")
1135 // Another file's change says nothing about the running clock.
1136 #expect(clock.sync(session, paths: [notes.url.appendingPathComponent("other.org").path]) == nil)
1137 #expect(clock.running?.start == "2026-10-05 Mon 11:00")
1138 }
1139
1140 @Test func clocksInAndOutAcrossFiles() throws {
1141 let notes = try Folder()
1142 let work = try notes.write("work.org", "* Task\nBody\n")
1143 let other = try notes.write("other.org", "* Other\n")
1144 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1145 session.open(work.path)
1146 session.reveal(2)
1147 let stateFile = notes.url.appendingPathComponent("clock.json")
1148 let clock = ClockModel(file: stateFile)
1149 var utc = Calendar(identifier: .gregorian)
1150 utc.timeZone = TimeZone(identifier: "UTC")!
1151 let start = Date(timeIntervalSince1970: 1_789_000_000)
1152 _ = clock.clockIn(session, now: start)
1153 #expect(clock.running?.heading == "Task")
1154 #expect(ClockModel(file: stateFile).running == clock.running)
1155
1156 // Out from another file: the clocked file's buffer is still open behind it and takes
1157 // the change.
1158 session.open(other.path)
1159 let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
1160 #expect(message == "Clock stopped after 1:35")
1161 #expect(clock.running == nil)
1162 #expect(session.dirtyPaths == [work.path])
1163 #expect(session.saveAll())
1164 let text = try String(contentsOf: work, encoding: .utf8)
1165 #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=> 1:35\n:END:\nBody\n"), "\(text)")
1166 }
1167
1168 /// `org-clock-out-when-done`, through the session's text-changed hook, and the Effort
1169 /// notification.
1170 @Test func clocksOutWhenDoneAndRemindsAtEffort() async throws {
1171 let notes = try Folder()
1172 let work = try notes.write("work.org", "* TODO Task\n:PROPERTIES:\n:Effort: 1:00\n:END:\n:LOGBOOK:\nCLOCK: [2026-09-01 Tue 09:00]--[2026-09-01 Tue 09:20] => 0:20\n:END:\n** Sub\n:LOGBOOK:\nCLOCK: [2026-09-02 Wed 09:00]--[2026-09-02 Wed 09:10] => 0:10\n:END:\n")
1173 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1174 let defaults = try #require(UserDefaults(suiteName: "orgstar-clock-done-\(UUID().uuidString)"))
1175 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: defaults)
1176 let center = FakeReminderCenter()
1177 clock.notifications = center
1178 var messages: [String] = []
1179 session.textChanged = { path in if let message = clock.textChanged(path, session) { messages.append(message) } }
1180 let start = Date(timeIntervalSince1970: 1_789_000_000)
1181 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1182 #expect(clock.running != nil)
1183 // An hour of effort, half an hour clocked in the subtree before.
1184 #expect(clock.effort(session, now: start).map { [$0.effort, $0.clocked] } == [60, 30])
1185 for _ in 0..<200 where center.added.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
1186 #expect(center.added == ["orgstar-effort"])
1187 // Marking it done from an unopened file's command clocks out.
1188 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1189 #expect(clock.running == nil && messages.count == 1)
1190 let text = try String(contentsOf: work, encoding: .utf8)
1191 #expect(!text.contains(#/CLOCK: \[[^\]]+\]\n/#), "\(text)")
1192
1193 // nil keeps it running.
1194 UserConfig.apply("org-clock-out-when-done = \"nil\"\n", to: defaults)
1195 _ = session.perform(SetTodo(keyword: "TODO"), path: work.path, at: 2, expect: nil)
1196 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1197 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1198 #expect(clock.running != nil)
1199 }
1200}
1201
1202@MainActor
1203struct BufferTests {
1204 @Test func buffersKeepEditsWhileOthersShow() throws {
1205 let notes = try Folder()
1206 let a = try notes.write("a.org", "* A\n")
1207 let b = try notes.write("b.org", "* B\n")
1208 let c = try notes.write("c.org", "* C\n")
1209 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1210 session.saveMode = .explicit
1211 session.open(a.path)
1212 _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
1213 session.open(b.path)
1214 #expect(session.path == b.path)
1215 #expect(session.openPaths == [a.path, b.path])
1216 #expect(session.dirtyPaths == [a.path])
1217 // A background buffer takes commands for its file, not the disk.
1218 _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
1219 #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
1220 #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
1221
1222 session.open(a.path)
1223 #expect(session.document?.text.hasPrefix("* DONE A") == true)
1224 session.open(c.path)
1225 // Opened after the current buffer.
1226 #expect(session.openPaths == [a.path, c.path, b.path])
1227 session.cycle(1)
1228 #expect(session.path == b.path)
1229 session.cycle(1)
1230 #expect(session.path == a.path)
1231 session.showPrevious()
1232 #expect(session.path == b.path)
1233 #expect(session.recentPaths == [b.path, a.path, c.path])
1234
1235 session.kill(b.path)
1236 #expect(session.path == a.path)
1237 #expect(session.openPaths == [a.path, c.path])
1238 #expect(session.saveAll())
1239 #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
1240 session.kill(a.path)
1241 session.kill(c.path)
1242 #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
1243 }
1244
1245 @Test func backgroundBuffersFollowTheDisk() throws {
1246 let notes = try Folder()
1247 let a = try notes.write("a.org", "* A\n")
1248 let b = try notes.write("b.org", "* B\n")
1249 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1250 session.open(a.path)
1251 session.open(b.path)
1252 try notes.write("a.org", "* A changed\n")
1253 session.fileChanged(a.path)
1254 #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
1255 }
1256}
1257
1258@MainActor
1259struct LinkFollowTests {
1260 @Test func followsLinksOfEachKind() async throws {
1261 let notes = try Folder()
1262 let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
1263 let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
1264 _ = try notes.write("pic.png", "not really")
1265 let workspace = try WorkspaceModel(directory: nil)
1266 try await workspace.addRoot(notes.url)
1267 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1268 session.open(a.path)
1269 let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
1270 func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1271
1272 #expect(follow("here") == .shown)
1273 #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
1274 #expect(follow("#two") == .shown)
1275 #expect(follow("Second") == .shown)
1276 #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
1277
1278 #expect(follow("file:sub/b.org::5") == .shown)
1279 #expect(session.path == b.path)
1280 #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
1281 session.open(a.path)
1282 #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
1283 session.open(a.path)
1284 #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
1285 #expect(follow("id:none") == .message("No heading has the ID none"))
1286 // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
1287 #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
1288 #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
1289 #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
1290 #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
1291 #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1292 }
1293
1294 @Test func followsDenoteLinks() async throws {
1295 let notes = try Folder()
1296 let a = try notes.write("a.org", "* Start\n")
1297 let note = try notes.write("sub/20261119T120000--a-note__kw.org", "#+title: A note\n* Inside\n:PROPERTIES:\n:CUSTOM_ID: in\n:END:\n")
1298 let pdf = try notes.write("20261119T120000--a-note.pdf", "pdf")
1299 let workspace = try WorkspaceModel(directory: nil)
1300 try await workspace.addRoot(notes.url)
1301 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1302 session.open(a.path)
1303 func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1304
1305 #expect(follow("denote:20261119T120000") == .shown && session.path == note.path)
1306 session.open(a.path)
1307 #expect(follow("denote:20261119T120000::#in") == .shown && session.path == note.path)
1308 #expect(session.revealRequest?.offset == (try String(contentsOfFile: note.path, encoding: .utf8) as NSString).range(of: "* Inside").location)
1309 #expect(follow("denote:20200101T000000") == .message("No file has the Denote identifier 20200101T000000"))
1310 // Query links: the notes whose text or name the regexp matches.
1311 #expect(follow("denote:query-contents:INSIDE") == .choose(prompt: "Notes matching INSIDE: ", paths: [note.path]))
1312 #expect(follow("denote:query-filenames:a-no+te") == .choose(prompt: "Notes matching a-no+te: ", paths: [pdf.path, note.path].sorted()))
1313 #expect(follow("denote:query-contents:Start") == .message("No notes match Start"))
1314 }
1315
1316 @Test func followsAttachmentAndRadioLinks() throws {
1317 let notes = try Folder()
1318 let text = "* Task\n:PROPERTIES:\n:ID: ab12-cd\n:END:\nSee [[attachment:scan.pdf]] and <<<the plan>>>.\n* Later\nAs in The Plan.\n"
1319 let a = try notes.write("a.org", text)
1320 let scan = try notes.write("data/ab/12-cd/scan.pdf", "pdf")
1321 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1322 session.open(a.path)
1323 let tree = try #require(session.document?.tree)
1324 func follow(_ needle: String) throws -> LinkFollow {
1325 let link = try #require(Links.link(at: (text as NSString).range(of: needle).location + 1, text: text, tree: tree)?.link)
1326 return session.follow(link, workspace: nil, isText: { $0.hasSuffix(".org") })
1327 }
1328 #expect(try follow("attachment:") == .openExternally(URL(fileURLWithPath: (scan.path as NSString).standardizingPath)))
1329 #expect(try follow("The Plan") == .shown)
1330 #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location)
1331 }
1332}
1333
1334struct ICalendarFilesTests {
1335 @Test func writesBesideEachFileAndCombined() throws {
1336 let folder = try Folder()
1337 let a = try folder.write("a.org", "#+EXPORT_FILE_NAME: out/cal\n* Meeting <2026-10-12 Mon 10:00>\n")
1338 let b = try folder.write("b.org", "* TODO Task\nDEADLINE: <2026-10-20 Tue>\n")
1339 var options = ICalendarOptions()
1340 options.includeTodo = .unfinished
1341 let read = { (path: String) -> (text: String, settings: OrgSettings)? in (try? String(contentsOfFile: path, encoding: .utf8)).map { ($0, OrgSettings.default) } }
1342 let written = try ICalendarFiles.exportEach([a.path, b.path], options: options, read: read)
1343 #expect(written.map(\.lastPathComponent) == ["cal.ics", "b.ics"])
1344 #expect(written[0].deletingLastPathComponent().lastPathComponent == "out")
1345 let first = try String(contentsOf: written[0], encoding: .utf8)
1346 #expect(first.hasPrefix("BEGIN:VCALENDAR\r\n") && first.contains("SUMMARY:Meeting <2026-10-12 Mon 10:00>\r\n"))
1347 let combined = folder.url.appendingPathComponent("all/org.ics").path
1348 let url = try ICalendarFiles.combine([a.path, b.path], to: combined, options: options, read: read)
1349 let text = try String(contentsOf: url, encoding: .utf8)
1350 #expect(text.contains("X-WR-CALNAME:OrgMode\r\n") && text.contains("BEGIN:VTODO\r\n") && text.contains("DUE;VALUE=DATE:20261020\r\n"))
1351 }
1352
1353 @Test func readsSettings() {
1354 let defaults = UserDefaults(suiteName: "orgstar-ics-\(UUID().uuidString)")!
1355 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .none)
1356 #expect(OrgPreferences.icalendarOptions(defaults).useDeadline == ["event-if-not-todo", "todo-due"])
1357 defaults.set("NEXT WAIT", forKey: "icalendarIncludeTodo")
1358 defaults.set("event-if-todo", forKey: "icalendarUseScheduled")
1359 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .keywords(["NEXT", "WAIT"]))
1360 #expect(OrgPreferences.icalendarOptions(defaults).useScheduled == ["event-if-todo"])
1361 defaults.set("unblocked", forKey: "icalendarIncludeTodo")
1362 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .unblocked)
1363 }
1364}