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