Commit 7e166e6ee4

7e166e6ee404742e15cc842a82ce103091f15756

parent: 55a97d948e

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-19 19:54 UTC

Editor: ignore selection changes while reloading text

Archiving a subtree replaces the editor's text through update(), which
loads the new text before mapping the folds. Replacing the storage moves
the caret to the new end; when that falls inside a stale fold range,
selectionChanged() jumps to the fold's old end, which clamps back to the
same offset, and recurses until the stack overflows. update() sets the
caret after setting the folds, so selection changes during load are
skipped.

Layout: unified · split

Sources/OrgEditorAppKit/OrgEditor.swift +3
@@ -865,6 +865,9 @@ public final class OrgEditor: NSObject {
865 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving 865 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
866 /// back jumps to the end of the heading line. 866 /// back jumps to the end of the heading line.
867 func selectionChanged() { 867 func selectionChanged() {
868 // Replacing the text moves the caret while the folds are still the old text's; the
869 // loader sets the caret afterwards.
870 guard !isLoading else { return }
868 let selection = textView.selectedRange() 871 let selection = textView.selectedRange()
869 defer { previousSelection = selection.location } 872 defer { previousSelection = selection.location }
870 redrawShadedSelection(selection) 873 redrawShadedSelection(selection)
Tests/OrgEditorAppKitTests/EditorTests.swift +13
@@ -347,6 +347,19 @@ struct BufferTests {
347 h.checkInSync() 347 h.checkInSync()
348 } 348 }
349 349
350 /// Shorter text, as archiving a subtree leaves it: reloading puts the caret at the new
351 /// end, inside the old range of the fold after the removed subtree.
352 @Test func updateRemovingTextBeforeAFold() {
353 let h = Harness("* a\n* b\n* c\nlong body\n")
354 h.editor.setFolds(FoldState(folds: [h.offset(of: "* c")]))
355 h.caret(at: h.offset(of: "* b"))
356 h.editor.update { $0 = DocumentState(bytes: Array("* a\n* c\nlong body\n".utf8)) }
357 #expect(h.string == "* a\n* c\nlong body\n")
358 #expect(h.caret == h.offset(of: "* c"))
359 #expect(h.editor.foldState.folds == [h.offset(of: "* c")])
360 h.checkInSync()
361 }
362
350 /// Each buffer's editor reports its own changes: a background buffer's edit saves its 363 /// Each buffer's editor reports its own changes: a background buffer's edit saves its
351 /// file, not the shown one's. 364 /// file, not the shown one's.
352 @Test func backgroundEditorsSaveTheirOwnFiles() async throws { 365 @Test func backgroundEditorsSaveTheirOwnFiles() async throws {