Sources/OrgEditorAppKit/OrgEditor+Shrink.swift

155 lines · 7371 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4import OrgDocument
  5import OrgPresentation
  6
  7extension OrgEditor {
  8    // MARK: - Shrunk table columns
  9
 10
 11    /// Narrows `columns` of `table` and widens its others.
 12    private func setShrunk(_ columns: [Int], in table: Range<Int>) {
 13        shrunk.set(columns, in: table, text: textView.string)
 14        restyleOutsideEditing(table)
 15        invalidateLayout(lines: [table])
 16        redrawViews()
 17    }
 18
 19    /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
 20    /// `expand` for `org-table-expand`.
 21    func tableColumnWidth(_ id: String) {
 22        switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) {
 23        case .notInTable: onMessage?("Not in a table")
 24        case .set(let columns, let table): setShrunk(columns, in: table)
 25        case .ask(let table, let current, let max):
 26            onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
 27                guard let self, let answer else { return }
 28                self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
 29            }
 30        }
 31    }
 32
 33    /// Hides each shrunk segment's text and draws its display where the text was.
 34    func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
 35        guard !shrunk.isEmpty else { return }
 36        let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
 37        for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
 38            let r = segment.range
 39            let shown = segment.display.count
 40            let kept = min(shown, r.count)
 41            if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
 42            guard kept > 0 else { continue }
 43            let visible = NSRange(location: r.upperBound - kept, length: kept)
 44            storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
 45            storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
 46            if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
 47        }
 48    }
 49
 50    /// Moves drawer and block folds through `edit`, checking again only those near it.
 51    func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
 52        guard !wrapperHidden.isEmpty else { return }
 53        var mapped: [Int: Range<Int>] = [:]
 54        let entries = Array(wrapperHidden)
 55        // One pass maps every start and range.
 56        let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
 57        for i in entries.indices {
 58            let newStart = moved[2 * i].lowerBound
 59            let newRange = moved[2 * i + 1]
 60            if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
 61                if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
 62            } else {
 63                mapped[newStart] = newRange
 64            }
 65        }
 66        wrapperHidden = mapped
 67        view.wrapperFolds = Set(mapped.keys)
 68    }
 69
 70    /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
 71    /// cycles folded, children, subtree. Returns false elsewhere.
 72    @discardableResult
 73    public func cycleAtCaret() -> Bool {
 74        leaveSparseTree()
 75        let caret = textView.selectedRange().location
 76        guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
 77        setFolds(state)
 78        // Off a closing line that folding hid, to the opening line, as org does.
 79        if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
 80        return true
 81    }
 82
 83    /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree).
 84    func fold(_ id: String) {
 85        leaveSparseTree()
 86        let caret = textView.selectedRange().location
 87        let tree = document.tree
 88        let next: FoldState?
 89        if id == "org.fold.close" {
 90            next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) }
 91                .map { Presentation.hideSubtree($0.start, foldState) }
 92        } else {
 93            next = Presentation.heading(containing: caret, in: tree).map {
 94                id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState)
 95            }
 96        }
 97        if let next, next != foldState { setFolds(next) }
 98    }
 99
100    /// Shift-TAB: overview, contents, show all.
101    public func cycleGlobal() {
102        leaveSparseTree()
103        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
104        globalVisibility = visibility
105        setFolds(state)
106    }
107
108    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
109    public func reveal(_ offset: Int) {
110        let target = max(0, min(offset, utf16Length))
111        if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
112        unfold(around: target)
113        setCaret(target)
114        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
115    }
116
117    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
118    func unfold(around offset: Int) {
119        leaveSparseTree()
120        var state = foldState
121        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
122            state.folds.remove(entry.start)
123            state.bodyFolds.remove(entry.start)
124        }
125        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
126            state.wrapperFolds.remove(start)
127        }
128        guard state != foldState else { return }
129        setFolds(state)
130    }
131
132    /// Applies edits through the text view as one undo step, not merged with typing around it.
133    func applyEdits(_ edits: [TextEdit]) {
134        guard !edits.isEmpty, let storage = textView.textStorage else { return }
135        textView.breakUndoCoalescing()
136        textView.undoManager?.beginUndoGrouping()
137        // By lines, so a fold between two changes stays.
138        let text = storage.string
139        for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
140            let range = NSRange(edit.range)
141            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
142            storage.replaceCharacters(in: range, with: edit.replacement)
143            textView.didChangeText()
144        }
145        textView.undoManager?.endUndoGrouping()
146        textView.breakUndoCoalescing()
147    }
148
149    func setCaret(_ offset: Int) {
150        let clamped = max(0, min(offset, utf16Length))
151        previousSelection = clamped
152        textView.setSelectedRange(NSRange(location: clamped, length: 0))
153    }
154}
155#endif