Tests/OrgEditorAppKitTests/EditorTests.swift

474 lines · 20984 bytes

  1import AppKit
  2import OrgCore
  3import OrgDocument
  4import OrgPresentation
  5@testable import OrgApp
  6import Testing
  7@testable import OrgEditorAppKit
  8
  9/// An editor in an offscreen window, laid out.
 10@MainActor
 11final class Harness {
 12    let editor: OrgEditor
 13    let window: NSWindow
 14
 15    convenience init(_ text: String) {
 16        self.init(DocumentState(bytes: Array(text.utf8)))
 17        drainStyling()
 18        layout()
 19    }
 20
 21    /// The editor as a window would show it first: background styling not yet run.
 22    init(_ document: DocumentState, layout: Bool = true, mode: OrgEditor.Mode = .org) {
 23        _ = NSApplication.shared
 24        editor = OrgEditor(document: document, mode: mode)
 25        window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 800), styleMask: [.titled], backing: .buffered, defer: false)
 26        window.contentView = editor.makeScrollView()
 27        window.makeFirstResponder(editor.textView)
 28        if layout { self.layout() }
 29    }
 30
 31    func drainStyling() {
 32        editor.finishStyling()
 33    }
 34
 35    var textView: NSTextView { editor.textView }
 36    var string: String { textView.string }
 37
 38    func layout() {
 39        let manager = editor.textLayoutManager
 40        manager.ensureLayout(for: manager.documentRange)
 41    }
 42
 43    /// Text of each laid-out paragraph.
 44    var visibleLines: [String] {
 45        layout()
 46        let manager = editor.textLayoutManager
 47        var lines: [String] = []
 48        manager.enumerateTextLayoutFragments(from: manager.documentRange.location, options: [.ensuresLayout]) { fragment in
 49            let content = manager.textContentManager!
 50            let start = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
 51            let end = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.endLocation)
 52            lines.append((self.string as NSString).substring(with: NSRange(location: start, length: end - start)))
 53            return true
 54        }
 55        return lines.filter { !$0.isEmpty }
 56    }
 57
 58    func caret(at offset: Int) {
 59        textView.setSelectedRange(NSRange(location: offset, length: 0))
 60    }
 61
 62    var caret: Int { textView.selectedRange().location }
 63
 64    func offset(of line: String) -> Int {
 65        (string as NSString).range(of: line).location
 66    }
 67
 68    func checkInSync() {
 69        #expect(editor.document.text == string)
 70        #expect(editor.document.tree.green == OrgParser.parse(string).green)
 71    }
 72}
 73
 74let outline = "* a\nbody\n** b\nmore\n* c\ntext\n"
 75
 76@MainActor
 77struct FoldingTests {
 78    @Test func foldingHidesTheSubtree() {
 79        let h = Harness(outline)
 80        #expect(h.visibleLines == ["* a\n", "body\n", "** b\n", "more\n", "* c\n", "text\n"])
 81        h.caret(at: 1)
 82        #expect(h.editor.cycleAtCaret())
 83        #expect(h.visibleLines == ["* a\n", "* c\n", "text\n"])
 84        h.editor.cycleAtCaret()
 85        #expect(h.visibleLines == ["* a\n", "body\n", "** b\n", "* c\n", "text\n"])
 86        h.editor.cycleAtCaret()
 87        #expect(h.visibleLines.count == 6)
 88    }
 89
 90    @Test func globalCycleAndStartup() {
 91        let h = Harness(outline)
 92        h.editor.run("org.cycle-global")
 93        h.editor.run("org.cycle-global")
 94        #expect(h.visibleLines == ["* a\n", "** b\n", "* c\n"])
 95        h.editor.run("org.cycle-global")
 96        #expect(h.visibleLines.count == 6)
 97        #expect(Harness("#+STARTUP: overview\n" + outline).visibleLines == ["#+STARTUP: overview\n", "* a\n", "* c\n"])
 98    }
 99
100    @Test func revealUnfoldsWhatHidesTheTarget() {
101        let h = Harness("#+STARTUP: overview\n" + outline)
102        let target = h.offset(of: "more")
103        h.editor.reveal(target)
104        #expect(h.visibleLines.contains("more\n"))
105        #expect(h.caret == target)
106    }
107
108    @Test func readOnlyAndReloadKeepFolds() {
109        let editor = OrgEditor(document: DocumentState(bytes: Array(outline.utf8)), editable: false)
110        #expect(!editor.textView.isEditable)
111        editor.setFolds(FoldState(folds: [19]))
112        editor.diskChanged(to: Array(("new line\n" + outline).utf8))
113        #expect(editor.document.text == "new line\n" + outline)
114        #expect(editor.foldState.folds == [28])
115    }
116
117    @Test func tabFoldsOnlyOnHeadings() {
118        let h = Harness(outline)
119        h.caret(at: 5)
120        #expect(!h.editor.cycleAtCaret())
121        h.editor.run("org.cycle-global")
122        #expect(h.visibleLines == ["* a\n", "* c\n"])
123    }
124
125    @Test func caretMovesOverFoldedText() {
126        let h = Harness(outline)
127        h.caret(at: 1)
128        h.editor.cycleAtCaret()
129        h.caret(at: 0)
130        h.textView.moveDown(nil)
131        #expect(h.caret >= h.offset(of: "* c") && h.caret < h.offset(of: "text"))
132        h.caret(at: 3)
133        h.textView.moveRight(nil)
134        #expect(h.caret == h.offset(of: "* c"))
135        h.textView.moveLeft(nil)
136        #expect(h.caret == 3)
137    }
138
139    @Test func newHeadingAtTheEndOfAFoldedHeadingGoesAfterItsSubtree() {
140        let h = Harness(outline)
141        h.caret(at: 1)
142        h.editor.cycleAtCaret()
143        h.caret(at: 3)
144        h.editor.run("org.heading.insert")
145        #expect(h.string == "* a\nbody\n** b\nmore\n* \n* c\ntext\n")
146    }
147
148    @Test func copyingAcrossAFoldIncludesHiddenText() {
149        let h = Harness(outline)
150        h.caret(at: 1)
151        h.editor.cycleAtCaret()
152        h.textView.setSelectedRange(NSRange(location: 0, length: h.offset(of: "text")))
153        let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)"))
154        defer { pasteboard.releaseGlobally() }
155        #expect(h.textView.writeSelection(to: pasteboard, types: h.textView.writablePasteboardTypes))
156        #expect(pasteboard.string(forType: .string) == "* a\nbody\n** b\nmore\n* c\n")
157    }
158
159    @Test func opensWithTheCaretAtTheStart() {
160        let h = Harness("* a\nbody\n* b\n")
161        #expect(h.textView.selectedRange() == NSRange(location: 0, length: 0))
162    }
163
164    @Test func drawersFoldAtOpenAndToggleWithTab() {
165        let text = "* a\n:PROPERTIES:\n:ID: x\n:END:\nbody\n#+begin_src sh\necho\n#+end_src\n* c\n"
166        let h = Harness(text)
167        #expect(h.visibleLines == ["* a\n", ":PROPERTIES:\n", "body\n", "#+begin_src sh\n", "echo\n", "#+end_src\n", "* c\n"])
168        h.caret(at: h.offset(of: ":PROPERTIES:"))
169        #expect(h.editor.cycleAtCaret())
170        #expect(h.visibleLines.count == 9)
171        h.caret(at: h.offset(of: "#+end_src"))
172        #expect(h.editor.cycleAtCaret())
173        #expect(h.visibleLines == ["* a\n", ":PROPERTIES:\n", ":ID: x\n", ":END:\n", "body\n", "#+begin_src sh\n", "* c\n"])
174        #expect(h.textView.selectedRange().location == h.offset(of: "#+begin_src"))
175        // Heading cycling leaves the block folded.
176        h.caret(at: 1)
177        h.editor.cycleAtCaret()
178        h.editor.cycleAtCaret()
179        #expect(h.visibleLines.contains("#+begin_src sh\n") && !h.visibleLines.contains("echo\n"))
180        #expect(Harness("#+STARTUP: nohidedrawers\n" + text).visibleLines.contains(":ID: x\n"))
181        let folded = Harness(text)
182        folded.editor.reveal(folded.offset(of: ":ID: x") + 1)
183        #expect(folded.visibleLines.contains(":ID: x\n"))
184    }
185
186    @Test func drawerFoldsFollowEdits() {
187        let h = Harness("* a\n:PROPERTIES:\n:ID: x\n:END:\nbody\n* b\n:LOGBOOK:\nl\n:END:\n")
188        h.caret(at: h.offset(of: "body") + 4)
189        h.textView.insertText(" more", replacementRange: h.textView.selectedRange())
190        h.textView.insertNewline(nil)
191        h.caret(at: 2)
192        h.textView.insertText("new ", replacementRange: h.textView.selectedRange())
193        #expect(h.visibleLines == ["* new a\n", ":PROPERTIES:\n", "body more\n", "\n", "* b\n", ":LOGBOOK:\n"])
194        // Renaming the drawer's opening line keeps a drawer, and its fold.
195        h.caret(at: h.offset(of: ":LOGBOOK:") + 1)
196        h.textView.insertText("X", replacementRange: h.textView.selectedRange())
197        #expect(h.visibleLines.last == ":XLOGBOOK:\n")
198        h.checkInSync()
199    }
200
201    @Test func foldsFollowEdits() {
202        let h = Harness(outline)
203        h.caret(at: h.offset(of: "* c") + 1)
204        h.editor.cycleAtCaret()
205        h.caret(at: 0)
206        h.textView.insertText("new ", replacementRange: NSRange(location: 2, length: 0))
207        #expect(h.visibleLines == ["* new a\n", "body\n", "** b\n", "more\n", "* c\n"])
208        h.checkInSync()
209    }
210}
211
212@MainActor
213struct EditingTests {
214    @Test func typingKeepsTheDocumentInSync() {
215        let h = Harness(outline)
216        h.caret(at: h.offset(of: "body") + 4)
217        h.textView.insertText(" *bold*", replacementRange: h.textView.selectedRange())
218        h.textView.insertNewline(nil)
219        h.textView.insertText("* new heading", replacementRange: h.textView.selectedRange())
220        h.textView.deleteBackward(nil)
221        h.checkInSync()
222        #expect(h.editor.document.isDirty)
223    }
224
225    @Test func inputMethodComposition() {
226        let h = Harness("* a\n")
227        h.caret(at: 3)
228        h.textView.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
229        #expect(h.textView.hasMarkedText())
230        h.textView.setMarkedText("かん", selectedRange: NSRange(location: 2, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
231        h.textView.insertText("漢", replacementRange: NSRange(location: NSNotFound, length: 0))
232        #expect(!h.textView.hasMarkedText())
233        #expect(h.string == "* a漢\n")
234        h.checkInSync()
235    }
236
237    @Test func undoKeepsTheDocumentInSync() {
238        let h = Harness(outline)
239        h.caret(at: 3)
240        h.textView.insertText("xyz", replacementRange: h.textView.selectedRange())
241        h.textView.breakUndoCoalescing()
242        h.textView.undoManager?.undo()
243        #expect(h.string == outline)
244        h.checkInSync()
245    }
246
247    @Test func styling() throws {
248        let h = Harness("** b\nbody\n")
249        let storage = try #require(h.textView.textStorage)
250        #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
251        let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
252        #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
253        h.caret(at: 0)
254        h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
255        let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
256        #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
257    }
258
259    @Test func accessibilityReadsTheWholeText() {
260        let h = Harness(outline)
261        h.caret(at: 1)
262        h.editor.cycleAtCaret()
263        #expect(h.textView.accessibilityValue() as? String == outline)
264        h.textView.setSelectedRange(NSRange(location: 0, length: 3))
265        #expect(h.textView.accessibilitySelectedText() == "* a")
266        #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
267    }
268
269    @Test func saveWritesAndClearsDirty() throws {
270        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
271        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
272        defer { try? FileManager.default.removeItem(at: folder) }
273        let file = folder.appendingPathComponent("a.org")
274        try Data(outline.utf8).write(to: file)
275        let h = Harness(outline)
276        h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
277        let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
278        #expect(try h.editor.save(using: saver, to: file) == .saved)
279        #expect(!h.editor.document.isDirty)
280        #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
281    }
282}
283
284@MainActor
285struct BufferTests {
286    @Test func updateMapsCaretAndFoldsAndClearsUndo() {
287        let h = Harness(outline)
288        var changes = 0
289        h.editor.onChange = { changes += 1 }
290        h.caret(at: 1)
291        h.textView.insertText("x", replacementRange: NSRange(location: 4, length: 0))
292        #expect(changes == 1)
293        RunLoop.current.run(until: Date())
294        #expect(h.textView.undoManager?.canUndo == true)
295        h.editor.setFolds(FoldState(folds: [h.offset(of: "** b")]))
296        h.caret(at: h.offset(of: "* c") + 2)
297        h.editor.update { $0 = DocumentState(bytes: Array(("new\n" + outline).utf8)) }
298        #expect(changes == 2)
299        #expect(h.string == "new\n" + outline)
300        #expect(h.caret == h.offset(of: "* c") + 2)
301        #expect(h.editor.foldState.folds == [h.offset(of: "** b")])
302        #expect(h.textView.undoManager?.canUndo != true)
303        h.checkInSync()
304    }
305
306    /// Each buffer's editor reports its own changes: a background buffer's edit saves its
307    /// file, not the shown one's.
308    @Test func backgroundEditorsSaveTheirOwnFiles() async throws {
309        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
310        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
311        defer { try? FileManager.default.removeItem(at: folder) }
312        let a = folder.appendingPathComponent("a.org"), b = folder.appendingPathComponent("b.org")
313        try Data("* A\n".utf8).write(to: a)
314        try Data("* B\n".utf8).write(to: b)
315        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
316        session.autosaveDelay = .milliseconds(10)
317        var harnesses: [String: Harness] = [:]
318        for file in [a, b] {
319            session.open(file.path)
320            let h = Harness(try #require(session.document))
321            let path = file.path
322            h.editor.onChange = { [weak session] in session?.bufferChanged(path) }
323            session.attach(h.editor)
324            harnesses[path] = h
325        }
326        #expect(session.path == b.path)
327        harnesses[a.path]!.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
328        #expect(session.dirtyPaths == [a.path])
329        #expect(!session.isDirty)
330        for _ in 0..<50 where (try? String(contentsOf: a, encoding: .utf8)) != "x* A\n" {
331            try await Task.sleep(for: .milliseconds(20))
332        }
333        #expect(try String(contentsOf: a, encoding: .utf8) == "x* A\n")
334    }
335
336    /// The wiring the app uses: the editor is the session's buffer and reports typing.
337    @Test func sessionSavesWhatIsTyped() async throws {
338        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
339        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
340        defer { try? FileManager.default.removeItem(at: folder) }
341        let file = folder.appendingPathComponent("a.org")
342        try Data(outline.utf8).write(to: file)
343        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
344        session.autosaveDelay = .milliseconds(10)
345        session.open(file.path)
346        let h = Harness(try #require(session.document))
347        h.editor.onChange = { [weak session] in session?.bufferChanged() }
348        session.attach(h.editor)
349        h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
350        #expect(session.isDirty)
351        await session.autosave?.value
352        #expect(!session.isDirty)
353        #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
354
355        try Data(("x" + outline + "end\n").utf8).write(to: file)
356        session.fileChanged(file.path)
357        #expect(h.string == "x" + outline + "end\n")
358    }
359}
360
361@MainActor
362struct RestyleTests {
363    func indent(_ h: Harness, at line: String) -> CGFloat? {
364        let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
365        return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
366    }
367
368    @Test func newHeadingReindentsTheLinesItTakesOver() {
369        let h = Harness("* a\none\ntwo\nthree\n")
370        h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
371        #expect(indent(h, at: "one") == 2)
372        #expect(indent(h, at: "three") == 3)
373        h.checkInSync()
374    }
375
376    @Test func joiningAwayAHeadingReindentsItsBody() {
377        let h = Harness("* a\none\n** b\ntwo\nthree\n")
378        h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
379        #expect(indent(h, at: "three") == 2)
380        h.checkInSync()
381    }
382
383    @Test func typingASpaceAfterAStarMakesAHeading() {
384        let h = Harness("* a\n*x\nbody\nmore\n")
385        h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
386        #expect(indent(h, at: "more") == 2)
387        h.checkInSync()
388    }
389}
390
391@MainActor
392struct RestyleFuzzTests {
393    /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
394    /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
395    @Test func incrementalRestyleEqualsFullRestyle() throws {
396        let environment = ProcessInfo.processInfo.environment
397        var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
398        let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
399        func next(_ bound: Int) -> Int {
400            state = state &* 6364136223846793005 &+ 1442695040888963407
401            return Int((state >> 33) % UInt64(bound))
402        }
403        let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
404        let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
405        for n in 0..<count {
406            let length = (h.string as NSString).length
407            let start = next(length + 1)
408            let end = min(length, start + next(4))
409            let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
410            h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
411            let fresh = Harness(h.string)
412            let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
413            #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
414            if !same { break }
415        }
416        h.checkInSync()
417    }
418}
419
420@MainActor
421struct InitialStylingTests {
422    @Test func stylesTheFirstScreenThenTheRest() throws {
423        let line = "* heading *bold*\nbody text\n"
424        let text = String(repeating: line, count: 4_000)
425        let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
426        let length = (text as NSString).length
427        #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
428        h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
429        h.drainStyling()
430        #expect(h.editor.styledUpTo == length + 1)
431        #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
432    }
433
434    @Test func editsBeforeTheWatermarkShiftIt() {
435        let text = String(repeating: "line of text\n", count: 5_000)
436        let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
437        let before = h.editor.styledUpTo
438        h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
439        #expect(h.editor.styledUpTo == before + 3)
440    }
441}
442
443@MainActor
444struct CommandTests {
445    @Test func performEditsThroughTheTextView() {
446        let h = Harness("* a :t:\nbody\n")
447        var messages: [String] = []
448        h.editor.onMessage = { messages.append($0) }
449        h.caret(at: 2)
450        h.editor.perform(PriorityUp())
451        #expect(h.string.hasPrefix("* [#B] a "))
452        #expect(h.caret == 2)
453        h.checkInSync()
454        // Undo groups by event: let the run loop close the first command's group, as a key
455        // press would.
456        RunLoop.current.run(until: Date())
457        h.editor.perform(TodoCycle())
458        #expect(h.string.hasPrefix("* TODO [#B] a "))
459        RunLoop.current.run(until: Date())
460        h.textView.undoManager?.undo()
461        #expect(h.string.hasPrefix("* [#B] a "))
462        h.checkInSync()
463        h.caret(at: h.offset(of: "body"))
464        h.editor.perform(PromoteHeading())
465        #expect(messages == ["Not on a heading"])
466    }
467
468    @Test func readOnlyEditorsRefuseEdits() {
469        let editor = OrgEditor(document: DocumentState(bytes: Array("* a\n".utf8)), editable: false)
470        editor.textView.setSelectedRange(NSRange(location: 2, length: 0))
471        #expect(editor.perform(TodoCycle()) == .failed("read-only"))
472        #expect(editor.document.text == "* a\n")
473    }
474}