Tests/OrgAppTests/AppTests.swift

1395 lines · 71942 bytes

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