Sources/OrgEditorAppKit/OrgEditor.swift

53903567a65c44ccdf4ba4ff6ffa6d04721efea1
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

347 lines · 15821 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4import OrgDocument
  5import OrgPresentation
  6
  7/// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread.
  8final class HiddenRanges: @unchecked Sendable {
  9    private let lock = NSLock()
 10    private var ranges: [Range<Int>] = []
 11
 12    func set(_ new: [Range<Int>]) {
 13        lock.withLock { ranges = new }
 14    }
 15
 16    var all: [Range<Int>] {
 17        lock.withLock { ranges }
 18    }
 19
 20    func covers(_ start: Int, _ end: Int) -> Bool {
 21        lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } }
 22    }
 23
 24    func containing(_ offset: Int) -> Range<Int>? {
 25        lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } }
 26    }
 27}
 28
 29/// Folded heading starts, read by the layout-fragment callback.
 30final class FoldedHeadings: @unchecked Sendable {
 31    private let lock = NSLock()
 32    private var starts: Set<Int> = []
 33
 34    func set(_ new: Set<Int>) {
 35        lock.withLock { starts = new }
 36    }
 37
 38    func contains(_ offset: Int) -> Bool {
 39        lock.withLock { starts.contains(offset) }
 40    }
 41}
 42
 43/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
 44/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
 45@MainActor
 46public final class OrgEditor: NSObject {
 47    public let textView: NSTextView
 48    public private(set) var document: DocumentState
 49    public private(set) var view = ViewState()
 50    /// Called with the time from a character edit to restyled text.
 51    public var onEditTiming: ((Duration) -> Void)?
 52
 53    let hidden = HiddenRanges()
 54    let folded = FoldedHeadings()
 55    let theme = Theme()
 56    private var isLoading = false
 57    private var previousSelection = 0
 58
 59    public init(document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800)) {
 60        self.document = document
 61        textView = NSTextView(usingTextLayoutManager: true)
 62        super.init()
 63        textView.frame = frame
 64        textView.isRichText = false
 65        textView.allowsUndo = true
 66        textView.isAutomaticQuoteSubstitutionEnabled = false
 67        textView.isAutomaticDashSubstitutionEnabled = false
 68        textView.isAutomaticTextReplacementEnabled = false
 69        textView.isAutomaticSpellingCorrectionEnabled = false
 70        textView.font = theme.font
 71        textView.typingAttributes = theme.base
 72        textView.isVerticallyResizable = true
 73        textView.autoresizingMask = [.width]
 74        textView.textContainer?.widthTracksTextView = true
 75        textView.delegate = self
 76        textView.textStorage?.delegate = self
 77        textLayoutManager.delegate = self
 78        textContentStorage.delegate = self
 79
 80        isLoading = true
 81        textView.string = document.text
 82        isLoading = false
 83        restyleOutsideEditing(0..<utf16Length)
 84    }
 85
 86    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
 87    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
 88    var utf16Length: Int { (textView.string as NSString).length }
 89
 90    /// A scroll view holding the text view, ready for a window.
 91    public func makeScrollView() -> NSScrollView {
 92        let scroll = NSScrollView(frame: textView.frame)
 93        scroll.hasVerticalScroller = true
 94        scroll.documentView = textView
 95        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
 96        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
 97        return scroll
 98    }
 99
100    // MARK: - Saving
101
102    /// Saves through `saver`. When a merge changes the buffer, the text view is reloaded and
103    /// folds are mapped through the change.
104    @discardableResult
105    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
106        let before = document.text
107        let outcome = try saver.save(&document, to: url)
108        if document.text != before {
109            let edits = lineEdits(from: before, to: document.text)
110            isLoading = true
111            textView.string = document.text
112            isLoading = false
113            restyleOutsideEditing(0..<utf16Length)
114            setFolds(view.mapped(through: edits).folds)
115        }
116        return outcome
117    }
118
119    // MARK: - Folding
120
121    public func setFolds(_ folds: Set<Int>) {
122        view.folds = folds
123        view = view.pruned(to: document.tree)
124        folded.set(view.folds)
125        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
126        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
127        textView.needsDisplay = true
128        let caret = textView.selectedRange().location
129        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
130    }
131
132    /// Folds or unfolds the heading whose line holds the caret. Returns false off a heading.
133    @discardableResult
134    public func toggleFoldAtCaret() -> Bool {
135        guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
136        var folds = view.folds
137        if folds.contains(heading) { folds.remove(heading) } else { folds.insert(heading) }
138        setFolds(folds)
139        return true
140    }
141
142    /// Folds every heading, or unfolds everything if anything is folded.
143    public func toggleAllFolds() {
144        setFolds(view.folds.isEmpty ? Set(Presentation.headings(document.tree)) : [])
145    }
146
147    private func setCaret(_ offset: Int) {
148        let clamped = max(0, min(offset, utf16Length))
149        previousSelection = clamped
150        textView.setSelectedRange(NSRange(location: clamped, length: 0))
151    }
152
153    // MARK: - Styling
154
155    private func restyleOutsideEditing(_ range: Range<Int>) {
156        guard let storage = textView.textStorage else { return }
157        storage.beginEditing()
158        restyle(range, in: storage)
159        storage.endEditing()
160    }
161
162    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
163    /// attribute changes are allowed and characters must not change.
164    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
165        guard !range.isEmpty else { return }
166        let whole = NSRange(range)
167        storage.setAttributes(theme.base, range: whole)
168        for run in Presentation.indents(document.tree, in: range) {
169            guard let clipped = clip(run.range, to: range) else { continue }
170            storage.addAttribute(.paragraphStyle, value: theme.paragraphStyle(firstLine: run.firstLine, wrapped: run.wrapped), range: clipped)
171        }
172        for run in Presentation.styles(document.tree, in: range) {
173            guard let clipped = clip(run.range, to: range) else { continue }
174            theme.apply(run.role, to: storage, range: clipped)
175        }
176    }
177
178    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
179        let clipped = run.clamped(to: range)
180        return clipped.isEmpty ? nil : NSRange(clipped)
181    }
182
183    /// The region an edit affects in one version of the tree: inside the innermost section
184    /// holding the edited lines (plus the line after), every element that overlaps them or the
185    /// line on either side. A changed heading line, or an added or removed heading, widens it
186    /// to that section's whole own body. Run on the old and the new tree, the union covers
187    /// elements that grew and elements that shrank.
188    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
189        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
190        let lineRange = lines.location..<(lines.location + lines.length)
191        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
192        var container = tree.root
193        while let child = container.children.first(where: {
194            ($0.kind == .section || $0.kind == .zerothSection)
195                && $0.range.lowerBound <= lineRange.lowerBound && lineRange.upperBound <= $0.range.upperBound
196        }) {
197            container = child
198        }
199        var lower = lineRange.lowerBound
200        var upper = lineRange.upperBound
201        let children = container.children
202        for child in children where child.range.overlaps(around) {
203            lower = min(lower, child.range.lowerBound)
204            upper = max(upper, child.range.upperBound)
205        }
206        let heading = children.first { $0.kind == .heading }
207        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
208            lower = min(lower, container.range.lowerBound)
209            upper = max(upper, children.first { $0.kind == .section }?.range.lowerBound ?? container.range.upperBound)
210        }
211        return lower..<min(upper, text.length)
212    }
213
214    // MARK: - Editing
215
216    fileprivate func storageEdited(range: NSRange, delta: Int) {
217        guard !isLoading, let storage = textView.textStorage else { return }
218        let clock = ContinuousClock()
219        let start = clock.now
220        let replacement = (storage.string as NSString).substring(with: range)
221        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
222        let oldText = document.text as NSString
223        let newText = storage.string as NSString
224        let newEnd = edit.range.lowerBound + replacement.utf16.count
225        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
226            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
227        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
228        do {
229            try document.apply([edit], baseRevision: document.revision)
230        } catch {
231            assertionFailure("text view and document disagree: \(error)")
232            return
233        }
234        let oldHidden = hidden.all
235        view = view.mapped(through: [edit]).pruned(to: document.tree)
236        folded.set(view.folds)
237        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
238        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
239        let delta = edit.replacement.utf16.count - edit.range.count
240        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
241        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
242        if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
243            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
244        }
245        onEditTiming?(clock.now - start)
246    }
247
248    /// Whether a heading line touches `start..<end` or starts right after it, where joining
249    /// lines could take it away.
250    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
251        let length = min(end + 1, text.length) - start
252        guard length >= 0 else { return false }
253        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
254        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
255            let stars = line.prefix { $0 == "*" }
256            let after = line.dropFirst(stars.count)
257            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
258        }
259    }
260
261    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
262        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
263        return mapped
264    }
265
266    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
267    /// back jumps to the end of the heading line.
268    fileprivate func selectionChanged() {
269        let selection = textView.selectedRange()
270        defer { previousSelection = selection.location }
271        guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
272        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
273    }
274}
275
276extension OrgEditor: NSTextViewDelegate {
277    public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
278        switch selector {
279        case #selector(NSResponder.insertTab(_:)): return toggleFoldAtCaret()
280        case #selector(NSResponder.insertBacktab(_:)):
281            toggleAllFolds()
282            return true
283        default: return false
284        }
285    }
286
287    public func textViewDidChangeSelection(_ notification: Notification) {
288        selectionChanged()
289    }
290}
291
292extension OrgEditor: NSTextStorageDelegate {
293    public nonisolated func textStorage(
294        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
295    ) {
296        guard editedMask.contains(.editedCharacters) else { return }
297        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
298    }
299}
300
301extension OrgEditor: NSTextContentStorageDelegate {
302    /// Folded text isn't enumerated, so it isn't laid out or drawn.
303    public nonisolated func textContentManager(
304        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
305    ) -> Bool {
306        guard let range = textElement.elementRange else { return true }
307        let documentStart = textContentManager.documentRange.location
308        let start = textContentManager.offset(from: documentStart, to: range.location)
309        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
310        return !hidden.covers(start, end)
311    }
312}
313
314extension OrgEditor: NSTextLayoutManagerDelegate {
315    public nonisolated func textLayoutManager(
316        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
317    ) -> NSTextLayoutFragment {
318        let range = textElement.elementRange
319        if let range, let manager = textLayoutManager.textContentManager {
320            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
321            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
322        }
323        return NSTextLayoutFragment(textElement: textElement, range: range)
324    }
325}
326
327/// A heading line drawn with an ellipsis after it, like org's folded headings.
328final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
329    override func draw(at point: CGPoint, in context: CGContext) {
330        super.draw(at: point, in: context)
331        guard let line = textLineFragments.first else { return }
332        let bounds = line.typographicBounds
333        let ellipsis = NSAttributedString(string: " …", attributes: [
334            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
335            .foregroundColor: NSColor.secondaryLabelColor,
336        ])
337        NSGraphicsContext.saveGraphicsState()
338        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
339        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
340        NSGraphicsContext.restoreGraphicsState()
341    }
342
343    override var renderingSurfaceBounds: CGRect {
344        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
345    }
346}
347#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