Tests/OrgAppTests/AppTests.swift
1434 lines · 73851 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
659@MainActor
660struct AgendaCommandTests {
661 @Test func loadsViews() throws {
662 let folder = try Folder()
663 let file = try folder.write("views.toml", """
664 [[view]]
665 name = "Work"
666 type = "match"
667 match = "+work"
668 [[view]]
669 name = "Week"
670 span = 7
671 start = -1
672 [[view]]
673 name = "Waiting"
674 type = "todo"
675 keywords = "WAIT|HOLD"
676 [[view]]
677 name = "Broken"
678 type = "match"
679 """)
680 let loaded = AgendaViewLoader.load(userFile: file)
681 #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Stuck Projects", "Work", "Week", "Waiting"])
682 #expect(loaded.views[3].mode == .match("+work", todoOnly: false))
683 #expect(loaded.views[4].mode == .agenda(span: 7, startOffset: -1))
684 #expect(loaded.views[5].mode == .todo(keywords: "WAIT|HOLD"))
685 #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
686 }
687
688 @Test func viewsSortAndPrefixThemselves() async throws {
689 let notes = try Folder()
690 try notes.write("a.org", "* TODO b\n:PROPERTIES:\n:Effort: 0:30\n:END:\n* TODO [#A] c\n* TODO a\n")
691 let file = try notes.write("views.toml", """
692 [[view]]
693 name = "Alphabetical"
694 type = "todo"
695 sorting-strategy = "alpha-up bogus"
696 prefix-format = "%e"
697 """)
698 let loaded = AgendaViewLoader.load(userFile: file)
699 #expect(loaded.problems == ["views.toml line 1: unknown sorting key bogus"])
700 #expect(loaded.views[3].settings == AgendaViewSettings(prefixFormat: "%e", sortingStrategy: ["alpha-up"]))
701 let model = try WorkspaceModel(directory: nil)
702 try await model.addRoot(notes.url)
703 let agenda = AgendaModel(workspace: model)
704 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
705 agenda.mode = .todo(keywords: nil)
706 await agenda.refresh(open: [:])
707 // `alpha-up` keeps the priority cookie, as Org does.
708 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO a", "TODO b"])
709 #expect(agenda.list.map(\.prefixDetail) == [nil, nil, "0:30"])
710 agenda.mode = .todo(keywords: "TODO")
711 await agenda.refresh(open: [:])
712 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO b", "TODO a"])
713 }
714
715 @Test func stuckProjectViews() async throws {
716 let notes = try Folder()
717 try notes.write("a.org", "* Projects\n** Website\n*** TODO Draft\n** Garden\n*** WAIT Seeds\n")
718 let file = try notes.write("views.toml", """
719 [[view]]
720 name = "Stuck"
721 type = "stuck"
722 [[view]]
723 name = "Waiting counts"
724 type = "stuck"
725 keywords = "TODO WAIT"
726 """)
727 let loaded = AgendaViewLoader.load(userFile: file)
728 #expect(loaded.problems.isEmpty)
729 #expect(loaded.views[3].mode == .stuck(nil))
730 guard case .stuck(let definition?) = loaded.views[4].mode else { Issue.record("no definition"); return }
731 #expect(definition.todo == ["TODO", "WAIT"] && definition.match == "+LEVEL=2/-DONE")
732 let model = try WorkspaceModel(directory: nil)
733 try await model.addRoot(notes.url)
734 let agenda = AgendaModel(workspace: model)
735 agenda.mode = loaded.views[3].mode
736 await agenda.refresh(open: [:])
737 #expect(agenda.list.map(\.text) == ["Garden"])
738 agenda.mode = loaded.views[4].mode
739 await agenda.refresh(open: [:])
740 #expect(agenda.list.isEmpty)
741 }
742
743 @Test func blockViews() async throws {
744 let notes = try Folder()
745 let today = Days.date(Days.absolute(Date(), calendar: .current))
746 let stamp = String(format: "%04d-%02d-%02d", today.year, today.month, today.day)
747 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")
748 let file = try notes.write("views.toml", """
749 [[view]]
750 name = "Daily"
751 span = 1
752 sorting-strategy = "alpha-up"
753 [[view.block]]
754 type = "agenda"
755 header = "Today"
756 [[view.block]]
757 type = "todo"
758 skip-entry-if = "'scheduled 'regexp \\"someday\\""
759 [[view.block]]
760 type = "match"
761 match = "TODO=\\"WAIT\\""
762 [[view]]
763 name = "Broken skip"
764 type = "todo"
765 skip-entry-if = "'level 2"
766 """)
767 let loaded = AgendaViewLoader.load(userFile: file)
768 #expect(loaded.problems == ["views.toml line 14: skip-entry-if: level isn't supported"])
769 guard case .blocks(let blocks) = loaded.views.last!.mode else { Issue.record("no blocks"); return }
770 #expect(blocks.map(\.mode) == [.agenda(span: 1, startOffset: nil), .todo(keywords: nil), .match("TODO=\"WAIT\"", todoOnly: false)])
771 #expect(blocks.map(\.settings.header) == ["Today", nil, nil])
772 #expect(blocks.allSatisfy { $0.settings.sortingStrategy == ["alpha-up"] })
773 #expect(blocks[1].settings.skip == AgendaSkip(subtree: false, conditions: [.scheduled, .regexp("someday")]))
774 let model = try WorkspaceModel(directory: nil)
775 try await model.addRoot(notes.url)
776 let agenda = AgendaModel(workspace: model)
777 agenda.mode = loaded.views.last!.mode
778 await agenda.refresh(open: [:])
779 #expect(agenda.blocks.map(\.header) == ["Today", "TODO items: all", "Entries matching TODO=\"WAIT\""])
780 #expect(agenda.blocks[0].days.count == 1 && agenda.blocks[0].days[0].items.contains { $0.text == "TODO Call" })
781 #expect(agenda.blocks[1].list.map(\.text) == ["WAIT Hear back", "NEXT Write"])
782 #expect(agenda.blocks[2].list.map(\.text) == ["WAIT Hear back"])
783 #expect(agenda.list.isEmpty && agenda.days.isEmpty)
784 }
785
786 @Test func agendaFilesList() async throws {
787 let notes = try Folder()
788 try notes.write("a.org", "* TODO A\n")
789 try notes.write("b.org", "* TODO B\n")
790 try notes.write(".hidden.org", "* TODO Hidden\n")
791 try notes.write("sub/c.org", "* TODO C\n")
792 try notes.write("sub/d.org", "* TODO D\n")
793 try notes.write("sub/notes.txt", "x\n")
794 try notes.write("list", "sub/d.org\n\n b.org\nmissing.org\nsub/notes.txt\n")
795 let root = notes.url.path
796 #expect(AgendaFiles.resolve(["sub"], base: root) == ["\(root)/sub/c.org", "\(root)/sub/d.org"])
797 #expect(AgendaFiles.resolve([root, "sub/c.org"], base: nil) == ["\(root)/a.org", "\(root)/b.org"])
798 #expect(AgendaFiles.resolve(["list", "a.org"], base: root) == ["\(root)/sub/d.org", "\(root)/b.org", "\(root)/sub/notes.txt", "\(root)/a.org"])
799 let model = try WorkspaceModel(directory: nil)
800 try await model.addRoot(notes.url)
801 let agenda = AgendaModel(workspace: model)
802 agenda.agendaFiles = ["sub/c.org", "b.org"]
803 agenda.mode = .todo(keywords: nil)
804 await agenda.refresh(open: [:])
805 #expect(agenda.list.map(\.text) == ["TODO C", "TODO B"])
806 }
807
808 @Test func todoListMode() async throws {
809 let notes = try Folder()
810 try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
811 let model = try WorkspaceModel(directory: nil)
812 try await model.addRoot(notes.url)
813 let agenda = AgendaModel(workspace: model)
814 agenda.mode = .todo(keywords: nil)
815 await agenda.refresh(open: [:])
816 #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
817 agenda.mode = .match("work", todoOnly: false)
818 await agenda.refresh(open: [:])
819 #expect(agenda.list.map(\.text) == ["TODO One"])
820 }
821
822 @Test func runsCommandsOnClosedAndOpenFiles() throws {
823 let notes = try Folder()
824 let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
825 let b = try notes.write("b.org", "* TODO Three\n")
826 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
827 session.open(a.path)
828
829 // A closed file is changed on disk.
830 let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
831 guard case .commit = closed else { Issue.record("\(closed)"); return }
832 #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
833
834 // The open file changes in its buffer.
835 let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
836 guard case .commit = open else { Issue.record("\(open)"); return }
837 #expect(session.document?.text == "* TODO One\n* DONE Two\n")
838
839 // A heading that moved is refused.
840 let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
841 guard case .failed = stale else { Issue.record("\(stale)"); return }
842 #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
843 }
844}
845
846final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
847 private let lock = NSLock()
848 private var pending: [String] = ["someone.else"]
849 var authorized = true
850 private(set) var added: [String] = []
851
852 func authorize() async -> Bool { authorized }
853 func pendingIDs() async -> [String] { lock.withLock { pending } }
854 var delivered: [String] = []
855 func deliveredIDs() async -> [String] { lock.withLock { delivered } }
856 /// The system showing a notification: no longer pending.
857 func fire(_ id: String, keep: Bool) {
858 lock.withLock {
859 pending.removeAll { $0 == id }
860 if keep { delivered.append(id) }
861 }
862 }
863 func add(_ reminder: Reminder) async throws {
864 lock.withLock {
865 pending.append(reminder.id)
866 added.append(reminder.id)
867 }
868 }
869 func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
870 var ids: [String] { lock.withLock { pending } }
871}
872
873@MainActor
874struct ReminderSchedulerTests {
875 func reminder(_ id: String, _ minutes: Double) -> Reminder {
876 let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
877 return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
878 }
879
880 @Test func reconciles() async {
881 let center = FakeReminderCenter()
882 let scheduler = ReminderScheduler(center: center)
883 await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
884 #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
885 #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
886
887 await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
888 #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
889 #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
890
891 await scheduler.clear()
892 #expect(center.ids == ["someone.else"])
893 #expect(scheduler.scheduledThrough == nil)
894
895 // Fired reminders aren't set again, whether or not they're still in Notification Center.
896 await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
897 center.fire("orgstar.e", keep: false)
898 await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
899 #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
900 let relaunched = ReminderScheduler(center: center)
901 center.fire("orgstar.f", keep: true)
902 await relaunched.reconcile([reminder("f", 6)])
903 #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
904 await scheduler.clear()
905
906 center.authorized = false
907 await scheduler.reconcile([reminder("d", 4)])
908 #expect(!scheduler.isAuthorized)
909 #expect(center.ids == ["someone.else"])
910 }
911}
912
913@MainActor
914struct EmacsFallbackTests {
915 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
916 func recalculatesTablesNativeCodeCannot() async throws {
917 let notes = try Folder()
918 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n")
919 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
920 session.open(file.path)
921 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
922 guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
923 Issue.record("\(step)")
924 return
925 }
926 #expect(reason == "non-numeric field a")
927 #expect(!lisp)
928 let message = await session.recalculateInEmacs(table: table, point: point, form: form)
929 #expect(message == "Recalculated in Emacs")
930 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | 2 a |\n| y | 2 | 4 |\n#+TBLFM: $3=$2*2\n")
931 }
932
933 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
934 func cancelingARecalculationLeavesTheTable() async throws {
935 let notes = try Folder()
936 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=$1*2\n"
937 let file = try notes.write("t.org", text)
938 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
939 session.open(file.path)
940 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
941 guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else {
942 Issue.record("\(step)")
943 return
944 }
945 let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) }
946 task.cancel()
947 #expect(await task.value == "Recalculation canceled")
948 #expect(session.document?.text == text)
949 }
950}
951
952@MainActor
953struct BabelSessionTests {
954 @Test func runsBlocksAndWritesResults() async throws {
955 let notes = try Folder()
956 let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
957 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
958 session.open(file.path)
959 let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
960 guard case .external(.babel(let job)) = step else {
961 Issue.record("\(step)")
962 return
963 }
964 #expect(await session.runBabel(job) == "Code block evaluation complete.")
965 // A column that is half numbers is right-aligned, as org-table-align does.
966 #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n| 42 |\n")
967 }
968}
969
970@MainActor
971struct BabelErrorTests {
972 func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
973 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
974 throw CancellationError()
975 }
976 return job
977 }
978
979 /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
980 @Test func reportsErrorsAndStillInsertsResults() async throws {
981 let notes = try Folder()
982 let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
983 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
984 session.open(file.path)
985 #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
986 #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
987 }
988
989 @Test func cancelsARunningBlock() async throws {
990 let notes = try Folder()
991 let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
992 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
993 session.open(file.path)
994 let start = ContinuousClock.now
995 var message: String?
996 session.startBabel(try job(session, file.path)) { message = $0 }
997 #expect(session.isRunningBabel)
998 try await Task.sleep(for: .milliseconds(200))
999 session.cancelBabel()
1000 while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
1001 #expect(message == "Code block canceled.")
1002 #expect(!session.isRunningBabel)
1003 #expect(ContinuousClock.now - start < .seconds(5))
1004 #expect(session.document?.text.contains("#+RESULTS:") == false)
1005 }
1006}
1007
1008struct EmacsExportTests {
1009 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
1010 func exportsBesideTheFile() async throws {
1011 let notes = try Folder()
1012 let file = try notes.write("doc.org", "#+TITLE: On disk\n")
1013 // The buffer's text is exported, not the file's.
1014 let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii")
1015 #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
1016 let text = try String(contentsOfFile: written, encoding: .utf8)
1017 #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
1018 #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
1019 }
1020
1021 /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used.
1022 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
1023 func exportsTheSubtreeBodyOnly() async throws {
1024 let notes = try Folder()
1025 let file = try notes.write("doc.org", "")
1026 let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n"
1027 let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1
1028 let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true)
1029 #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt")
1030 let out = try String(contentsOfFile: written, encoding: .utf8)
1031 #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)")
1032 }
1033
1034 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
1035 func exportUsesBabelPath() async throws {
1036 let notes = try Folder()
1037 let file = try notes.write("doc.org", "")
1038 let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"#
1039 let written = try await EmacsRunner.export(text: "", path: file.path, function: function)
1040 #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"])
1041 }
1042
1043 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
1044 func cancellingStopsTheExport() async throws {
1045 let notes = try Folder()
1046 let file = try notes.write("doc.org", "")
1047 let pidFile = notes.url.appendingPathComponent("pid")
1048 let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"#
1049 let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) }
1050 var pid: pid_t?
1051 for _ in 0..<200 where pid == nil {
1052 try await Task.sleep(for: .milliseconds(50))
1053 pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) }
1054 }
1055 let started = try #require(pid)
1056 export.cancel()
1057 await #expect(throws: CancellationError.self) { try await export.value }
1058 var alive = true
1059 for _ in 0..<100 where alive {
1060 alive = kill(started, 0) == 0
1061 if alive { try await Task.sleep(for: .milliseconds(50)) }
1062 }
1063 #expect(!alive)
1064 }
1065}
1066
1067@MainActor
1068struct CaptureAppTests {
1069 @Test func loadsTemplates() throws {
1070 let folder = try Folder()
1071 let file = try folder.write("capture.toml", """
1072 [[template]]
1073 key = "w"
1074 name = "Work"
1075 file = "work.org"
1076 olp = "Projects/Work"
1077 template = "* TODO %?\\n%a"
1078 [[template]]
1079 key = "j"
1080 type = "plain"
1081 file = "~/journal.org"
1082 template = "%U %?"
1083 prepend = true
1084 """)
1085 let loaded = CaptureTemplates.load(userFile: file)
1086 #expect(loaded.problems.isEmpty)
1087 #expect(loaded.templates.map(\.key) == ["w", "j"])
1088 #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
1089 #expect(loaded.templates[0].template == "* TODO %?\n%a")
1090 #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
1091 try """
1092 [[template]]
1093 key = "d"
1094 file = "journal.org"
1095 datetree = true
1096 olp = "Journal"
1097 tree-type = "month"
1098 template = "* %?"
1099 empty-lines-after = 1
1100 jump-to-captured = true
1101 [[template]]
1102 key = "i"
1103 id = "abc"
1104 template = "* %?"
1105 clock-in = true
1106 clock-resume = true
1107 [[template]]
1108 key = "k"
1109 clock = true
1110 type = "item"
1111 template = "%?"
1112 immediate-finish = true
1113 """.write(to: file, atomically: true, encoding: .utf8)
1114 let targets = CaptureTemplates.load(userFile: file)
1115 #expect(targets.problems.isEmpty)
1116 #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
1117 #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
1118 #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
1119 #expect(targets.templates[2].options.immediateFinish)
1120 #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
1121 }
1122
1123 @Test func loadsGroupsRegexpsAndTreeTypes() throws {
1124 let folder = try Folder()
1125 let file = try folder.write("capture.toml", """
1126 [[template]]
1127 key = "t"
1128 name = "Todo"
1129 file = "todo.org"
1130 template = "* TODO %?"
1131 [[template]]
1132 key = "w"
1133 name = "Work"
1134 [[template]]
1135 key = "wm"
1136 name = "Meeting"
1137 file = "work.org"
1138 regexp = "^\\\\* Meetings"
1139 template = "* %?"
1140 [[template]]
1141 key = "wq"
1142 name = "Quarter"
1143 file = "work.org"
1144 datetree = true
1145 tree-type = "year quarter"
1146 time-prompt = true
1147 template = "* %?"
1148 [[template]]
1149 key = "xy"
1150 name = "Ungrouped"
1151 file = "x.org"
1152 template = "* %?"
1153 """)
1154 let loaded = CaptureTemplates.load(userFile: file)
1155 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
1156 #expect(loaded.groups == [CaptureGroup(key: "w", name: "Work")])
1157 #expect(loaded.templates.map(\.key) == ["t", "wm", "wq", "xy"])
1158 #expect(loaded.templates[1].target == .regexp(file: "work.org", regexp: "^\\* Meetings"))
1159 #expect(loaded.templates[2].target == .datetree(file: "work.org", path: [], tree: CaptureTemplate.TreeType(groups: [.year, .quarter])))
1160 #expect(loaded.templates[2].asksTreeDate && !loaded.templates[0].asksTreeDate)
1161 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "").map(\.key) == ["t", "w", "xy"])
1162 #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "w").map(\.key) == ["wm", "wq"])
1163 #expect(CaptureTemplates.label(loaded.templates[1], groups: loaded.groups) == "Work › Meeting")
1164 try "[[template]]\nkey = \"d\"\nfile = \"j.org\"\ndatetree = true\ntree-type = \"year fortnight\"\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
1165 #expect(CaptureTemplates.load(userFile: file).problems.count == 1)
1166 }
1167
1168 @Test func treeDateFollowsOrgCapture() {
1169 var calendar = Calendar(identifier: .gregorian)
1170 calendar.timeZone = TimeZone(identifier: "UTC")!
1171 let now = calendar.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 7, minute: 6, second: 27))!
1172 func text(_ date: Date) -> String {
1173 let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
1174 return String(format: "%04d-%02d-%02d %02d:%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!)
1175 }
1176 #expect(text(Capture.treeDate("", now: now, calendar: calendar)) == "2026-10-11 07:06")
1177 #expect(text(Capture.treeDate("fri", now: now, calendar: calendar)) == "2026-10-16 00:00")
1178 #expect(text(Capture.treeDate("fri 14:00", now: now, calendar: calendar)) == "2026-10-16 14:00")
1179 }
1180
1181 @Test func capturesIntoClosedMissingAndOpenFiles() throws {
1182 let notes = try Folder()
1183 let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
1184 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1185 let template = CaptureTemplates.defaults[0]
1186 let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
1187 #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
1188 #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
1189
1190 _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
1191 #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
1192
1193 session.open(todo.path)
1194 _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
1195 #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
1196
1197 // An ID's file is resolved by the caller.
1198 let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
1199 let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
1200 _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
1201 #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
1202 }
1203}
1204
1205@MainActor
1206struct ClockModelTests {
1207 /// A clock started in Emacs becomes the running one; stopped there, it ends here.
1208 @Test func followsClocksStartedElsewhere() throws {
1209 let notes = try Folder()
1210 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")
1211 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1212 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
1213 #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 09:00]")
1214 #expect(clock.running?.path == work.path && clock.running?.start == "2026-10-05 Mon 09:00")
1215 #expect(clock.history.first?.title == "Task")
1216 #expect(clock.sync(session, paths: [work.path]) == nil)
1217 // Emacs clocks out.
1218 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"
1219 .write(to: work, atomically: true, encoding: .utf8)
1220 #expect(clock.sync(session, paths: [work.path]) == "The clock in \"Task\" was stopped elsewhere")
1221 #expect(clock.running == nil)
1222 // The dangling one stays for resolution; a clock Emacs starts later runs.
1223 #expect(clock.sync(session, paths: [work.path]) == nil)
1224 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"
1225 .write(to: work, atomically: true, encoding: .utf8)
1226 #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 11:00]")
1227 // Another file's change says nothing about the running clock.
1228 #expect(clock.sync(session, paths: [notes.url.appendingPathComponent("other.org").path]) == nil)
1229 #expect(clock.running?.start == "2026-10-05 Mon 11:00")
1230 }
1231
1232 @Test func clocksInAndOutAcrossFiles() throws {
1233 let notes = try Folder()
1234 let work = try notes.write("work.org", "* Task\nBody\n")
1235 let other = try notes.write("other.org", "* Other\n")
1236 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1237 session.open(work.path)
1238 session.reveal(2)
1239 let stateFile = notes.url.appendingPathComponent("clock.json")
1240 let clock = ClockModel(file: stateFile)
1241 var utc = Calendar(identifier: .gregorian)
1242 utc.timeZone = TimeZone(identifier: "UTC")!
1243 let start = Date(timeIntervalSince1970: 1_789_000_000)
1244 _ = clock.clockIn(session, now: start)
1245 #expect(clock.running?.heading == "Task")
1246 #expect(ClockModel(file: stateFile).running == clock.running)
1247
1248 // Out from another file: the clocked file's buffer is still open behind it and takes
1249 // the change.
1250 session.open(other.path)
1251 let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
1252 #expect(message == "Clock stopped after 1:35")
1253 #expect(clock.running == nil)
1254 #expect(session.dirtyPaths == [work.path])
1255 #expect(session.saveAll())
1256 let text = try String(contentsOf: work, encoding: .utf8)
1257 #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=> 1:35\n:END:\nBody\n"), "\(text)")
1258 }
1259
1260 /// `org-clock-out-when-done`, through the session's text-changed hook, and the Effort
1261 /// notification.
1262 @Test func clocksOutWhenDoneAndRemindsAtEffort() async throws {
1263 let notes = try Folder()
1264 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")
1265 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1266 let defaults = try #require(UserDefaults(suiteName: "orgstar-clock-done-\(UUID().uuidString)"))
1267 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: defaults)
1268 let center = FakeReminderCenter()
1269 clock.notifications = center
1270 var messages: [String] = []
1271 session.textChanged = { path in if let message = clock.textChanged(path, session) { messages.append(message) } }
1272 let start = Date(timeIntervalSince1970: 1_789_000_000)
1273 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1274 #expect(clock.running != nil)
1275 // An hour of effort, half an hour clocked in the subtree before.
1276 #expect(clock.effort(session, now: start).map { [$0.effort, $0.clocked] } == [60, 30])
1277 for _ in 0..<200 where center.added.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
1278 #expect(center.added == ["orgstar-effort"])
1279 // Marking it done from an unopened file's command clocks out.
1280 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1281 #expect(clock.running == nil && messages.count == 1)
1282 let text = try String(contentsOf: work, encoding: .utf8)
1283 #expect(!text.contains(#/CLOCK: \[[^\]]+\]\n/#), "\(text)")
1284
1285 // nil keeps it running.
1286 UserConfig.apply("org-clock-out-when-done = \"nil\"\n", to: defaults)
1287 _ = session.perform(SetTodo(keyword: "TODO"), path: work.path, at: 2, expect: nil)
1288 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1289 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1290 #expect(clock.running != nil)
1291 }
1292}
1293
1294@MainActor
1295struct BufferTests {
1296 @Test func buffersKeepEditsWhileOthersShow() throws {
1297 let notes = try Folder()
1298 let a = try notes.write("a.org", "* A\n")
1299 let b = try notes.write("b.org", "* B\n")
1300 let c = try notes.write("c.org", "* C\n")
1301 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1302 session.saveMode = .explicit
1303 session.open(a.path)
1304 _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
1305 session.open(b.path)
1306 #expect(session.path == b.path)
1307 #expect(session.openPaths == [a.path, b.path])
1308 #expect(session.dirtyPaths == [a.path])
1309 // A background buffer takes commands for its file, not the disk.
1310 _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
1311 #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
1312 #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
1313
1314 session.open(a.path)
1315 #expect(session.document?.text.hasPrefix("* DONE A") == true)
1316 session.open(c.path)
1317 // Opened after the current buffer.
1318 #expect(session.openPaths == [a.path, c.path, b.path])
1319 session.cycle(1)
1320 #expect(session.path == b.path)
1321 session.cycle(1)
1322 #expect(session.path == a.path)
1323 session.showPrevious()
1324 #expect(session.path == b.path)
1325 #expect(session.recentPaths == [b.path, a.path, c.path])
1326
1327 session.kill(b.path)
1328 #expect(session.path == a.path)
1329 #expect(session.openPaths == [a.path, c.path])
1330 #expect(session.saveAll())
1331 #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
1332 session.kill(a.path)
1333 session.kill(c.path)
1334 #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
1335 }
1336
1337 @Test func backgroundBuffersFollowTheDisk() throws {
1338 let notes = try Folder()
1339 let a = try notes.write("a.org", "* A\n")
1340 let b = try notes.write("b.org", "* B\n")
1341 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1342 session.open(a.path)
1343 session.open(b.path)
1344 try notes.write("a.org", "* A changed\n")
1345 session.fileChanged(a.path)
1346 #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
1347 }
1348}
1349
1350@MainActor
1351struct LinkFollowTests {
1352 @Test func followsLinksOfEachKind() async throws {
1353 let notes = try Folder()
1354 let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
1355 let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
1356 _ = try notes.write("pic.png", "not really")
1357 let workspace = try WorkspaceModel(directory: nil)
1358 try await workspace.addRoot(notes.url)
1359 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1360 session.open(a.path)
1361 let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
1362 func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1363
1364 #expect(follow("here") == .shown)
1365 #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
1366 #expect(follow("#two") == .shown)
1367 #expect(follow("Second") == .shown)
1368 #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
1369
1370 #expect(follow("file:sub/b.org::5") == .shown)
1371 #expect(session.path == b.path)
1372 #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
1373 session.open(a.path)
1374 #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
1375 session.open(a.path)
1376 #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
1377 #expect(follow("id:none") == .message("No heading has the ID none"))
1378 // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
1379 #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
1380 #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
1381 #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
1382 #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
1383 #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1384 }
1385
1386 @Test func followsAttachmentAndRadioLinks() throws {
1387 let notes = try Folder()
1388 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"
1389 let a = try notes.write("a.org", text)
1390 let scan = try notes.write("data/ab/12-cd/scan.pdf", "pdf")
1391 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1392 session.open(a.path)
1393 let tree = try #require(session.document?.tree)
1394 func follow(_ needle: String) throws -> LinkFollow {
1395 let link = try #require(Links.link(at: (text as NSString).range(of: needle).location + 1, text: text, tree: tree)?.link)
1396 return session.follow(link, workspace: nil, isText: { $0.hasSuffix(".org") })
1397 }
1398 #expect(try follow("attachment:") == .openExternally(URL(fileURLWithPath: (scan.path as NSString).standardizingPath)))
1399 #expect(try follow("The Plan") == .shown)
1400 #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location)
1401 }
1402}
1403
1404struct ICalendarFilesTests {
1405 @Test func writesBesideEachFileAndCombined() throws {
1406 let folder = try Folder()
1407 let a = try folder.write("a.org", "#+EXPORT_FILE_NAME: out/cal\n* Meeting <2026-10-12 Mon 10:00>\n")
1408 let b = try folder.write("b.org", "* TODO Task\nDEADLINE: <2026-10-20 Tue>\n")
1409 var options = ICalendarOptions()
1410 options.includeTodo = .unfinished
1411 let read = { (path: String) -> (text: String, settings: OrgSettings)? in (try? String(contentsOfFile: path, encoding: .utf8)).map { ($0, OrgSettings.default) } }
1412 let written = try ICalendarFiles.exportEach([a.path, b.path], options: options, read: read)
1413 #expect(written.map(\.lastPathComponent) == ["cal.ics", "b.ics"])
1414 #expect(written[0].deletingLastPathComponent().lastPathComponent == "out")
1415 let first = try String(contentsOf: written[0], encoding: .utf8)
1416 #expect(first.hasPrefix("BEGIN:VCALENDAR\r\n") && first.contains("SUMMARY:Meeting <2026-10-12 Mon 10:00>\r\n"))
1417 let combined = folder.url.appendingPathComponent("all/org.ics").path
1418 let url = try ICalendarFiles.combine([a.path, b.path], to: combined, options: options, read: read)
1419 let text = try String(contentsOf: url, encoding: .utf8)
1420 #expect(text.contains("X-WR-CALNAME:OrgMode\r\n") && text.contains("BEGIN:VTODO\r\n") && text.contains("DUE;VALUE=DATE:20261020\r\n"))
1421 }
1422
1423 @Test func readsSettings() {
1424 let defaults = UserDefaults(suiteName: "orgstar-ics-\(UUID().uuidString)")!
1425 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .none)
1426 #expect(OrgPreferences.icalendarOptions(defaults).useDeadline == ["event-if-not-todo", "todo-due"])
1427 defaults.set("NEXT WAIT", forKey: "icalendarIncludeTodo")
1428 defaults.set("event-if-todo", forKey: "icalendarUseScheduled")
1429 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .keywords(["NEXT", "WAIT"]))
1430 #expect(OrgPreferences.icalendarOptions(defaults).useScheduled == ["event-if-todo"])
1431 defaults.set("unblocked", forKey: "icalendarIncludeTodo")
1432 #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .unblocked)
1433 }
1434}