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 {
3838 func contains(_ offset: Int) -> Bool {
3939 lock.withLock { starts.contains(offset) }
4040 }
41
42 var all: Set<Int> {
43 lock.withLock { starts }
44 }
4145}
4246
4347/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
@@ -62,9 +66,11 @@ public final class OrgEditor: NSObject {
6266 didSet {
6367 guard themeSpec != oldValue else { return }
6468 theme = Theme(themeSpec)
65 applyThemeToView()
66 restyleEverything()
67 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
69 keepingTopLine {
70 applyThemeToView()
71 restyleEverything()
72 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
73 }
6874 }
6975 }
7076 private var isLoading = false
@@ -594,9 +600,8 @@ public final class OrgEditor: NSObject {
594600 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
595601 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
596602 view.wrapperFolds = Set(wrapperHidden.keys)
597 updateHidden()
603 updateHiddenAndLayout()
598604 orgTextView?.redrawLineNumbers()
599 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
600605 textView.needsDisplay = true
601606 let caret = textView.selectedRange().location
602607 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
@@ -622,6 +627,65 @@ public final class OrgEditor: NSObject {
622627 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
623628 }
624629
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
625689 // MARK: - Sparse trees
626690
627691 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
@@ -640,9 +704,10 @@ public final class OrgEditor: NSObject {
640704 setFolds(state)
641705 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
642706 self.highlights = highlights
643 updateHidden()
644 restyleOutsideEditing(0..<utf16Length)
645 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
707 keepingTopLine {
708 updateHiddenAndLayout()
709 restyleOutsideEditing(0..<utf16Length)
710 }
646711 orgTextView?.redrawLineNumbers()
647712 textView.needsDisplay = true
648713 let caret = textView.selectedRange().location
@@ -721,8 +786,10 @@ public final class OrgEditor: NSObject {
721786 }
722787
723788 private func refreshImages() {
724 restyleOutsideEditing(0..<utf16Length)
725 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
789 keepingTopLine {
790 restyleOutsideEditing(0..<utf16Length)
791 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
792 }
726793 textView.needsDisplay = true
727794 }
728795
@@ -786,8 +853,7 @@ public final class OrgEditor: NSObject {
786853 } catch {
787854 return
788855 }
789 updateHidden()
790 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
856 updateHiddenAndLayout()
791857 orgTextView?.redrawLineNumbers()
792858 textView.needsDisplay = true
793859 if let narrowed {
@@ -820,7 +886,7 @@ public final class OrgEditor: NSObject {
820886 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
821887 shrunk.set(columns, in: table, text: textView.string)
822888 restyleOutsideEditing(table)
823 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
889 invalidateLayout(lines: [table])
824890 textView.needsDisplay = true
825891 }
826892
@@ -1124,8 +1190,9 @@ public final class OrgEditor: NSObject {
11241190 guard isOrg else { return }
11251191 let blocks = Presentation.shadedBlocks(document.tree)
11261192 guard blocks != shaded.all else { return }
1193 let old = shaded.all
11271194 shaded.set(blocks)
1128 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1195 invalidateLayout(from: old, to: blocks)
11291196 }
11301197
11311198 /// 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 {
11931260 }
11941261 scheduleBlockCheck()
11951262 }
1196 if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
1197 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
1198 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1199 }
1263 invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
1264 invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
12001265 onEditTiming?(clock.now - start)
12011266 let lineCount = lines.lineCount
12021267 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
Sources/OrgEditorAppKit/ViewToggles.swift +15 −13
@@ -38,20 +38,22 @@ extension OrgEditor {
3838 set {
3939 guard let container = textView.textContainer, newValue != truncatesLines else { return }
4040 let scroll = textView.enclosingScrollView
41 scroll?.hasHorizontalScroller = newValue
42 textView.isHorizontallyResizable = newValue
43 if newValue {
44 container.widthTracksTextView = false
45 container.size = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
46 textView.autoresizingMask = [.width, .height]
47 } else {
48 let width = scroll?.contentSize.width ?? textView.frame.width
49 textView.setFrameSize(NSSize(width: width, height: textView.frame.height))
50 container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
51 container.widthTracksTextView = true
52 textView.autoresizingMask = [.width]
41 keepingTopLine {
42 scroll?.hasHorizontalScroller = newValue
43 textView.isHorizontallyResizable = newValue
44 if newValue {
45 container.widthTracksTextView = false
46 container.size = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
47 textView.autoresizingMask = [.width, .height]
48 } else {
49 let width = scroll?.contentSize.width ?? textView.frame.width
50 textView.setFrameSize(NSSize(width: width, height: textView.frame.height))
51 container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
52 container.widthTracksTextView = true
53 textView.autoresizingMask = [.width]
54 }
55 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
5356 }
54 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
5557 textView.needsDisplay = true
5658 }
5759 }
Sources/OrgstarMobile/MobileEditor.swift +54 −6
@@ -581,8 +581,52 @@ final class MobileEditor: NSObject, DocumentBuffer {
581581 private func restyleAll() {
582582 let interval = Perf.begin("editor.restyleAll")
583583 defer { interval.end() }
584 restyle(0..<textView.textStorage.length)
585 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
584 keepingTopLine {
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)
586630 }
587631
588632 /// Styles are set after the edit has been processed, as TextKit asks.
@@ -713,7 +757,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
713757 /// Narrows `columns` of `table` and widens its others.
714758 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
715759 shrunk.set(columns, in: table, text: textView.textStorage.string)
716 restyleAll()
760 restyle(table)
761 invalidateLayout(lines: [table])
717762 }
718763
719764 /// 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 {
809854 get { (textView as? KeyedTextView)?.truncates ?? false }
810855 set {
811856 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
812 view.truncates = newValue
813 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
857 keepingTopLine {
858 view.truncates = newValue
859 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
860 }
814861 }
815862 }
816863
@@ -825,6 +872,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
825872 let tree = document.tree
826873 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
827874 let before = hidden.folded
875 let oldHidden = hidden.all
828876 hidden.set(
829877 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
830878 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
@@ -838,7 +886,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
838886 for start in changed { storage.edited(.editedAttributes, range: text.lineRange(for: NSRange(location: start, length: 0)), changeInLength: 0) }
839887 storage.endEditing()
840888 }
841 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
889 invalidateLayout(lines: Array(Set(oldHidden).symmetricDifference(hidden.all)))
842890 textView.setNeedsDisplay()
843891 }
844892
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}