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