Tests/OrgAppTests/AppTests.swift

44019206b2343f9f00af44ffb9964c36b4c7fb4c
orgstar/Tests/OrgAppTests/AppTests.swift

949 lines · 45527 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        let model = try WorkspaceModel(directory: nil)
111        try await model.addRoot(notes.url)
112        let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
113        let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
114        #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other"])
115        #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing"])
116        #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
117        #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other"])
118    }
119
120    @Test func createRenameAndTrashFiles() async throws {
121        let notes = try Folder()
122        try notes.write("a.org", "* Alpha\n")
123        let model = try WorkspaceModel(directory: nil)
124        model.trasher = { try FileManager.default.removeItem(at: $0) }
125        try await model.addRoot(notes.url)
126        let root = try #require(model.rootPaths.first)
127
128        let created = try await model.createFile(named: "projects/plan", in: root)
129        #expect(created == root + "/projects/plan.org")
130        #expect(model.files.map(\.path).contains(created))
131        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
132        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
133
134        let renamed = try await model.rename(created, to: "roadmap.org")
135        #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
136        let folder = try await model.rename(root + "/projects", to: "work")
137        #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
138
139        try await model.trash(folder + "/roadmap.org")
140        #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
141        #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
142        #expect(model.search("alpha").count == 1)
143    }
144
145    /// Watching starts with no folders (a first launch); a folder added afterwards is
146    /// watched.
147    @Test func foldersAddedLaterAreWatched() async throws {
148        let notes = try Folder()
149        let model = try WorkspaceModel(directory: nil)
150        model.startWatching()
151        try await model.addRoot(notes.url)
152        let file = try notes.write("new.org", "* Fresh heading\n")
153        var found = false
154        for _ in 0..<40 where !found {
155            try await Task.sleep(for: .milliseconds(100))
156            found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
157        }
158        #expect(found)
159    }
160
161    @Test func changedFilesAreReindexed() async throws {
162        let notes = try Folder()
163        let file = try notes.write("a.org", "* Old\n")
164        let model = try WorkspaceModel(directory: nil)
165        try await model.addRoot(notes.url)
166        try notes.write("a.org", "* New\n")
167        await model.filesChanged([file], rescan: [])
168        #expect(model.search("new").count == 1)
169        #expect(model.changedFile?.path == file.path)
170    }
171}
172
173@MainActor
174struct DocumentSessionTests {
175    @Test func openShowAndReload() throws {
176        let notes = try Folder()
177        let file = try notes.write("a.org", "* One\n* Two\n")
178        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
179        session.open(file.path)
180        #expect(session.outline.map(\.title) == ["One", "Two"])
181
182        let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
183        session.show(location)
184        #expect(session.revealRequest?.offset == 6)
185
186        try notes.write("a.org", "intro\n* One\n* Two\n")
187        session.fileChanged(file.path)
188        #expect(session.outline.map(\.start) == [6, 12])
189        session.show(location)
190        #expect(session.revealRequest?.offset == 12)
191    }
192
193    @Test func openReadsSetupFiles() throws {
194        let notes = try Folder()
195        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
196        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
197        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
198        session.open(file.path)
199        #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
200    }
201
202    @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
203        let notes = try Folder()
204        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
205        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
206        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
207        session.open(file.path)
208        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == false)
209        try notes.write("setup.org", "#+TODO: NEXT WAIT | DONE\n")
210        let text = session.document!.text
211        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
212        guard case .commit(let result) = CtrlCCtrlC().run(in: context) else { Issue.record("no commit"); return }
213        #expect(result.effects.contains(.refreshSetup))
214        session.refreshSetup()
215        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
216        #expect(session.document?.isDirty == false)
217    }
218
219    @Test func reloadingFromDiskReadsSetupFilesAgain() throws {
220        let notes = try Folder()
221        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
222        let file = try notes.write("a.org", "* WAIT One\n")
223        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
224        session.open(file.path)
225        try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
226        try notes.write("setup.org", "#+TODO: WAIT | DONE\n")
227        session.fileChanged(file.path)
228        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
229    }
230
231    @Test func missingFileReportsAnError() {
232        let session = DocumentSession()
233        session.open("/nonexistent/a.org")
234        #expect(session.lastError != nil)
235        #expect(session.document == nil)
236    }
237}
238
239@MainActor
240struct SessionSavingTests {
241    let notes: Folder
242    let file: URL
243    let recovery: FileRecoveryStore
244    let session: DocumentSession
245
246    init() throws {
247        notes = try Folder()
248        file = try notes.write("a.org", "a\nb\nc\n")
249        recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
250        session = DocumentSession(recovery: recovery)
251        session.saveMode = .explicit
252        session.open(file.path)
253    }
254
255    /// Types `text` at `offset`, as the editor would.
256    func type(_ text: String, at offset: Int) throws {
257        let buffer = StateBuffer(session.document!)
258        session.attach(buffer)
259        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
260        session.bufferChanged()
261    }
262
263    var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
264
265    @Test func saveWritesAndClearsDirty() throws {
266        try type("x", at: 0)
267        #expect(session.isDirty)
268        #expect(session.save())
269        #expect(!session.isDirty)
270        #expect(disk == "xa\nb\nc\n")
271    }
272
273    @Test func automaticModeSavesAfterTheDelay() async throws {
274        session.saveMode = .automatic
275        session.autosaveDelay = .milliseconds(10)
276        try type("x", at: 0)
277        #expect(disk == "a\nb\nc\n")
278        await session.autosave?.value
279        #expect(disk == "xa\nb\nc\n")
280        #expect(!session.isDirty)
281    }
282
283    @Test func explicitModeWaitsForSave() throws {
284        try type("x", at: 0)
285        #expect(session.autosave == nil)
286    }
287
288    @Test func externalChangeMergesIntoEdits() throws {
289        try type("x", at: 0)
290        try notes.write("a.org", "a\nb\nC\n")
291        session.fileChanged(file.path)
292        #expect(session.document?.text == "xa\nb\nC\n")
293        #expect(session.conflict == nil)
294        #expect(session.save())
295        #expect(disk == "xa\nb\nC\n")
296    }
297
298    @Test func conflictKeepMine() throws {
299        try type("x", at: 0)
300        try notes.write("a.org", "z\nb\nc\n")
301        session.fileChanged(file.path)
302        #expect(session.conflict != nil)
303        #expect(!session.save())
304        #expect(disk == "z\nb\nc\n")
305        session.keepMine()
306        #expect(session.conflict == nil)
307        #expect(disk == "xa\nb\nc\n")
308        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
309        #expect(kept.contains("z\nb\nc\n"))
310    }
311
312    @Test func conflictUseDiskVersion() throws {
313        try type("x", at: 0)
314        try notes.write("a.org", "z\nb\nc\n")
315        #expect(!session.save())
316        #expect(session.conflict != nil)
317        session.useDiskVersion()
318        #expect(session.conflict == nil)
319        #expect(!session.isDirty)
320        #expect(session.document?.text == "z\nb\nc\n")
321        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
322        #expect(kept.contains("xa\nb\nc\n"))
323    }
324
325    @Test func searchSeesUnsavedHeadings() async throws {
326        let workspace = try WorkspaceModel(directory: nil)
327        try await workspace.addRoot(notes.url)
328        try type("* Unsaved heading\n", at: 0)
329        let overlay = workspace.overlay(path: session.path, document: session.document)
330        #expect(workspace.search("unsaved").isEmpty)
331        #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
332    }
333}
334
335@MainActor
336struct KeymapLoaderTests {
337    @Test func layersTheUserFile() throws {
338        let folder = try Folder()
339        let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
340        #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
341
342        let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
343        let loaded = KeymapLoader.load(.emacs, userFile: file)
344        #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
345        #expect(loaded.problems == ["line 4: bad or missing keys"])
346
347        let broken = try folder.write("broken.toml", "keys = \"x")
348        #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
349    }
350}
351
352@MainActor
353struct MoveSubtreeTests {
354    @Test func refileWithinAndAcrossFiles() async throws {
355        let notes = try Folder()
356        let file = try notes.write("a.org", "* one\nbody\n* two\n")
357        let other = try notes.write("b.org", "* inbox\n")
358        let workspace = try WorkspaceModel(directory: nil)
359        try await workspace.addRoot(notes.url)
360        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
361        session.saveMode = .explicit
362        session.open(file.path)
363        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
364        #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
365
366        #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
367        #expect(session.document?.text == "* two\n** one\nbody\n")
368
369        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
370        StateBufferCaret.set(session, 6)
371        #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
372        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
373        #expect(session.document?.text == "* two\n")
374    }
375
376    @Test func archiveToTheArchiveFile() throws {
377        let notes = try Folder()
378        let file = try notes.write("a.org", "* done\n* keep\n")
379        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
380        session.saveMode = .explicit
381        session.open(file.path)
382        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
383        #expect(session.document?.text == "* keep\n")
384        let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
385        #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
386    }
387}
388
389@MainActor
390struct AgendaActionTests {
391    /// From the agenda: entries in files that aren't open move and archive on disk, and the
392    /// current buffer stays as it was.
393    @Test func refileAndArchiveFromAnEntry() async throws {
394        let notes = try Folder()
395        let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
396        let other = try notes.write("b.org", "* inbox\n")
397        let shown = try notes.write("c.org", "* shown\n")
398        let workspace = try WorkspaceModel(directory: nil)
399        try await workspace.addRoot(notes.url)
400        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
401        session.saveMode = .explicit
402        session.open(shown.path)
403
404        let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
405        #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
406        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
407        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
408
409        let text = try String(contentsOf: file, encoding: .utf8)
410        let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
411        #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
412        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
413
414        #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
415        #expect(try String(contentsOf: file, encoding: .utf8) == "")
416        #expect(session.path == shown.path && session.document?.text == "* shown\n")
417    }
418
419    @Test func locatesMovedHeadings() throws {
420        let notes = try Folder()
421        let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
422        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
423        #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
424        #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
425        #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
426        #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
427    }
428}
429
430@MainActor
431struct MoveIntoOpenBufferTests {
432    /// A target open with unsaved edits above its heading takes the subtree in its buffer,
433    /// under the right heading, and the disk keeps the saved text.
434    @Test func refileIntoAnOpenBuffer() async throws {
435        let notes = try Folder()
436        let file = try notes.write("a.org", "* task\nbody\n")
437        let other = try notes.write("b.org", "* inbox\n* projects\n")
438        let workspace = try WorkspaceModel(directory: nil)
439        try await workspace.addRoot(notes.url)
440        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
441        session.saveMode = .explicit
442        session.open(other.path)
443        let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
444        _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
445        session.open(file.path)
446        #expect(session.refile(to: projects) == "Refiled to b.org/projects")
447        #expect(session.document?.text == "")
448        #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
449        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
450    }
451
452    @Test func archiveIntoAnOpenBuffer() throws {
453        let notes = try Folder()
454        let file = try notes.write("a.org", "* done\n* keep\n")
455        let archive = try notes.write("a.org_archive", "* old\n")
456        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
457        session.saveMode = .explicit
458        session.open(archive.path)
459        session.open(file.path)
460        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
461        #expect(session.document?.text == "* keep\n")
462        let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
463        #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
464        #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
465    }
466}
467
468/// Inserts text at the caret, for tests.
469struct InsertText: OrgCommand {
470    let text: String
471    var id: String { "test.insert" }
472    var title: String { "Insert" }
473    func applies(in context: EditContext) -> Bool { true }
474    func run(in context: EditContext) -> CommandStep {
475        .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
476    }
477}
478
479/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
480@MainActor
481enum StateBufferCaret {
482    static func set(_ session: DocumentSession, _ offset: Int) {
483        let buffer = StateBuffer(session.document!)
484        buffer.selection = [offset..<offset]
485        session.attach(buffer)
486    }
487}
488
489@MainActor
490struct AgendaModelTests {
491    @Test func topLevelFilesAndTheOpenBuffer() async throws {
492        let notes = try Folder()
493        try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
494        try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
495        try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
496        let model = try WorkspaceModel(directory: nil)
497        try await model.addRoot(notes.url)
498        let agenda = AgendaModel(workspace: model)
499        var utc = Calendar(identifier: .gregorian)
500        utc.timeZone = TimeZone(identifier: "UTC")!
501        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
502
503        await agenda.refresh(open: [:], now: now, calendar: utc)
504        #expect(agenda.days.count == 10)
505        #expect(agenda.days[3].isToday)
506        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
507
508        agenda.includeSubfolders = true
509        await agenda.refresh(open: [:], now: now, calendar: utc)
510        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
511
512        let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
513        await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
514        #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
515
516        agenda.shift(forward: true, now: now, calendar: utc)
517        await agenda.refresh(open: [:], now: now, calendar: utc)
518        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
519    }
520}
521
522@MainActor
523struct AgendaCommandTests {
524    @Test func loadsViews() throws {
525        let folder = try Folder()
526        let file = try folder.write("views.toml", """
527        [[view]]
528        name = "Work"
529        type = "match"
530        match = "+work"
531        [[view]]
532        name = "Week"
533        span = 7
534        start = -1
535        [[view]]
536        name = "Waiting"
537        type = "todo"
538        keywords = "WAIT|HOLD"
539        [[view]]
540        name = "Broken"
541        type = "match"
542        """)
543        let loaded = AgendaViewLoader.load(userFile: file)
544        #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Work", "Week", "Waiting"])
545        #expect(loaded.views[2].mode == .match("+work", todoOnly: false))
546        #expect(loaded.views[3].mode == .agenda(span: 7, startOffset: -1))
547        #expect(loaded.views[4].mode == .todo(keywords: "WAIT|HOLD"))
548        #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
549    }
550
551    @Test func todoListMode() async throws {
552        let notes = try Folder()
553        try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
554        let model = try WorkspaceModel(directory: nil)
555        try await model.addRoot(notes.url)
556        let agenda = AgendaModel(workspace: model)
557        agenda.mode = .todo(keywords: nil)
558        await agenda.refresh(open: [:])
559        #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
560        agenda.mode = .match("work", todoOnly: false)
561        await agenda.refresh(open: [:])
562        #expect(agenda.list.map(\.text) == ["TODO One"])
563    }
564
565    @Test func runsCommandsOnClosedAndOpenFiles() throws {
566        let notes = try Folder()
567        let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
568        let b = try notes.write("b.org", "* TODO Three\n")
569        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
570        session.open(a.path)
571
572        // A closed file is changed on disk.
573        let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
574        guard case .commit = closed else { Issue.record("\(closed)"); return }
575        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
576
577        // The open file changes in its buffer.
578        let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
579        guard case .commit = open else { Issue.record("\(open)"); return }
580        #expect(session.document?.text == "* TODO One\n* DONE Two\n")
581
582        // A heading that moved is refused.
583        let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
584        guard case .failed = stale else { Issue.record("\(stale)"); return }
585        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
586    }
587}
588
589final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
590    private let lock = NSLock()
591    private var pending: [String] = ["someone.else"]
592    var authorized = true
593    private(set) var added: [String] = []
594
595    func authorize() async -> Bool { authorized }
596    func pendingIDs() async -> [String] { lock.withLock { pending } }
597    var delivered: [String] = []
598    func deliveredIDs() async -> [String] { lock.withLock { delivered } }
599    /// The system showing a notification: no longer pending.
600    func fire(_ id: String, keep: Bool) {
601        lock.withLock {
602            pending.removeAll { $0 == id }
603            if keep { delivered.append(id) }
604        }
605    }
606    func add(_ reminder: Reminder) async throws {
607        lock.withLock {
608            pending.append(reminder.id)
609            added.append(reminder.id)
610        }
611    }
612    func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
613    var ids: [String] { lock.withLock { pending } }
614}
615
616@MainActor
617struct ReminderSchedulerTests {
618    func reminder(_ id: String, _ minutes: Double) -> Reminder {
619        let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
620        return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
621    }
622
623    @Test func reconciles() async {
624        let center = FakeReminderCenter()
625        let scheduler = ReminderScheduler(center: center)
626        await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
627        #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
628        #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
629
630        await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
631        #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
632        #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
633
634        await scheduler.clear()
635        #expect(center.ids == ["someone.else"])
636        #expect(scheduler.scheduledThrough == nil)
637
638        // Fired reminders aren't set again, whether or not they're still in Notification Center.
639        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
640        center.fire("orgstar.e", keep: false)
641        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
642        #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
643        let relaunched = ReminderScheduler(center: center)
644        center.fire("orgstar.f", keep: true)
645        await relaunched.reconcile([reminder("f", 6)])
646        #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
647        await scheduler.clear()
648
649        center.authorized = false
650        await scheduler.reconcile([reminder("d", 4)])
651        #expect(!scheduler.isAuthorized)
652        #expect(center.ids == ["someone.else"])
653    }
654}
655
656@MainActor
657struct EmacsFallbackTests {
658    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
659    func recalculatesTablesNativeCodeCannot() async throws {
660        let notes = try Folder()
661        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")
662        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
663        session.open(file.path)
664        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
665        guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
666            Issue.record("\(step)")
667            return
668        }
669        #expect(reason == "non-numeric field a")
670        #expect(!lisp)
671        let message = await session.recalculateInEmacs(table: table, point: point, form: form)
672        #expect(message == "Recalculated in Emacs")
673        #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")
674    }
675}
676
677@MainActor
678struct BabelSessionTests {
679    @Test func runsBlocksAndWritesResults() async throws {
680        let notes = try Folder()
681        let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
682        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
683        session.open(file.path)
684        let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
685        guard case .external(.babel(let job)) = step else {
686            Issue.record("\(step)")
687            return
688        }
689        #expect(await session.runBabel(job) == "Code block evaluation complete.")
690        // A column that is half numbers is right-aligned, as org-table-align does.
691        #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n|     42 |\n")
692    }
693}
694
695@MainActor
696struct BabelErrorTests {
697    func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
698        guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
699            throw CancellationError()
700        }
701        return job
702    }
703
704    /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
705    @Test func reportsErrorsAndStillInsertsResults() async throws {
706        let notes = try Folder()
707        let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
708        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
709        session.open(file.path)
710        #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
711        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
712    }
713
714    @Test func cancelsARunningBlock() async throws {
715        let notes = try Folder()
716        let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
717        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
718        session.open(file.path)
719        let start = ContinuousClock.now
720        var message: String?
721        session.startBabel(try job(session, file.path)) { message = $0 }
722        #expect(session.isRunningBabel)
723        try await Task.sleep(for: .milliseconds(200))
724        session.cancelBabel()
725        while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
726        #expect(message == "Code block canceled.")
727        #expect(!session.isRunningBabel)
728        #expect(ContinuousClock.now - start < .seconds(5))
729        #expect(session.document?.text.contains("#+RESULTS:") == false)
730    }
731}
732
733struct EmacsExportTests {
734    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
735    func exportsBesideTheFile() async throws {
736        let notes = try Folder()
737        let file = try notes.write("doc.org", "#+TITLE: On disk\n")
738        // The buffer's text is exported, not the file's.
739        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")
740        #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
741        let text = try String(contentsOfFile: written, encoding: .utf8)
742        #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
743        #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
744    }
745}
746
747@MainActor
748struct CaptureAppTests {
749    @Test func loadsTemplates() throws {
750        let folder = try Folder()
751        let file = try folder.write("capture.toml", """
752        [[template]]
753        key = "w"
754        name = "Work"
755        file = "work.org"
756        olp = "Projects/Work"
757        template = "* TODO %?\\n%a"
758        [[template]]
759        key = "j"
760        type = "plain"
761        file = "~/journal.org"
762        template = "%U %?"
763        prepend = true
764        """)
765        let loaded = CaptureTemplates.load(userFile: file)
766        #expect(loaded.problems.isEmpty)
767        #expect(loaded.templates.map(\.key) == ["w", "j"])
768        #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
769        #expect(loaded.templates[0].template == "* TODO %?\n%a")
770        #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
771        try """
772        [[template]]
773        key = "d"
774        file = "journal.org"
775        datetree = true
776        olp = "Journal"
777        tree-type = "month"
778        template = "* %?"
779        empty-lines-after = 1
780        jump-to-captured = true
781        [[template]]
782        key = "i"
783        id = "abc"
784        template = "* %?"
785        clock-in = true
786        clock-resume = true
787        [[template]]
788        key = "k"
789        clock = true
790        type = "item"
791        template = "%?"
792        immediate-finish = true
793        """.write(to: file, atomically: true, encoding: .utf8)
794        let targets = CaptureTemplates.load(userFile: file)
795        #expect(targets.problems.isEmpty)
796        #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
797        #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
798        #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
799        #expect(targets.templates[2].options.immediateFinish)
800        #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
801    }
802
803    @Test func capturesIntoClosedMissingAndOpenFiles() throws {
804        let notes = try Folder()
805        let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
806        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
807        let template = CaptureTemplates.defaults[0]
808        let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
809        #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
810        #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
811
812        _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
813        #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
814
815        session.open(todo.path)
816        _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
817        #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
818
819        // An ID's file is resolved by the caller.
820        let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
821        let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
822        _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
823        #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
824    }
825}
826
827@MainActor
828struct ClockModelTests {
829    @Test func clocksInAndOutAcrossFiles() throws {
830        let notes = try Folder()
831        let work = try notes.write("work.org", "* Task\nBody\n")
832        let other = try notes.write("other.org", "* Other\n")
833        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
834        session.open(work.path)
835        session.reveal(2)
836        let stateFile = notes.url.appendingPathComponent("clock.json")
837        let clock = ClockModel(file: stateFile)
838        var utc = Calendar(identifier: .gregorian)
839        utc.timeZone = TimeZone(identifier: "UTC")!
840        let start = Date(timeIntervalSince1970: 1_789_000_000)
841        _ = clock.clockIn(session, now: start)
842        #expect(clock.running?.heading == "Task")
843        #expect(ClockModel(file: stateFile).running == clock.running)
844
845        // Out from another file: the clocked file's buffer is still open behind it and takes
846        // the change.
847        session.open(other.path)
848        let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
849        #expect(message == "Clock stopped after 1:35")
850        #expect(clock.running == nil)
851        #expect(session.dirtyPaths == [work.path])
852        #expect(session.saveAll())
853        let text = try String(contentsOf: work, encoding: .utf8)
854        #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=>  1:35\n:END:\nBody\n"), "\(text)")
855    }
856}
857
858@MainActor
859struct BufferTests {
860    @Test func buffersKeepEditsWhileOthersShow() throws {
861        let notes = try Folder()
862        let a = try notes.write("a.org", "* A\n")
863        let b = try notes.write("b.org", "* B\n")
864        let c = try notes.write("c.org", "* C\n")
865        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
866        session.saveMode = .explicit
867        session.open(a.path)
868        _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
869        session.open(b.path)
870        #expect(session.path == b.path)
871        #expect(session.openPaths == [a.path, b.path])
872        #expect(session.dirtyPaths == [a.path])
873        // A background buffer takes commands for its file, not the disk.
874        _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
875        #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
876        #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
877
878        session.open(a.path)
879        #expect(session.document?.text.hasPrefix("* DONE A") == true)
880        session.open(c.path)
881        // Opened after the current buffer.
882        #expect(session.openPaths == [a.path, c.path, b.path])
883        session.cycle(1)
884        #expect(session.path == b.path)
885        session.cycle(1)
886        #expect(session.path == a.path)
887        session.showPrevious()
888        #expect(session.path == b.path)
889        #expect(session.recentPaths == [b.path, a.path, c.path])
890
891        session.kill(b.path)
892        #expect(session.path == a.path)
893        #expect(session.openPaths == [a.path, c.path])
894        #expect(session.saveAll())
895        #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
896        session.kill(a.path)
897        session.kill(c.path)
898        #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
899    }
900
901    @Test func backgroundBuffersFollowTheDisk() throws {
902        let notes = try Folder()
903        let a = try notes.write("a.org", "* A\n")
904        let b = try notes.write("b.org", "* B\n")
905        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
906        session.open(a.path)
907        session.open(b.path)
908        try notes.write("a.org", "* A changed\n")
909        session.fileChanged(a.path)
910        #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
911    }
912}
913
914@MainActor
915struct LinkFollowTests {
916    @Test func followsLinksOfEachKind() async throws {
917        let notes = try Folder()
918        let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
919        let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
920        _ = try notes.write("pic.png", "not really")
921        let workspace = try WorkspaceModel(directory: nil)
922        try await workspace.addRoot(notes.url)
923        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
924        session.open(a.path)
925        let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
926        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
927
928        #expect(follow("here") == .shown)
929        #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
930        #expect(follow("#two") == .shown)
931        #expect(follow("Second") == .shown)
932        #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
933
934        #expect(follow("file:sub/b.org::5") == .shown)
935        #expect(session.path == b.path)
936        #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
937        session.open(a.path)
938        #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
939        session.open(a.path)
940        #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
941        #expect(follow("id:none") == .message("No heading has the ID none"))
942        // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
943        #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
944        #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
945        #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
946        #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
947        #expect(follow("shell:rm -rf x") == .message("Orgstar doesn't run shell links"))
948    }
949}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form