Tests/OrgAppTests/AppTests.swift

f18103132ab04144c6fafa0d2e50f7c201126344
orgstar/Tests/OrgAppTests/AppTests.swift

990 lines · 47843 bytes

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