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