Sources/OrgEditorAppKit/OrgEditor+Folding.swift
225 lines · 10934 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgPresentation
5
6extension OrgEditor {
7 // MARK: - Folding
8
9 public var foldState: FoldState {
10 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
11 }
12
13
14 public func setFolds(_ state: FoldState) {
15 setFolds(state, wrappers: nil)
16 }
17
18 /// `wrappers`, when given, holds every folded drawer and block.
19 func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
20 sparseHidden = nil
21 view.folds = state.folds
22 view.bodyFolds = state.bodyFolds
23 view = view.pruned(to: document.tree, wrappers: false)
24 // Found one by one, or all at once when there are many.
25 let found = wrappers ?? (state.wrapperFolds.count > 32
26 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
27 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
28 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
29 view.wrapperFolds = Set(wrapperHidden.keys)
30 updateHiddenAndLayout()
31 redrawViews()
32 caretsOutOfHiddenText()
33 }
34
35 /// Every view's caret moved to just before the hidden text it sits in, if any.
36 func caretsOutOfHiddenText() {
37 for view in textViews {
38 let caret = view.selectedRange().location
39 guard let range = hidden.containing(caret) else { continue }
40 if view === active { setCaret(max(0, range.lowerBound - 1)) } else { view.setSelectedRange(NSRange(location: max(0, range.lowerBound - 1), length: 0)) }
41 }
42 }
43
44
45 func updateHidden() {
46 if let sparseHidden {
47 let ns = textView.string as NSString
48 // Headings whose next line is hidden show the fold ellipsis.
49 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
50 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
51 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
52 }
53 folded.set(Set(headings).union(view.wrapperFolds))
54 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
55 return
56 }
57 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
58 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
59 }
60
61 /// `updateHidden`, laying out again only the text that changed between hidden and shown
62 /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit
63 /// estimate the height of everything above the window afresh, which moves the text under it.
64 private func updateHiddenAndLayout() {
65 let oldHidden = hidden.all
66 let oldFolded = folded.all
67 updateHidden()
68 invalidateLayout(from: oldHidden, to: hidden.all)
69 invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 })
70 }
71
72 /// Lays out again the ranges in `old` and not in `new`, and the other way round.
73 func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) {
74 invalidateLayout(lines: Array(Set(old).symmetricDifference(new)))
75 }
76
77 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
78 /// heading or opening line of a fold, whose fragment draws the fold mark.
79 func invalidateLayout(lines ranges: [Range<Int>]) {
80 guard !ranges.isEmpty else { return }
81 let content = textContentStorage
82 let text = textView.string as NSString
83 for range in ranges {
84 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
85 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
86 guard let start = content.location(content.documentRange.location, offsetBy: lower),
87 let end = content.location(start, offsetBy: upper - lower),
88 let textRange = NSTextRange(location: start, end: end) else { continue }
89 for layout in layoutManagers { layout.invalidateLayout(for: textRange) }
90 }
91 }
92
93 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
94 /// top of the window back there. TextKit estimates the height of text it hasn't laid out,
95 /// so the same scroll position lands on different text after a fresh layout.
96 func keepingTopLine(_ change: () -> Void) {
97 guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() }
98 let visible = scroll.documentVisibleRect
99 let top = visible.minY - textView.textContainerOrigin.y
100 let start = content.documentRange.location
101 let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
102 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
103 }
104 change()
105 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
106 let above = NSTextRange(location: start, end: location) else { return }
107 // Styled now, not in the background passes, which would lay the text out again.
108 while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) }
109 textLayoutManager.ensureLayout(for: above)
110 guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return }
111 let frame = fragment.layoutFragmentFrame
112 let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height))
113 textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height))
114 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
115 let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height
116 if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) }
117 textView.scroll(NSPoint(x: visible.minX, y: y))
118 scroll.reflectScrolledClipView(scroll.contentView)
119 }
120
121 // MARK: - Sparse trees
122
123
124 func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
125 let text = textView.string
126 var state = foldState
127 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
128 state.wrapperFolds.remove(start)
129 }
130 sparseHidden = nil
131 setFolds(state)
132 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
133 self.highlights = highlights
134 keepingTopLine {
135 updateHiddenAndLayout()
136 restyleOutsideEditing(0..<utf16Length)
137 }
138 redrawViews()
139 caretsOutOfHiddenText()
140 }
141
142 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
143 /// open, the others folded.
144 func leaveSparseTree() {
145 guard let sparse = sparseHidden else { return }
146 sparseHidden = nil
147 let outline = Presentation.outline(document.tree)
148 let ns = textView.string as NSString
149 var open: Set<Int> = []
150 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
151 var parent = entry.parent
152 while let p = parent {
153 open.insert(outline[p].start)
154 parent = outline[p].parent
155 }
156 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
157 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
158 }
159 var state = foldState
160 state.folds = Set(outline.map(\.start)).subtracting(open)
161 state.bodyFolds = []
162 setFolds(state)
163 }
164
165 func clearHighlights() {
166 guard !highlights.isEmpty else { return }
167 let old = highlights
168 highlights = []
169 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
170 }
171
172 func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
173 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
174 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
175 }
176 }
177
178 // MARK: - Narrowing
179
180
181 func narrow(_ id: String) {
182 let caret = textView.selectedRange().location
183 do {
184 switch id {
185 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
186 // `org-toggle-narrow-to-subtree`.
187 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
188 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
189 default: narrowed = nil
190 }
191 } catch let failure as Narrowing.Failure {
192 onMessage?(failure.message)
193 return
194 } catch {
195 return
196 }
197 updateHiddenAndLayout()
198 redrawViews()
199 if let narrowed {
200 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
201 for view in textViews where view !== active {
202 let other = view.selectedRange().location
203 if !(narrowed.lowerBound...narrowed.upperBound).contains(other) {
204 view.setSelectedRange(NSRange(location: max(narrowed.lowerBound, min(other, narrowed.upperBound)), length: 0))
205 }
206 }
207 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
208 } else {
209 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
210 }
211 }
212
213 /// What narrowing hides: the text before the region, and the lines after it.
214 private var narrowHidden: [Range<Int>] {
215 guard let narrowed else { return [] }
216 let length = utf16Length
217 var ranges: [Range<Int>] = []
218 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
219 let ns = textView.string as NSString
220 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
221 if tail < length { ranges.append(tail..<length) }
222 return ranges
223 }
224}
225#endif