Tests/OrgAppTests/AppTests.swift

dd764a1db9c6495c09fa4fc20856a781d84441e4
orgstar/Tests/OrgAppTests/AppTests.swift

1467 lines · 76078 bytes

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