Tests/OrgAppTests/AppTests.swift

daac3706d5aa523bc907d6118edd28cbc0767283
orgstar/Tests/OrgAppTests/AppTests.swift

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