Tests/OrgEditorAppKitTests/EditorTests.swift

518 lines · 23089 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 textWidth() throws {
248        let h = Harness("Prose that is long enough to wrap in a narrow text area, past sixty columns of text.\n")
249        let full = try #require(h.textView.textContainer).size.width
250        var spec = ThemeSpec.default
251        spec.textWidth = 40
252        h.editor.themeSpec = spec
253        h.layout()
254        let narrow = try #require(h.textView.textContainer).size.width
255        #expect(narrow < full)
256        #expect(abs(narrow - 40 * h.editor.theme.column - 2 * h.textView.textContainer!.lineFragmentPadding) < 1)
257        // Centred: the same margin either side.
258        #expect(abs(h.textView.textContainerInset.width * 2 + narrow - h.textView.bounds.width) < 1)
259        spec.textWidth = 0
260        h.editor.themeSpec = spec
261        h.layout()
262        #expect(try #require(h.textView.textContainer).size.width == full)
263    }
264
265    @Test func mixedPitch() throws {
266        let text = "**** Heading :tag:\nProse text.\n- item\n| a | b |\n#+begin_src sh\necho\n#+end_src\n"
267        let h = Harness(text)
268        var spec = ThemeSpec.default
269        spec.bodyFont = "system"
270        h.editor.themeSpec = spec
271        h.drainStyling()
272        let storage = try #require(h.textView.textStorage)
273        let ns = text as NSString
274        func fixed(_ needle: String, offset: Int = 0) -> Bool {
275            let font = storage.attribute(.font, at: ns.range(of: needle).location + offset, effectiveRange: nil) as? NSFont
276            return font?.isFixedPitch == true
277        }
278        #expect(!fixed("Prose"))
279        #expect(!fixed("Heading"))
280        #expect(fixed("****"))
281        #expect(fixed(":tag:"))
282        #expect(fixed("- item") && !fixed("item"))
283        #expect(fixed("| a"))
284        #expect(fixed("echo"))
285        // Body indentation is still counted in columns of the fixed-pitch font.
286        let style = try #require(storage.attribute(.paragraphStyle, at: ns.range(of: "Prose").location, effectiveRange: nil) as? NSParagraphStyle)
287        #expect(style.firstLineHeadIndent == 5 * h.editor.theme.column)
288        #expect(h.editor.theme.font.isFixedPitch)
289    }
290
291    @Test func styling() throws {
292        let h = Harness("** b\nbody\n")
293        let storage = try #require(h.textView.textStorage)
294        #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
295        let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
296        #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
297        h.caret(at: 0)
298        h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
299        let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
300        #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
301    }
302
303    @Test func accessibilityReadsTheWholeText() {
304        let h = Harness(outline)
305        h.caret(at: 1)
306        h.editor.cycleAtCaret()
307        #expect(h.textView.accessibilityValue() as? String == outline)
308        h.textView.setSelectedRange(NSRange(location: 0, length: 3))
309        #expect(h.textView.accessibilitySelectedText() == "* a")
310        #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
311    }
312
313    @Test func saveWritesAndClearsDirty() throws {
314        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
315        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
316        defer { try? FileManager.default.removeItem(at: folder) }
317        let file = folder.appendingPathComponent("a.org")
318        try Data(outline.utf8).write(to: file)
319        let h = Harness(outline)
320        h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
321        let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
322        #expect(try h.editor.save(using: saver, to: file) == .saved)
323        #expect(!h.editor.document.isDirty)
324        #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
325    }
326}
327
328@MainActor
329struct BufferTests {
330    @Test func updateMapsCaretAndFoldsAndClearsUndo() {
331        let h = Harness(outline)
332        var changes = 0
333        h.editor.onChange = { changes += 1 }
334        h.caret(at: 1)
335        h.textView.insertText("x", replacementRange: NSRange(location: 4, length: 0))
336        #expect(changes == 1)
337        RunLoop.current.run(until: Date())
338        #expect(h.textView.undoManager?.canUndo == true)
339        h.editor.setFolds(FoldState(folds: [h.offset(of: "** b")]))
340        h.caret(at: h.offset(of: "* c") + 2)
341        h.editor.update { $0 = DocumentState(bytes: Array(("new\n" + outline).utf8)) }
342        #expect(changes == 2)
343        #expect(h.string == "new\n" + outline)
344        #expect(h.caret == h.offset(of: "* c") + 2)
345        #expect(h.editor.foldState.folds == [h.offset(of: "** b")])
346        #expect(h.textView.undoManager?.canUndo != true)
347        h.checkInSync()
348    }
349
350    /// Each buffer's editor reports its own changes: a background buffer's edit saves its
351    /// file, not the shown one's.
352    @Test func backgroundEditorsSaveTheirOwnFiles() async throws {
353        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
354        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
355        defer { try? FileManager.default.removeItem(at: folder) }
356        let a = folder.appendingPathComponent("a.org"), b = folder.appendingPathComponent("b.org")
357        try Data("* A\n".utf8).write(to: a)
358        try Data("* B\n".utf8).write(to: b)
359        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
360        session.autosaveDelay = .milliseconds(10)
361        var harnesses: [String: Harness] = [:]
362        for file in [a, b] {
363            session.open(file.path)
364            let h = Harness(try #require(session.document))
365            let path = file.path
366            h.editor.onChange = { [weak session] in session?.bufferChanged(path) }
367            session.attach(h.editor)
368            harnesses[path] = h
369        }
370        #expect(session.path == b.path)
371        harnesses[a.path]!.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
372        #expect(session.dirtyPaths == [a.path])
373        #expect(!session.isDirty)
374        for _ in 0..<50 where (try? String(contentsOf: a, encoding: .utf8)) != "x* A\n" {
375            try await Task.sleep(for: .milliseconds(20))
376        }
377        #expect(try String(contentsOf: a, encoding: .utf8) == "x* A\n")
378    }
379
380    /// The wiring the app uses: the editor is the session's buffer and reports typing.
381    @Test func sessionSavesWhatIsTyped() async throws {
382        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
383        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
384        defer { try? FileManager.default.removeItem(at: folder) }
385        let file = folder.appendingPathComponent("a.org")
386        try Data(outline.utf8).write(to: file)
387        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
388        session.autosaveDelay = .milliseconds(10)
389        session.open(file.path)
390        let h = Harness(try #require(session.document))
391        h.editor.onChange = { [weak session] in session?.bufferChanged() }
392        session.attach(h.editor)
393        h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
394        #expect(session.isDirty)
395        await session.autosave?.value
396        #expect(!session.isDirty)
397        #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
398
399        try Data(("x" + outline + "end\n").utf8).write(to: file)
400        session.fileChanged(file.path)
401        #expect(h.string == "x" + outline + "end\n")
402    }
403}
404
405@MainActor
406struct RestyleTests {
407    func indent(_ h: Harness, at line: String) -> CGFloat? {
408        let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
409        return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
410    }
411
412    @Test func newHeadingReindentsTheLinesItTakesOver() {
413        let h = Harness("* a\none\ntwo\nthree\n")
414        h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
415        #expect(indent(h, at: "one") == 2)
416        #expect(indent(h, at: "three") == 3)
417        h.checkInSync()
418    }
419
420    @Test func joiningAwayAHeadingReindentsItsBody() {
421        let h = Harness("* a\none\n** b\ntwo\nthree\n")
422        h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
423        #expect(indent(h, at: "three") == 2)
424        h.checkInSync()
425    }
426
427    @Test func typingASpaceAfterAStarMakesAHeading() {
428        let h = Harness("* a\n*x\nbody\nmore\n")
429        h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
430        #expect(indent(h, at: "more") == 2)
431        h.checkInSync()
432    }
433}
434
435@MainActor
436struct RestyleFuzzTests {
437    /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
438    /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
439    @Test func incrementalRestyleEqualsFullRestyle() throws {
440        let environment = ProcessInfo.processInfo.environment
441        var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
442        let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
443        func next(_ bound: Int) -> Int {
444            state = state &* 6364136223846793005 &+ 1442695040888963407
445            return Int((state >> 33) % UInt64(bound))
446        }
447        let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
448        let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
449        for n in 0..<count {
450            let length = (h.string as NSString).length
451            let start = next(length + 1)
452            let end = min(length, start + next(4))
453            let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
454            h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
455            let fresh = Harness(h.string)
456            let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
457            #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
458            if !same { break }
459        }
460        h.checkInSync()
461    }
462}
463
464@MainActor
465struct InitialStylingTests {
466    @Test func stylesTheFirstScreenThenTheRest() throws {
467        let line = "* heading *bold*\nbody text\n"
468        let text = String(repeating: line, count: 4_000)
469        let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
470        let length = (text as NSString).length
471        #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
472        h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
473        h.drainStyling()
474        #expect(h.editor.styledUpTo == length + 1)
475        #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
476    }
477
478    @Test func editsBeforeTheWatermarkShiftIt() {
479        let text = String(repeating: "line of text\n", count: 5_000)
480        let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
481        let before = h.editor.styledUpTo
482        h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
483        #expect(h.editor.styledUpTo == before + 3)
484    }
485}
486
487@MainActor
488struct CommandTests {
489    @Test func performEditsThroughTheTextView() {
490        let h = Harness("* a :t:\nbody\n")
491        var messages: [String] = []
492        h.editor.onMessage = { messages.append($0) }
493        h.caret(at: 2)
494        h.editor.perform(PriorityUp())
495        #expect(h.string.hasPrefix("* [#B] a "))
496        #expect(h.caret == 2)
497        h.checkInSync()
498        // Undo groups by event: let the run loop close the first command's group, as a key
499        // press would.
500        RunLoop.current.run(until: Date())
501        h.editor.perform(TodoCycle())
502        #expect(h.string.hasPrefix("* TODO [#B] a "))
503        RunLoop.current.run(until: Date())
504        h.textView.undoManager?.undo()
505        #expect(h.string.hasPrefix("* [#B] a "))
506        h.checkInSync()
507        h.caret(at: h.offset(of: "body"))
508        h.editor.perform(PromoteHeading())
509        #expect(messages == ["Not on a heading"])
510    }
511
512    @Test func readOnlyEditorsRefuseEdits() {
513        let editor = OrgEditor(document: DocumentState(bytes: Array("* a\n".utf8)), editable: false)
514        editor.textView.setSelectedRange(NSRange(location: 2, length: 0))
515        #expect(editor.perform(TodoCycle()) == .failed("read-only"))
516        #expect(editor.document.text == "* a\n")
517    }
518}