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