Sources/OrgEditorAppKit/OrgEditor+Shrink.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgEditorAppKit/OrgEditor+Shrink.swift history · blame · raw

163 lines · 8032 bytes

11 symbols in this file
  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), `zc` and `zO` (anywhere in a subtree), and `zR`,
 84    /// `zM`, `zr` and `zm` for the whole buffer.
 85    func fold(_ id: String) {
 86        leaveSparseTree()
 87        let caret = textView.selectedRange().location
 88        let tree = document.tree
 89        let next: FoldState?
 90        if id == "org.fold.close" || id == "org.fold.open-subtree" {
 91            next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) }
 92                .map { id == "org.fold.close" ? Presentation.hideSubtree($0.start, foldState) : Presentation.showSubtree($0.start, in: tree, foldState) }
 93        } else if id == "org.fold.open-all" {
 94            next = Presentation.showAllHeadings(foldState)
 95        } else if id == "org.fold.close-all" {
 96            next = Presentation.hideSublevels(1, in: tree, foldState)
 97        } else if id == "org.fold.more" || id == "org.fold.less" {
 98            let level = Presentation.foldLevel(in: tree, foldState)
 99            next = Presentation.hideSublevels(id == "org.fold.more" ? level + 1 : max(1, level - 1), in: tree, foldState)
100        } else {
101            next = Presentation.heading(containing: caret, in: tree).map {
102                id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState)
103            }
104        }
105        if let next, next != foldState { setFolds(next) }
106    }
107
108    /// Shift-TAB: overview, contents, show all.
109    public func cycleGlobal() {
110        leaveSparseTree()
111        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
112        globalVisibility = visibility
113        setFolds(state)
114    }
115
116    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
117    public func reveal(_ offset: Int) {
118        let target = max(0, min(offset, utf16Length))
119        if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
120        unfold(around: target)
121        setCaret(target)
122        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
123    }
124
125    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
126    func unfold(around offset: Int) {
127        leaveSparseTree()
128        var state = foldState
129        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
130            state.folds.remove(entry.start)
131            state.bodyFolds.remove(entry.start)
132        }
133        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
134            state.wrapperFolds.remove(start)
135        }
136        guard state != foldState else { return }
137        setFolds(state)
138    }
139
140    /// Applies edits through the text view as one undo step, not merged with typing around it.
141    func applyEdits(_ edits: [TextEdit]) {
142        guard !edits.isEmpty, let storage = textView.textStorage else { return }
143        textView.breakUndoCoalescing()
144        textView.undoManager?.beginUndoGrouping()
145        // By lines, so a fold between two changes stays.
146        let text = storage.string
147        for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
148            let range = NSRange(edit.range)
149            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
150            storage.replaceCharacters(in: range, with: edit.replacement)
151            textView.didChangeText()
152        }
153        textView.undoManager?.endUndoGrouping()
154        textView.breakUndoCoalescing()
155    }
156
157    func setCaret(_ offset: Int) {
158        let clamped = max(0, min(offset, utf16Length))
159        previousSelection = clamped
160        textView.setSelectedRange(NSRange(location: clamped, length: 0))
161    }
162}
163#endif