Sources/OrgEditorAppKit/OrgEditor+Folding.swift

e401b435a8497ae4bfbbfb0d4fcf1341479c93c6
orgstar/Sources/OrgEditorAppKit/OrgEditor+Folding.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form