Lay out only the changed ranges on fold and block changes !230

merged merged by cmc on 2026-10-11 03:13 UTC · krz/orgstar:claude/jovial-meitner-d68a71 into main

4 files changed, +249 −37

Layout: unified · split

Sources/OrgEditorAppKit/OrgEditor.swift +83 −18
@@ -38,6 +38,10 @@ final class FoldedHeadings: @unchecked Sendable {
38 func contains(_ offset: Int) -> Bool { 38 func contains(_ offset: Int) -> Bool {
39 lock.withLock { starts.contains(offset) } 39 lock.withLock { starts.contains(offset) }
40 } 40 }
41
42 var all: Set<Int> {
43 lock.withLock { starts }
44 }
41} 45}
42 46
43/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every 47/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
@@ -62,9 +66,11 @@ public final class OrgEditor: NSObject {
62 didSet { 66 didSet {
63 guard themeSpec != oldValue else { return } 67 guard themeSpec != oldValue else { return }
64 theme = Theme(themeSpec) 68 theme = Theme(themeSpec)
65 applyThemeToView() 69 keepingTopLine {
66 restyleEverything() 70 applyThemeToView()
67 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 71 restyleEverything()
72 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
73 }
68 } 74 }
69 } 75 }
70 private var isLoading = false 76 private var isLoading = false
@@ -594,9 +600,8 @@ public final class OrgEditor: NSObject {
594 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) }) 600 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
595 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } 601 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
596 view.wrapperFolds = Set(wrapperHidden.keys) 602 view.wrapperFolds = Set(wrapperHidden.keys)
597 updateHidden() 603 updateHiddenAndLayout()
598 orgTextView?.redrawLineNumbers() 604 orgTextView?.redrawLineNumbers()
599 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
600 textView.needsDisplay = true 605 textView.needsDisplay = true
601 let caret = textView.selectedRange().location 606 let caret = textView.selectedRange().location
602 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) } 607 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
@@ -622,6 +627,65 @@ public final class OrgEditor: NSObject {
622 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden) 627 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
623 } 628 }
624 629
630 /// `updateHidden`, laying out again only the text that changed between hidden and shown
631 /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit
632 /// estimate the height of everything above the window afresh, which moves the text under it.
633 private func updateHiddenAndLayout() {
634 let oldHidden = hidden.all
635 let oldFolded = folded.all
636 updateHidden()
637 invalidateLayout(from: oldHidden, to: hidden.all)
638 invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 })
639 }
640
641 /// Lays out again the ranges in `old` and not in `new`, and the other way round.
642 private func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) {
643 invalidateLayout(lines: Array(Set(old).symmetricDifference(new)))
644 }
645
646 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
647 /// heading or opening line of a fold, whose fragment draws the fold mark.
648 private func invalidateLayout(lines ranges: [Range<Int>]) {
649 guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return }
650 let text = textView.string as NSString
651 for range in ranges {
652 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
653 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
654 guard let start = content.location(content.documentRange.location, offsetBy: lower),
655 let end = content.location(start, offsetBy: upper - lower),
656 let textRange = NSTextRange(location: start, end: end) else { continue }
657 textLayoutManager.invalidateLayout(for: textRange)
658 }
659 }
660
661 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
662 /// top of the window back there. TextKit estimates the height of text it hasn't laid out,
663 /// so the same scroll position lands on different text after a fresh layout.
664 func keepingTopLine(_ change: () -> Void) {
665 guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() }
666 let visible = scroll.documentVisibleRect
667 let top = visible.minY - textView.textContainerOrigin.y
668 let start = content.documentRange.location
669 let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
670 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
671 }
672 change()
673 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
674 let above = NSTextRange(location: start, end: location) else { return }
675 // Styled now, not in the background passes, which would lay the text out again.
676 while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) }
677 textLayoutManager.ensureLayout(for: above)
678 guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return }
679 let frame = fragment.layoutFragmentFrame
680 let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height))
681 textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height))
682 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
683 let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height
684 if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) }
685 textView.scroll(NSPoint(x: visible.minX, y: y))
686 scroll.reflectScrolledClipView(scroll.contentView)
687 }
688
625 // MARK: - Sparse trees 689 // MARK: - Sparse trees
626 690
627 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next 691 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
@@ -640,9 +704,10 @@ public final class OrgEditor: NSObject {
640 setFolds(state) 704 setFolds(state)
641 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree) 705 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
642 self.highlights = highlights 706 self.highlights = highlights
643 updateHidden() 707 keepingTopLine {
644 restyleOutsideEditing(0..<utf16Length) 708 updateHiddenAndLayout()
645 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 709 restyleOutsideEditing(0..<utf16Length)
710 }
646 orgTextView?.redrawLineNumbers() 711 orgTextView?.redrawLineNumbers()
647 textView.needsDisplay = true 712 textView.needsDisplay = true
648 let caret = textView.selectedRange().location 713 let caret = textView.selectedRange().location
@@ -721,8 +786,10 @@ public final class OrgEditor: NSObject {
721 } 786 }
722 787
723 private func refreshImages() { 788 private func refreshImages() {
724 restyleOutsideEditing(0..<utf16Length) 789 keepingTopLine {
725 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 790 restyleOutsideEditing(0..<utf16Length)
791 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
792 }
726 textView.needsDisplay = true 793 textView.needsDisplay = true
727 } 794 }
728 795
@@ -786,8 +853,7 @@ public final class OrgEditor: NSObject {
786 } catch { 853 } catch {
787 return 854 return
788 } 855 }
789 updateHidden() 856 updateHiddenAndLayout()
790 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
791 orgTextView?.redrawLineNumbers() 857 orgTextView?.redrawLineNumbers()
792 textView.needsDisplay = true 858 textView.needsDisplay = true
793 if let narrowed { 859 if let narrowed {
@@ -820,7 +886,7 @@ public final class OrgEditor: NSObject {
820 private func setShrunk(_ columns: [Int], in table: Range<Int>) { 886 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
821 shrunk.set(columns, in: table, text: textView.string) 887 shrunk.set(columns, in: table, text: textView.string)
822 restyleOutsideEditing(table) 888 restyleOutsideEditing(table)
823 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 889 invalidateLayout(lines: [table])
824 textView.needsDisplay = true 890 textView.needsDisplay = true
825 } 891 }
826 892
@@ -1124,8 +1190,9 @@ public final class OrgEditor: NSObject {
1124 guard isOrg else { return } 1190 guard isOrg else { return }
1125 let blocks = Presentation.shadedBlocks(document.tree) 1191 let blocks = Presentation.shadedBlocks(document.tree)
1126 guard blocks != shaded.all else { return } 1192 guard blocks != shaded.all else { return }
1193 let old = shaded.all
1127 shaded.set(blocks) 1194 shaded.set(blocks)
1128 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 1195 invalidateLayout(from: old, to: blocks)
1129 } 1196 }
1130 1197
1131 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to 1198 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
@@ -1193,10 +1260,8 @@ public final class OrgEditor: NSObject {
1193 } 1260 }
1194 scheduleBlockCheck() 1261 scheduleBlockCheck()
1195 } 1262 }
1196 if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) 1263 invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
1197 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) { 1264 invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
1198 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1199 }
1200 onEditTiming?(clock.now - start) 1265 onEditTiming?(clock.now - start)
1201 let lineCount = lines.lineCount 1266 let lineCount = lines.lineCount
1202 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText) 1267 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
Sources/OrgEditorAppKit/ViewToggles.swift +15 −13
@@ -38,20 +38,22 @@ extension OrgEditor {
38 set { 38 set {
39 guard let container = textView.textContainer, newValue != truncatesLines else { return } 39 guard let container = textView.textContainer, newValue != truncatesLines else { return }
40 let scroll = textView.enclosingScrollView 40 let scroll = textView.enclosingScrollView
41 scroll?.hasHorizontalScroller = newValue 41 keepingTopLine {
42 textView.isHorizontallyResizable = newValue 42 scroll?.hasHorizontalScroller = newValue
43 if newValue { 43 textView.isHorizontallyResizable = newValue
44 container.widthTracksTextView = false 44 if newValue {
45 container.size = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) 45 container.widthTracksTextView = false
46 textView.autoresizingMask = [.width, .height] 46 container.size = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
47 } else { 47 textView.autoresizingMask = [.width, .height]
48 let width = scroll?.contentSize.width ?? textView.frame.width 48 } else {
49 textView.setFrameSize(NSSize(width: width, height: textView.frame.height)) 49 let width = scroll?.contentSize.width ?? textView.frame.width
50 container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude) 50 textView.setFrameSize(NSSize(width: width, height: textView.frame.height))
51 container.widthTracksTextView = true 51 container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
52 textView.autoresizingMask = [.width] 52 container.widthTracksTextView = true
53 textView.autoresizingMask = [.width]
54 }
55 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
53 } 56 }
54 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
55 textView.needsDisplay = true 57 textView.needsDisplay = true
56 } 58 }
57 } 59 }
Sources/OrgstarMobile/MobileEditor.swift +54 −6
@@ -581,8 +581,52 @@ final class MobileEditor: NSObject, DocumentBuffer {
581 private func restyleAll() { 581 private func restyleAll() {
582 let interval = Perf.begin("editor.restyleAll") 582 let interval = Perf.begin("editor.restyleAll")
583 defer { interval.end() } 583 defer { interval.end() }
584 restyle(0..<textView.textStorage.length) 584 keepingTopLine {
585 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 585 restyle(0..<textView.textStorage.length)
586 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
587 }
588 }
589
590 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
591 /// heading or opening line of a fold, whose fragment draws the fold mark. Laying out the
592 /// whole file again makes TextKit estimate the height of everything above the view afresh,
593 /// which moves the text under it.
594 private func invalidateLayout(lines ranges: [Range<Int>]) {
595 guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
596 let text = textView.textStorage.string as NSString
597 for range in ranges {
598 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
599 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
600 guard let start = content.location(content.documentRange.location, offsetBy: lower),
601 let end = content.location(start, offsetBy: upper - lower),
602 let textRange = NSTextRange(location: start, end: end) else { continue }
603 manager.invalidateLayout(for: textRange)
604 }
605 }
606
607 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
608 /// top of the view back there. TextKit estimates the height of text it hasn't laid out,
609 /// so the same scroll position lands on different text after a fresh layout.
610 private func keepingTopLine(_ change: () -> Void) {
611 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return change() }
612 let inset = textView.textContainerInset
613 let top = textView.contentOffset.y + textView.adjustedContentInset.top - inset.top
614 let start = content.documentRange.location
615 let anchor = manager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
616 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
617 }
618 change()
619 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
620 let above = NSTextRange(location: start, end: location) else { return }
621 manager.ensureLayout(for: above)
622 guard let fragment = manager.textLayoutFragment(for: location) else { return }
623 let frame = fragment.layoutFragmentFrame
624 manager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * textView.bounds.height))
625 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
626 let needed = manager.usageBoundsForTextContainer.maxY + inset.top + inset.bottom
627 if textView.contentSize.height < needed { textView.contentSize.height = needed }
628 let y = frame.minY + inset.top + max(0, min(anchor.within, frame.height)) - textView.adjustedContentInset.top
629 textView.contentOffset = CGPoint(x: textView.contentOffset.x, y: y)
586 } 630 }
587 631
588 /// Styles are set after the edit has been processed, as TextKit asks. 632 /// Styles are set after the edit has been processed, as TextKit asks.
@@ -713,7 +757,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
713 /// Narrows `columns` of `table` and widens its others. 757 /// Narrows `columns` of `table` and widens its others.
714 private func setShrunk(_ columns: [Int], in table: Range<Int>) { 758 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
715 shrunk.set(columns, in: table, text: textView.textStorage.string) 759 shrunk.set(columns, in: table, text: textView.textStorage.string)
716 restyleAll() 760 restyle(table)
761 invalidateLayout(lines: [table])
717 } 762 }
718 763
719 /// Hides each shrunk segment's text and draws its display where the text was, as pretty 764 /// Hides each shrunk segment's text and draws its display where the text was, as pretty
@@ -809,8 +854,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
809 get { (textView as? KeyedTextView)?.truncates ?? false } 854 get { (textView as? KeyedTextView)?.truncates ?? false }
810 set { 855 set {
811 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return } 856 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
812 view.truncates = newValue 857 keepingTopLine {
813 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 858 view.truncates = newValue
859 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
860 }
814 } 861 }
815 } 862 }
816 863
@@ -825,6 +872,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
825 let tree = document.tree 872 let tree = document.tree
826 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden } 873 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
827 let before = hidden.folded 874 let before = hidden.folded
875 let oldHidden = hidden.all
828 hidden.set( 876 hidden.set(
829 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers), 877 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
830 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds) 878 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
@@ -838,7 +886,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
838 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) } 886 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
839 storage.endEditing() 887 storage.endEditing()
840 } 888 }
841 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 889 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
842 textView.setNeedsDisplay() 890 textView.setNeedsDisplay()
843 } 891 }
844 892
Tests/OrgEditorAppKitTests/ScrollStabilityTests.swift added +97
@@ -0,0 +1,97 @@
1import AppKit
2import OrgCore
3import OrgDocument
4import OrgPresentation
5import Testing
6@testable import OrgEditorAppKit
7
8/// A long file with lines of very different lengths, as real notes have: TextKit's height
9/// estimates for text it hasn't laid out are far off for such a file, so laying the whole
10/// document out again moves what the window shows.
11@MainActor
12struct ScrollStabilityTests {
13 static func longDocument(headings: Int) -> String {
14 var seed: UInt64 = 0x9E37_79B9_7F4A_7C15
15 func next() -> Int {
16 seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
17 return Int(truncatingIfNeeded: seed >> 33)
18 }
19 let words = ["meeting", "todo", "the", "a", "deadline", "note", "project", "review", "call", "later", "important", "x"]
20 var text = "#+STARTUP: indent\n"
21 for n in 0..<headings {
22 text += "\(n % 3 == 0 ? "**" : "*") Heading \(n)\n"
23 for _ in 0..<(1 + next() % 4) {
24 let count: Int
25 switch next() % 5 {
26 case 0: count = 60 + next() % 120
27 case 1: count = 1 + next() % 4
28 default: count = 3 + next() % 12
29 }
30 text += (0..<count).map { _ in words[next() % words.count] }.joined(separator: " ") + "\n"
31 }
32 }
33 return text
34 }
35
36 /// The window on screen, with layout left to the view, as a user's window is.
37 static func shownHarness(_ text: String) -> Harness {
38 NSApplication.shared.setActivationPolicy(.regular)
39 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
40 h.window.makeKeyAndOrderFront(nil)
41 pump(h)
42 h.drainStyling()
43 pump(h)
44 return h
45 }
46
47 static func pump(_ h: Harness) {
48 RunLoop.main.run(until: Date().addingTimeInterval(0.05))
49 h.window.displayIfNeeded()
50 }
51
52 /// The number of the line at the top of the window.
53 static func topLine(_ h: Harness) -> Int {
54 let layout = h.editor.textLayoutManager
55 let content = layout.textContentManager!
56 let y = h.textView.enclosingScrollView!.documentVisibleRect.minY - h.textView.textContainerOrigin.y
57 guard let fragment = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, y))) else { return -1 }
58 let offset = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
59 return (h.string as NSString).substring(to: offset).filter { $0 == "\n" }.count
60 }
61
62 @Test func foldingNearTheEndKeepsTheWindowWhereItWas() {
63 let h = Self.shownHarness(Self.longDocument(headings: 1500))
64 let heading = h.offset(of: "* Heading 1480\n")
65 h.editor.setCaret(heading)
66 h.textView.scrollRangeToVisible(NSRange(location: heading, length: 0))
67 Self.pump(h)
68 let before = Self.topLine(h)
69 #expect(before > 5000)
70
71 var state = h.editor.foldState
72 state.folds.insert(heading)
73 h.editor.setFolds(state)
74 Self.pump(h)
75 let after = Self.topLine(h)
76 #expect(abs(after - before) <= 2, "top line moved from \(before) to \(after)")
77 }
78
79 @Test func aThemeChangeNearTheEndKeepsTheWindowWhereItWas() {
80 let h = Self.shownHarness(Self.longDocument(headings: 1500))
81 let heading = h.offset(of: "* Heading 1480\n")
82 h.editor.setCaret(heading)
83 h.textView.scrollRangeToVisible(NSRange(location: heading, length: 0))
84 Self.pump(h)
85 let before = Self.topLine(h)
86 #expect(before > 5000)
87
88 var spec = ThemeSpec.default
89 spec.light["heading-1"] = RGBA(hex: "#ff0000")
90 h.editor.themeSpec = spec
91 Self.pump(h)
92 h.drainStyling()
93 Self.pump(h)
94 let after = Self.topLine(h)
95 #expect(abs(after - before) <= 2, "top line moved from \(before) to \(after)")
96 }
97}