Tests/OrgAppTests/AppTests.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Tests/OrgAppTests/AppTests.swift history · blame · raw

1119 lines · 55372 bytes

   1import Foundation
   2import OrgCore
   3import OrgDocument
   4import OrgIndex
   5import Testing
   6@testable import OrgApp
   7
   8/// A temporary folder that removes itself.
   9final class Folder {
  10    let url: URL
  11
  12    init() throws {
  13        url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL
  14        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
  15    }
  16
  17    deinit {
  18        try? FileManager.default.removeItem(at: url)
  19    }
  20
  21    @discardableResult
  22    func write(_ path: String, _ text: String) throws -> URL {
  23        let file = url.appendingPathComponent(path)
  24        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
  25        try Data(text.utf8).write(to: file)
  26        return file.standardizedFileURL
  27    }
  28}
  29
  30struct FileTreeTests {
  31    @Test func foldersFirstThenFiles() {
  32        let files = ["b.org", "a/z.org", "a/y.org", "c.sync-conflict-1.org", "a2.org"].map {
  33            FileEntry(path: "/r/" + $0, root: "/r", kind: $0.contains("conflict") ? .conflict : .org)
  34        }
  35        let tree = FileTreeNode.build(root: "/r", files: files)
  36        #expect(tree.children?.map(\.name) == ["a", "a2.org", "b.org", "c.sync-conflict-1.org"])
  37        #expect(tree.children?[0].children?.map(\.name) == ["y.org", "z.org"])
  38        #expect(tree.children?[1].children == nil)
  39    }
  40
  41    @Test func fuzzyMatching() {
  42        #expect(FuzzyMatch.score("wn", "work/notes.org") != nil)
  43        #expect(FuzzyMatch.score("xyz", "work/notes.org") == nil)
  44        let files = ["work/notes.org", "notes.org", "personal/wine.org"].map { FileEntry(path: "/r/" + $0, root: "/r", kind: .org) }
  45        #expect(FuzzyMatch.rank("notes", files).map(\.relativePath) == ["notes.org", "work/notes.org"])
  46        #expect(FuzzyMatch.rank("", files).count == 3)
  47    }
  48}
  49
  50@MainActor
  51struct WorkspaceModelTests {
  52    @Test func addSearchRemoveAndPersist() async throws {
  53        let notes = try Folder()
  54        let support = try Folder()
  55        try notes.write("a.org", "* Groceries\nbuy apples\n")
  56        try notes.write("sub/b.org", "* Taxes\n")
  57        try notes.write("c.sync-conflict-1.org", "* Taxes copy\n")
  58
  59        let model = try WorkspaceModel(directory: support.url)
  60        try await model.addRoot(notes.url)
  61        #expect(model.files.count == 3)
  62        #expect(model.search("apples").map(\.title) == ["Groceries"])
  63        #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
  64        let root = try #require(model.rootPaths.first)
  65        #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
  66
  67        let reopened = try WorkspaceModel(directory: support.url)
  68        #expect(reopened.roots.count == 1)
  69        #expect(reopened.files.count == 3)
  70
  71        try reopened.removeRoot(path: root)
  72        #expect(reopened.roots.isEmpty)
  73        #expect(reopened.files.isEmpty)
  74        #expect(reopened.search("apples").isEmpty)
  75    }
  76
  77    @Test func aMovedFolderLeavesNoOldRows() async throws {
  78        let parent = try Folder()
  79        let original = parent.url.appendingPathComponent("notes")
  80        try FileManager.default.createDirectory(at: original, withIntermediateDirectories: true)
  81        try "* Plumber\n".write(to: original.appendingPathComponent("a.org"), atomically: true, encoding: .utf8)
  82        let data = parent.url.appendingPathComponent("data")
  83        let model = try WorkspaceModel(directory: data)
  84        try await model.addRoot(original)
  85        #expect(model.search("plumber").count == 1)
  86
  87        let moved = parent.url.appendingPathComponent("moved")
  88        try FileManager.default.moveItem(at: original, to: moved)
  89        let reopened = try WorkspaceModel(directory: data)
  90        await reopened.refresh()
  91        let found = reopened.search("plumber").map(\.path)
  92        #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
  93        // Adding it again, under its new path, adds nothing.
  94        try await reopened.addRoot(moved)
  95        #expect(reopened.roots.count == 1)
  96    }
  97
  98    @Test func listsDownloadsInTheTree() {
  99        let files = [FileEntry(path: "/r/a.org", root: "/r", kind: .org)]
 100        let tree = FileTreeNode.build(root: "/r", files: files, downloading: ["/r/b.org", "/r/sub/c.org"])
 101        #expect(tree.children?.map(\.name) == ["sub", "a.org", "b.org"])
 102        #expect(tree.children?[2].isDownloading == true && tree.children?[2].file == nil)
 103        #expect(tree.children?[0].children?.map(\.name) == ["c.org"])
 104    }
 105
 106    @Test func findsBacklinks() async throws {
 107        let notes = try Folder()
 108        try notes.write("a.org", "* Sink\n:PROPERTIES:\n:ID: s-1\n:CUSTOM_ID: sink\n:END:\nsee [[*Taps]]\n* Taps\n")
 109        try notes.write("b.org", "* Plumbing\n[[id:s-1][the sink]] and [[file:a.org]]\n* Other\n[[file:a.org::#sink]] [[https://x.org]]\n")
 110        // Links before the first heading come from the file itself.
 111        try notes.write("c.org", "#+TITLE: C\nAbout [[file:a.org::*Sink]] and [[file:a.org]].\n* Later\n")
 112        let model = try WorkspaceModel(directory: nil)
 113        try await model.addRoot(notes.url)
 114        let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
 115        let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
 116        let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
 117        #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
 118        #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
 119        #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
 120        #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
 121        let fromC = try #require(model.backlinks(to: sink).last)
 122        #expect(fromC == .file(c, contentHash: fromC.contentHash))
 123        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 124        session.show(fromC)
 125        #expect(session.path == c && session.revealRequest?.offset == 0)
 126    }
 127
 128    @Test func createRenameAndTrashFiles() async throws {
 129        let notes = try Folder()
 130        try notes.write("a.org", "* Alpha\n")
 131        let model = try WorkspaceModel(directory: nil)
 132        model.trasher = { try FileManager.default.removeItem(at: $0) }
 133        try await model.addRoot(notes.url)
 134        let root = try #require(model.rootPaths.first)
 135
 136        let created = try await model.createFile(named: "projects/plan", in: root)
 137        #expect(created == root + "/projects/plan.org")
 138        #expect(model.files.map(\.path).contains(created))
 139        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
 140        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
 141
 142        let renamed = try await model.rename(created, to: "roadmap.org")
 143        #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
 144        let folder = try await model.rename(root + "/projects", to: "work")
 145        #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
 146
 147        try await model.trash(folder + "/roadmap.org")
 148        #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
 149        #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
 150        #expect(model.search("alpha").count == 1)
 151    }
 152
 153    /// Watching starts with no folders (a first launch); a folder added afterwards is
 154    /// watched.
 155    @Test func foldersAddedLaterAreWatched() async throws {
 156        let notes = try Folder()
 157        let model = try WorkspaceModel(directory: nil)
 158        model.startWatching()
 159        try await model.addRoot(notes.url)
 160        let file = try notes.write("new.org", "* Fresh heading\n")
 161        var found = false
 162        for _ in 0..<40 where !found {
 163            try await Task.sleep(for: .milliseconds(100))
 164            found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
 165        }
 166        #expect(found)
 167    }
 168
 169    @Test func changedFilesAreReindexed() async throws {
 170        let notes = try Folder()
 171        let file = try notes.write("a.org", "* Old\n")
 172        let model = try WorkspaceModel(directory: nil)
 173        try await model.addRoot(notes.url)
 174        try notes.write("a.org", "* New\n")
 175        await model.filesChanged([file], rescan: [])
 176        #expect(model.search("new").count == 1)
 177        #expect(model.changedFile?.path == file.path)
 178    }
 179}
 180
 181@MainActor
 182struct DocumentSessionTests {
 183    @Test func openShowAndReload() throws {
 184        let notes = try Folder()
 185        let file = try notes.write("a.org", "* One\n* Two\n")
 186        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 187        session.open(file.path)
 188        #expect(session.outline.map(\.title) == ["One", "Two"])
 189
 190        let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
 191        session.show(location)
 192        #expect(session.revealRequest?.offset == 6)
 193
 194        try notes.write("a.org", "intro\n* One\n* Two\n")
 195        session.fileChanged(file.path)
 196        #expect(session.outline.map(\.start) == [6, 12])
 197        session.show(location)
 198        #expect(session.revealRequest?.offset == 12)
 199    }
 200
 201    @Test func sameFileByAnotherPathSharesItsBuffer() throws {
 202        let notes = try Folder()
 203        let file = try notes.write("a.org", "* One\n")
 204        let link = notes.url.appendingPathComponent("link")
 205        try FileManager.default.createSymbolicLink(at: link, withDestinationURL: notes.url)
 206        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 207        session.open(file.path)
 208        session.open(link.appendingPathComponent("a.org").path)
 209        #expect(session.openPaths == [file.path])
 210        #expect(session.path == file.path)
 211    }
 212
 213    @Test func buffersOfTheSameNameShowTheirFolders() throws {
 214        let notes = try Folder()
 215        let a = try notes.write("x/blog/index.org", "a\n")
 216        let b = try notes.write("y/blog/index.org", "b\n")
 217        let c = try notes.write("y/other.org", "c\n")
 218        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 219        session.open(a.path)
 220        #expect(session.bufferName(a.path) == "index.org")
 221        session.open(b.path)
 222        session.open(c.path)
 223        #expect(session.bufferName(a.path) == "index.org<x/blog>")
 224        #expect(session.bufferName(b.path) == "index.org<y/blog>")
 225        #expect(session.bufferName(c.path) == "other.org")
 226    }
 227
 228    @Test func openReadsSetupFiles() throws {
 229        let notes = try Folder()
 230        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 231        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 232        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 233        session.open(file.path)
 234        #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
 235    }
 236
 237
 238    @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
 239        let notes = try Folder()
 240        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 241        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 242        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 243        session.open(file.path)
 244        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == false)
 245        try notes.write("setup.org", "#+TODO: NEXT WAIT | DONE\n")
 246        let text = session.document!.text
 247        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
 248        guard case .commit(let result) = CtrlCCtrlC().run(in: context) else { Issue.record("no commit"); return }
 249        #expect(result.effects.contains(.refreshSetup))
 250        session.refreshSetup()
 251        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 252        #expect(session.document?.isDirty == false)
 253    }
 254
 255    @Test func reloadingFromDiskReadsSetupFilesAgain() throws {
 256        let notes = try Folder()
 257        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 258        let file = try notes.write("a.org", "* WAIT One\n")
 259        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 260        session.open(file.path)
 261        try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 262        try notes.write("setup.org", "#+TODO: WAIT | DONE\n")
 263        session.fileChanged(file.path)
 264        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 265    }
 266
 267    @Test func missingFileReportsAnError() {
 268        let session = DocumentSession()
 269        session.open("/nonexistent/a.org")
 270        #expect(session.lastError != nil)
 271        #expect(session.document == nil)
 272    }
 273}
 274
 275@MainActor
 276struct SessionSavingTests {
 277    let notes: Folder
 278    let file: URL
 279    let recovery: FileRecoveryStore
 280    let session: DocumentSession
 281
 282    init() throws {
 283        notes = try Folder()
 284        file = try notes.write("a.org", "a\nb\nc\n")
 285        recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
 286        session = DocumentSession(recovery: recovery)
 287        session.saveMode = .explicit
 288        session.open(file.path)
 289    }
 290
 291    /// Types `text` at `offset`, as the editor would.
 292    func type(_ text: String, at offset: Int) throws {
 293        let buffer = StateBuffer(session.document!)
 294        session.attach(buffer)
 295        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
 296        session.bufferChanged()
 297    }
 298
 299    var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
 300
 301    @Test func saveWritesAndClearsDirty() throws {
 302        try type("x", at: 0)
 303        #expect(session.isDirty)
 304        #expect(session.save())
 305        #expect(!session.isDirty)
 306        #expect(disk == "xa\nb\nc\n")
 307    }
 308
 309    @Test func automaticModeSavesAfterTheDelay() async throws {
 310        session.saveMode = .automatic
 311        session.autosaveDelay = .milliseconds(10)
 312        try type("x", at: 0)
 313        #expect(disk == "a\nb\nc\n")
 314        await session.autosave?.value
 315        #expect(disk == "xa\nb\nc\n")
 316        #expect(!session.isDirty)
 317    }
 318
 319    @Test func explicitModeWaitsForSave() throws {
 320        try type("x", at: 0)
 321        #expect(session.autosave == nil)
 322    }
 323
 324    @Test func externalChangeMergesIntoEdits() throws {
 325        try type("x", at: 0)
 326        try notes.write("a.org", "a\nb\nC\n")
 327        session.fileChanged(file.path)
 328        #expect(session.document?.text == "xa\nb\nC\n")
 329        #expect(session.conflict == nil)
 330        #expect(session.save())
 331        #expect(disk == "xa\nb\nC\n")
 332    }
 333
 334    @Test func conflictKeepMine() throws {
 335        try type("x", at: 0)
 336        try notes.write("a.org", "z\nb\nc\n")
 337        session.fileChanged(file.path)
 338        #expect(session.conflict != nil)
 339        #expect(!session.save())
 340        #expect(disk == "z\nb\nc\n")
 341        session.keepMine()
 342        #expect(session.conflict == nil)
 343        #expect(disk == "xa\nb\nc\n")
 344        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 345        #expect(kept.contains("z\nb\nc\n"))
 346    }
 347
 348    @Test func conflictUseDiskVersion() throws {
 349        try type("x", at: 0)
 350        try notes.write("a.org", "z\nb\nc\n")
 351        #expect(!session.save())
 352        #expect(session.conflict != nil)
 353        session.useDiskVersion()
 354        #expect(session.conflict == nil)
 355        #expect(!session.isDirty)
 356        #expect(session.document?.text == "z\nb\nc\n")
 357        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 358        #expect(kept.contains("xa\nb\nc\n"))
 359    }
 360
 361    @Test func searchSeesUnsavedHeadings() async throws {
 362        let workspace = try WorkspaceModel(directory: nil)
 363        try await workspace.addRoot(notes.url)
 364        try type("* Unsaved heading\n", at: 0)
 365        let overlay = workspace.overlay(path: session.path, document: session.document)
 366        #expect(workspace.search("unsaved").isEmpty)
 367        #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
 368    }
 369}
 370
 371@MainActor
 372struct KeymapLoaderTests {
 373    @Test func layersTheUserFile() throws {
 374        let folder = try Folder()
 375        let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
 376        #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
 377
 378        let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
 379        let loaded = KeymapLoader.load(.emacs, userFile: file)
 380        #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
 381        #expect(loaded.problems == ["line 4: bad or missing keys"])
 382
 383        let broken = try folder.write("broken.toml", "keys = \"x")
 384        #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
 385    }
 386}
 387
 388@MainActor
 389struct MoveSubtreeTests {
 390    @Test func refileWithinAndAcrossFiles() async throws {
 391        let notes = try Folder()
 392        let file = try notes.write("a.org", "* one\nbody\n* two\n")
 393        let other = try notes.write("b.org", "* inbox\n")
 394        let workspace = try WorkspaceModel(directory: nil)
 395        try await workspace.addRoot(notes.url)
 396        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 397        session.saveMode = .explicit
 398        session.open(file.path)
 399        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 400        #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
 401
 402        #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
 403        #expect(session.document?.text == "* two\n** one\nbody\n")
 404
 405        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
 406        StateBufferCaret.set(session, 6)
 407        #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
 408        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 409        #expect(session.document?.text == "* two\n")
 410    }
 411
 412    @Test func archiveToTheArchiveFile() throws {
 413        let notes = try Folder()
 414        let file = try notes.write("a.org", "* done\n* keep\n")
 415        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 416        session.saveMode = .explicit
 417        session.open(file.path)
 418        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 419        #expect(session.document?.text == "* keep\n")
 420        let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
 421        #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 422    }
 423}
 424
 425@MainActor
 426struct AgendaActionTests {
 427    /// From the agenda: entries in files that aren't open move and archive on disk, and the
 428    /// current buffer stays as it was.
 429    @Test func refileAndArchiveFromAnEntry() async throws {
 430        let notes = try Folder()
 431        let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
 432        let other = try notes.write("b.org", "* inbox\n")
 433        let shown = try notes.write("c.org", "* shown\n")
 434        let workspace = try WorkspaceModel(directory: nil)
 435        try await workspace.addRoot(notes.url)
 436        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 437        session.saveMode = .explicit
 438        session.open(shown.path)
 439
 440        let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
 441        #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
 442        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 443        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
 444
 445        let text = try String(contentsOf: file, encoding: .utf8)
 446        let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
 447        #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
 448        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
 449
 450        #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 451        #expect(try String(contentsOf: file, encoding: .utf8) == "")
 452        #expect(session.path == shown.path && session.document?.text == "* shown\n")
 453    }
 454
 455    @Test func locatesMovedHeadings() throws {
 456        let notes = try Folder()
 457        let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
 458        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 459        #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
 460        #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
 461        #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
 462        #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
 463    }
 464}
 465
 466@MainActor
 467struct MoveIntoOpenBufferTests {
 468    /// A target open with unsaved edits above its heading takes the subtree in its buffer,
 469    /// under the right heading, and the disk keeps the saved text.
 470    @Test func refileIntoAnOpenBuffer() async throws {
 471        let notes = try Folder()
 472        let file = try notes.write("a.org", "* task\nbody\n")
 473        let other = try notes.write("b.org", "* inbox\n* projects\n")
 474        let workspace = try WorkspaceModel(directory: nil)
 475        try await workspace.addRoot(notes.url)
 476        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 477        session.saveMode = .explicit
 478        session.open(other.path)
 479        let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
 480        _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
 481        session.open(file.path)
 482        #expect(session.refile(to: projects) == "Refiled to b.org/projects")
 483        #expect(session.document?.text == "")
 484        #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
 485        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
 486    }
 487
 488    @Test func archiveIntoAnOpenBuffer() throws {
 489        let notes = try Folder()
 490        let file = try notes.write("a.org", "* done\n* keep\n")
 491        let archive = try notes.write("a.org_archive", "* old\n")
 492        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 493        session.saveMode = .explicit
 494        session.open(archive.path)
 495        session.open(file.path)
 496        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 497        #expect(session.document?.text == "* keep\n")
 498        let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
 499        #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 500        #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
 501    }
 502}
 503
 504/// Inserts text at the caret, for tests.
 505struct InsertText: OrgCommand {
 506    let text: String
 507    var id: String { "test.insert" }
 508    var title: String { "Insert" }
 509    func applies(in context: EditContext) -> Bool { true }
 510    func run(in context: EditContext) -> CommandStep {
 511        .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
 512    }
 513}
 514
 515/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
 516@MainActor
 517enum StateBufferCaret {
 518    static func set(_ session: DocumentSession, _ offset: Int) {
 519        let buffer = StateBuffer(session.document!)
 520        buffer.selection = [offset..<offset]
 521        session.attach(buffer)
 522    }
 523}
 524
 525@MainActor
 526struct AgendaModelTests {
 527    @Test func openBuffersFollowTheirText() async throws {
 528        let notes = try Folder()
 529        let file = try notes.write("a.org", "* TODO One\n")
 530        let model = try WorkspaceModel(directory: nil)
 531        try await model.addRoot(notes.url)
 532        let agenda = AgendaModel(workspace: model)
 533        agenda.mode = .todo(keywords: nil)
 534        for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
 535            await agenda.refresh(open: [file.path: text])
 536            #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
 537        }
 538        await agenda.refresh(open: [:])
 539        #expect(agenda.list.map(\.text) == ["TODO One"])
 540    }
 541
 542    @Test func entriesKnowTheirDoneKeyword() async throws {
 543        let notes = try Folder()
 544        try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
 545        try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 546        let plain = try notes.write("b.org", "* WAIT Two\n")
 547        let model = try WorkspaceModel(directory: nil)
 548        model.settings = .with(todoKeywords: try #require(OrgSettings.default.withTodoKeywords("WAIT | OK")))
 549        try await model.addRoot(notes.url)
 550        let agenda = AgendaModel(workspace: model)
 551        agenda.mode = .todo(keywords: nil)
 552        await agenda.refresh(open: [:])
 553        #expect(Dictionary(uniqueKeysWithValues: agenda.list.map { ($0.todo ?? "", $0.doneKeyword) }) == ["NEXT": "FINISHED", "WAIT": "OK"])
 554        await agenda.refresh(open: [plain.path: "#+TODO: WAIT | GONE\n* WAIT Two\n"])
 555        #expect(agenda.list.first { $0.todo == "WAIT" }?.doneKeyword == "GONE")
 556    }
 557
 558    @Test func topLevelFilesAndTheOpenBuffer() async throws {
 559        let notes = try Folder()
 560        try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
 561        try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
 562        try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
 563        let model = try WorkspaceModel(directory: nil)
 564        try await model.addRoot(notes.url)
 565        let agenda = AgendaModel(workspace: model)
 566        agenda.startOffset = -3
 567        var utc = Calendar(identifier: .gregorian)
 568        utc.timeZone = TimeZone(identifier: "UTC")!
 569        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
 570
 571        await agenda.refresh(open: [:], now: now, calendar: utc)
 572        #expect(agenda.days.count == 10)
 573        #expect(agenda.days[3].isToday)
 574        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
 575
 576        agenda.includeSubfolders = true
 577        await agenda.refresh(open: [:], now: now, calendar: utc)
 578        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
 579
 580        let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
 581        await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
 582        #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
 583
 584        agenda.shift(forward: true, now: now, calendar: utc)
 585        await agenda.refresh(open: [:], now: now, calendar: utc)
 586        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
 587
 588        // org-agenda-start-on-weekday: a week starts on Monday by default, from a Wednesday.
 589        let wednesday = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 7, hour: 9)))
 590        agenda.showToday()
 591        agenda.span = 7
 592        agenda.startOffset = 0
 593        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 594        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 5))
 595        agenda.startOnWeekday = 0
 596        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 597        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 4))
 598        agenda.shift(forward: true, now: wednesday, calendar: utc)
 599        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 600        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 11))
 601        agenda.showToday()
 602        agenda.startOnWeekday = nil
 603        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 604        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
 605        agenda.startOnWeekday = 1
 606        agenda.span = 10
 607        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 608        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
 609    }
 610}
 611
 612@MainActor
 613struct AgendaCommandTests {
 614    @Test func loadsViews() throws {
 615        let folder = try Folder()
 616        let file = try folder.write("views.toml", """
 617        [[view]]
 618        name = "Work"
 619        type = "match"
 620        match = "+work"
 621        [[view]]
 622        name = "Week"
 623        span = 7
 624        start = -1
 625        [[view]]
 626        name = "Waiting"
 627        type = "todo"
 628        keywords = "WAIT|HOLD"
 629        [[view]]
 630        name = "Broken"
 631        type = "match"
 632        """)
 633        let loaded = AgendaViewLoader.load(userFile: file)
 634        #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Work", "Week", "Waiting"])
 635        #expect(loaded.views[2].mode == .match("+work", todoOnly: false))
 636        #expect(loaded.views[3].mode == .agenda(span: 7, startOffset: -1))
 637        #expect(loaded.views[4].mode == .todo(keywords: "WAIT|HOLD"))
 638        #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
 639    }
 640
 641    @Test func todoListMode() async throws {
 642        let notes = try Folder()
 643        try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
 644        let model = try WorkspaceModel(directory: nil)
 645        try await model.addRoot(notes.url)
 646        let agenda = AgendaModel(workspace: model)
 647        agenda.mode = .todo(keywords: nil)
 648        await agenda.refresh(open: [:])
 649        #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
 650        agenda.mode = .match("work", todoOnly: false)
 651        await agenda.refresh(open: [:])
 652        #expect(agenda.list.map(\.text) == ["TODO One"])
 653    }
 654
 655    @Test func runsCommandsOnClosedAndOpenFiles() throws {
 656        let notes = try Folder()
 657        let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
 658        let b = try notes.write("b.org", "* TODO Three\n")
 659        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 660        session.open(a.path)
 661
 662        // A closed file is changed on disk.
 663        let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 664        guard case .commit = closed else { Issue.record("\(closed)"); return }
 665        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 666
 667        // The open file changes in its buffer.
 668        let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
 669        guard case .commit = open else { Issue.record("\(open)"); return }
 670        #expect(session.document?.text == "* TODO One\n* DONE Two\n")
 671
 672        // A heading that moved is refused.
 673        let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 674        guard case .failed = stale else { Issue.record("\(stale)"); return }
 675        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 676    }
 677}
 678
 679final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
 680    private let lock = NSLock()
 681    private var pending: [String] = ["someone.else"]
 682    var authorized = true
 683    private(set) var added: [String] = []
 684
 685    func authorize() async -> Bool { authorized }
 686    func pendingIDs() async -> [String] { lock.withLock { pending } }
 687    var delivered: [String] = []
 688    func deliveredIDs() async -> [String] { lock.withLock { delivered } }
 689    /// The system showing a notification: no longer pending.
 690    func fire(_ id: String, keep: Bool) {
 691        lock.withLock {
 692            pending.removeAll { $0 == id }
 693            if keep { delivered.append(id) }
 694        }
 695    }
 696    func add(_ reminder: Reminder) async throws {
 697        lock.withLock {
 698            pending.append(reminder.id)
 699            added.append(reminder.id)
 700        }
 701    }
 702    func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
 703    var ids: [String] { lock.withLock { pending } }
 704}
 705
 706@MainActor
 707struct ReminderSchedulerTests {
 708    func reminder(_ id: String, _ minutes: Double) -> Reminder {
 709        let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
 710        return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
 711    }
 712
 713    @Test func reconciles() async {
 714        let center = FakeReminderCenter()
 715        let scheduler = ReminderScheduler(center: center)
 716        await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
 717        #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
 718        #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
 719
 720        await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
 721        #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
 722        #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
 723
 724        await scheduler.clear()
 725        #expect(center.ids == ["someone.else"])
 726        #expect(scheduler.scheduledThrough == nil)
 727
 728        // Fired reminders aren't set again, whether or not they're still in Notification Center.
 729        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
 730        center.fire("orgstar.e", keep: false)
 731        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
 732        #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
 733        let relaunched = ReminderScheduler(center: center)
 734        center.fire("orgstar.f", keep: true)
 735        await relaunched.reconcile([reminder("f", 6)])
 736        #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
 737        await scheduler.clear()
 738
 739        center.authorized = false
 740        await scheduler.reconcile([reminder("d", 4)])
 741        #expect(!scheduler.isAuthorized)
 742        #expect(center.ids == ["someone.else"])
 743    }
 744}
 745
 746@MainActor
 747struct EmacsFallbackTests {
 748    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 749    func recalculatesTablesNativeCodeCannot() async throws {
 750        let notes = try Folder()
 751        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")
 752        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 753        session.open(file.path)
 754        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
 755        guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
 756            Issue.record("\(step)")
 757            return
 758        }
 759        #expect(reason == "non-numeric field a")
 760        #expect(!lisp)
 761        let message = await session.recalculateInEmacs(table: table, point: point, form: form)
 762        #expect(message == "Recalculated in Emacs")
 763        #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")
 764    }
 765
 766    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 767    func cancelingARecalculationLeavesTheTable() async throws {
 768        let notes = try Folder()
 769        let text = "| n | twice |\n|---+-------|\n| a |       |\n#+TBLFM: $2=$1*2\n"
 770        let file = try notes.write("t.org", text)
 771        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 772        session.open(file.path)
 773        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
 774        guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else {
 775            Issue.record("\(step)")
 776            return
 777        }
 778        let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) }
 779        task.cancel()
 780        #expect(await task.value == "Recalculation canceled")
 781        #expect(session.document?.text == text)
 782    }
 783}
 784
 785@MainActor
 786struct BabelSessionTests {
 787    @Test func runsBlocksAndWritesResults() async throws {
 788        let notes = try Folder()
 789        let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
 790        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 791        session.open(file.path)
 792        let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
 793        guard case .external(.babel(let job)) = step else {
 794            Issue.record("\(step)")
 795            return
 796        }
 797        #expect(await session.runBabel(job) == "Code block evaluation complete.")
 798        // A column that is half numbers is right-aligned, as org-table-align does.
 799        #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n|     42 |\n")
 800    }
 801}
 802
 803@MainActor
 804struct BabelErrorTests {
 805    func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
 806        guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
 807            throw CancellationError()
 808        }
 809        return job
 810    }
 811
 812    /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
 813    @Test func reportsErrorsAndStillInsertsResults() async throws {
 814        let notes = try Folder()
 815        let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
 816        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 817        session.open(file.path)
 818        #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
 819        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
 820    }
 821
 822    @Test func cancelsARunningBlock() async throws {
 823        let notes = try Folder()
 824        let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
 825        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 826        session.open(file.path)
 827        let start = ContinuousClock.now
 828        var message: String?
 829        session.startBabel(try job(session, file.path)) { message = $0 }
 830        #expect(session.isRunningBabel)
 831        try await Task.sleep(for: .milliseconds(200))
 832        session.cancelBabel()
 833        while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
 834        #expect(message == "Code block canceled.")
 835        #expect(!session.isRunningBabel)
 836        #expect(ContinuousClock.now - start < .seconds(5))
 837        #expect(session.document?.text.contains("#+RESULTS:") == false)
 838    }
 839}
 840
 841struct EmacsExportTests {
 842    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 843    func exportsBesideTheFile() async throws {
 844        let notes = try Folder()
 845        let file = try notes.write("doc.org", "#+TITLE: On disk\n")
 846        // The buffer's text is exported, not the file's.
 847        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")
 848        #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
 849        let text = try String(contentsOfFile: written, encoding: .utf8)
 850        #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
 851        #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
 852    }
 853
 854    /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used.
 855    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 856    func exportsTheSubtreeBodyOnly() async throws {
 857        let notes = try Folder()
 858        let file = try notes.write("doc.org", "")
 859        let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n"
 860        let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1
 861        let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true)
 862        #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt")
 863        let out = try String(contentsOfFile: written, encoding: .utf8)
 864        #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)")
 865    }
 866
 867    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 868    func exportUsesBabelPath() async throws {
 869        let notes = try Folder()
 870        let file = try notes.write("doc.org", "")
 871        let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"#
 872        let written = try await EmacsRunner.export(text: "", path: file.path, function: function)
 873        #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"])
 874    }
 875
 876    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 877    func cancellingStopsTheExport() async throws {
 878        let notes = try Folder()
 879        let file = try notes.write("doc.org", "")
 880        let pidFile = notes.url.appendingPathComponent("pid")
 881        let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"#
 882        let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) }
 883        var pid: pid_t?
 884        for _ in 0..<200 where pid == nil {
 885            try await Task.sleep(for: .milliseconds(50))
 886            pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) }
 887        }
 888        let started = try #require(pid)
 889        export.cancel()
 890        await #expect(throws: CancellationError.self) { try await export.value }
 891        var alive = true
 892        for _ in 0..<100 where alive {
 893            alive = kill(started, 0) == 0
 894            if alive { try await Task.sleep(for: .milliseconds(50)) }
 895        }
 896        #expect(!alive)
 897    }
 898}
 899
 900@MainActor
 901struct CaptureAppTests {
 902    @Test func loadsTemplates() throws {
 903        let folder = try Folder()
 904        let file = try folder.write("capture.toml", """
 905        [[template]]
 906        key = "w"
 907        name = "Work"
 908        file = "work.org"
 909        olp = "Projects/Work"
 910        template = "* TODO %?\\n%a"
 911        [[template]]
 912        key = "j"
 913        type = "plain"
 914        file = "~/journal.org"
 915        template = "%U %?"
 916        prepend = true
 917        """)
 918        let loaded = CaptureTemplates.load(userFile: file)
 919        #expect(loaded.problems.isEmpty)
 920        #expect(loaded.templates.map(\.key) == ["w", "j"])
 921        #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
 922        #expect(loaded.templates[0].template == "* TODO %?\n%a")
 923        #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
 924        try """
 925        [[template]]
 926        key = "d"
 927        file = "journal.org"
 928        datetree = true
 929        olp = "Journal"
 930        tree-type = "month"
 931        template = "* %?"
 932        empty-lines-after = 1
 933        jump-to-captured = true
 934        [[template]]
 935        key = "i"
 936        id = "abc"
 937        template = "* %?"
 938        clock-in = true
 939        clock-resume = true
 940        [[template]]
 941        key = "k"
 942        clock = true
 943        type = "item"
 944        template = "%?"
 945        immediate-finish = true
 946        """.write(to: file, atomically: true, encoding: .utf8)
 947        let targets = CaptureTemplates.load(userFile: file)
 948        #expect(targets.problems.isEmpty)
 949        #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
 950        #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
 951        #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
 952        #expect(targets.templates[2].options.immediateFinish)
 953        #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
 954    }
 955
 956    @Test func capturesIntoClosedMissingAndOpenFiles() throws {
 957        let notes = try Folder()
 958        let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
 959        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 960        let template = CaptureTemplates.defaults[0]
 961        let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
 962        #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
 963        #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
 964
 965        _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
 966        #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
 967
 968        session.open(todo.path)
 969        _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
 970        #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
 971
 972        // An ID's file is resolved by the caller.
 973        let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
 974        let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
 975        _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
 976        #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
 977    }
 978}
 979
 980@MainActor
 981struct ClockModelTests {
 982    @Test func clocksInAndOutAcrossFiles() throws {
 983        let notes = try Folder()
 984        let work = try notes.write("work.org", "* Task\nBody\n")
 985        let other = try notes.write("other.org", "* Other\n")
 986        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 987        session.open(work.path)
 988        session.reveal(2)
 989        let stateFile = notes.url.appendingPathComponent("clock.json")
 990        let clock = ClockModel(file: stateFile)
 991        var utc = Calendar(identifier: .gregorian)
 992        utc.timeZone = TimeZone(identifier: "UTC")!
 993        let start = Date(timeIntervalSince1970: 1_789_000_000)
 994        _ = clock.clockIn(session, now: start)
 995        #expect(clock.running?.heading == "Task")
 996        #expect(ClockModel(file: stateFile).running == clock.running)
 997
 998        // Out from another file: the clocked file's buffer is still open behind it and takes
 999        // the change.
1000        session.open(other.path)
1001        let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
1002        #expect(message == "Clock stopped after 1:35")
1003        #expect(clock.running == nil)
1004        #expect(session.dirtyPaths == [work.path])
1005        #expect(session.saveAll())
1006        let text = try String(contentsOf: work, encoding: .utf8)
1007        #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=>  1:35\n:END:\nBody\n"), "\(text)")
1008    }
1009}
1010
1011@MainActor
1012struct BufferTests {
1013    @Test func buffersKeepEditsWhileOthersShow() throws {
1014        let notes = try Folder()
1015        let a = try notes.write("a.org", "* A\n")
1016        let b = try notes.write("b.org", "* B\n")
1017        let c = try notes.write("c.org", "* C\n")
1018        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1019        session.saveMode = .explicit
1020        session.open(a.path)
1021        _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
1022        session.open(b.path)
1023        #expect(session.path == b.path)
1024        #expect(session.openPaths == [a.path, b.path])
1025        #expect(session.dirtyPaths == [a.path])
1026        // A background buffer takes commands for its file, not the disk.
1027        _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
1028        #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
1029        #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
1030
1031        session.open(a.path)
1032        #expect(session.document?.text.hasPrefix("* DONE A") == true)
1033        session.open(c.path)
1034        // Opened after the current buffer.
1035        #expect(session.openPaths == [a.path, c.path, b.path])
1036        session.cycle(1)
1037        #expect(session.path == b.path)
1038        session.cycle(1)
1039        #expect(session.path == a.path)
1040        session.showPrevious()
1041        #expect(session.path == b.path)
1042        #expect(session.recentPaths == [b.path, a.path, c.path])
1043
1044        session.kill(b.path)
1045        #expect(session.path == a.path)
1046        #expect(session.openPaths == [a.path, c.path])
1047        #expect(session.saveAll())
1048        #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
1049        session.kill(a.path)
1050        session.kill(c.path)
1051        #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
1052    }
1053
1054    @Test func backgroundBuffersFollowTheDisk() throws {
1055        let notes = try Folder()
1056        let a = try notes.write("a.org", "* A\n")
1057        let b = try notes.write("b.org", "* B\n")
1058        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1059        session.open(a.path)
1060        session.open(b.path)
1061        try notes.write("a.org", "* A changed\n")
1062        session.fileChanged(a.path)
1063        #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
1064    }
1065}
1066
1067@MainActor
1068struct LinkFollowTests {
1069    @Test func followsLinksOfEachKind() async throws {
1070        let notes = try Folder()
1071        let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
1072        let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
1073        _ = try notes.write("pic.png", "not really")
1074        let workspace = try WorkspaceModel(directory: nil)
1075        try await workspace.addRoot(notes.url)
1076        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1077        session.open(a.path)
1078        let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
1079        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1080
1081        #expect(follow("here") == .shown)
1082        #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
1083        #expect(follow("#two") == .shown)
1084        #expect(follow("Second") == .shown)
1085        #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
1086
1087        #expect(follow("file:sub/b.org::5") == .shown)
1088        #expect(session.path == b.path)
1089        #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
1090        session.open(a.path)
1091        #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
1092        session.open(a.path)
1093        #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
1094        #expect(follow("id:none") == .message("No heading has the ID none"))
1095        // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
1096        #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
1097        #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
1098        #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
1099        #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
1100        #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1101    }
1102
1103    @Test func followsAttachmentAndRadioLinks() throws {
1104        let notes = try Folder()
1105        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"
1106        let a = try notes.write("a.org", text)
1107        let scan = try notes.write("data/ab/12-cd/scan.pdf", "pdf")
1108        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1109        session.open(a.path)
1110        let tree = try #require(session.document?.tree)
1111        func follow(_ needle: String) throws -> LinkFollow {
1112            let link = try #require(Links.link(at: (text as NSString).range(of: needle).location + 1, text: text, tree: tree)?.link)
1113            return session.follow(link, workspace: nil, isText: { $0.hasSuffix(".org") })
1114        }
1115        #expect(try follow("attachment:") == .openExternally(URL(fileURLWithPath: (scan.path as NSString).standardizingPath)))
1116        #expect(try follow("The Plan") == .shown)
1117        #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location)
1118    }
1119}