Tests/OrgAppTests/AppTests.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Tests/OrgAppTests/AppTests.swift

1620 lines · 83247 bytes

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

Global

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

Repository & editor

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