Sources/OrgEditorAppKit/OrgEditor.swift

34d9da1754968de3302011c7e5328aa53829ed93
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

487 lines · 22272 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    /// Text before this offset is styled; after it, only base attributes until the background
 59    /// passes reach it. Always at a line start.
 60    private(set) var styledUpTo = 0
 61    private var stylingScheduled = false
 62
 63    /// Styled before the first render: more than a screenful.
 64    static let firstStyleChunk = 30_000
 65    /// Styled per run-loop turn afterwards.
 66    static let styleChunk = 200_000
 67
 68    public init(document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true) {
 69        self.document = document
 70        textView = NSTextView(usingTextLayoutManager: true)
 71        super.init()
 72        textView.frame = frame
 73        textView.isRichText = false
 74        textView.isEditable = editable
 75        textView.allowsUndo = true
 76        textView.isAutomaticQuoteSubstitutionEnabled = false
 77        textView.isAutomaticDashSubstitutionEnabled = false
 78        textView.isAutomaticTextReplacementEnabled = false
 79        textView.isAutomaticSpellingCorrectionEnabled = false
 80        textView.font = theme.font
 81        textView.typingAttributes = theme.base
 82        textView.isVerticallyResizable = true
 83        textView.autoresizingMask = [.width]
 84        textView.textContainer?.widthTracksTextView = true
 85        textView.delegate = self
 86        textView.textStorage?.delegate = self
 87        textLayoutManager.delegate = self
 88        textContentStorage.delegate = self
 89
 90        load(document.text)
 91        if let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
 92    }
 93
 94    /// Replaces the storage's text. Setting the attributed string directly is about 100x
 95    /// faster than `NSTextView.string` for large files.
 96    private func load(_ text: String) {
 97        isLoading = true
 98        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
 99        isLoading = false
100        styledUpTo = 0
101        styleNextChunk(Self.firstStyleChunk)
102        scheduleStyling()
103    }
104
105    // MARK: - Initial styling
106
107    /// Styles whole lines from the watermark onward, about `size` units.
108    private func styleNextChunk(_ size: Int) {
109        let text = textView.textStorage!.string as NSString
110        guard styledUpTo < text.length else { return }
111        let target = min(text.length, styledUpTo + size)
112        let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
113        restyleOutsideEditing(styledUpTo..<end)
114        styledUpTo = end
115    }
116
117    private func scheduleStyling() {
118        guard !stylingScheduled, styledUpTo < utf16Length else { return }
119        stylingScheduled = true
120        DispatchQueue.main.async { [weak self] in
121            guard let self else { return }
122            self.stylingScheduled = false
123            self.styleNextChunk(Self.styleChunk)
124            self.scheduleStyling()
125        }
126    }
127
128    /// Styles everything still waiting for a background pass.
129    public func finishStyling() {
130        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
131    }
132
133    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
134    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
135    var utf16Length: Int { (textView.string as NSString).length }
136
137    /// A scroll view holding the text view, ready for a window.
138    public func makeScrollView() -> NSScrollView {
139        let scroll = NSScrollView(frame: textView.frame)
140        scroll.hasVerticalScroller = true
141        scroll.documentView = textView
142        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
143        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
144        return scroll
145    }
146
147    // MARK: - Saving
148
149    /// Saves through `saver`. When a merge changes the buffer, the text view is reloaded and
150    /// folds are mapped through the change.
151    @discardableResult
152    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
153        let before = document.text
154        let outcome = try saver.save(&document, to: url)
155        if document.text != before {
156            let edits = lineEdits(from: before, to: document.text)
157            load(document.text)
158            let mapped = view.mapped(through: edits)
159            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
160        }
161        return outcome
162    }
163
164    // MARK: - Disk
165
166    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
167    /// its headings.
168    public func diskChanged(to bytes: [UInt8]) {
169        let edits: [TextEdit]
170        switch document.diskChanged(to: bytes) {
171        case .reloaded(let changes), .merged(let changes): edits = changes
172        case .unchanged, .conflict: return
173        }
174        let mapped = view.mapped(through: edits)
175        load(document.text)
176        setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
177    }
178
179    // MARK: - Folding
180
181    public var foldState: FoldState {
182        FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
183    }
184
185    private var globalVisibility: GlobalVisibility?
186
187    public func setFolds(_ state: FoldState) {
188        view.folds = state.folds
189        view.bodyFolds = state.bodyFolds
190        view = view.pruned(to: document.tree)
191        updateHidden()
192        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
193        textView.needsDisplay = true
194        let caret = textView.selectedRange().location
195        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
196    }
197
198    private func updateHidden() {
199        folded.set(view.folds.union(view.bodyFolds))
200        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
201    }
202
203    /// TAB on a heading: folded, children, subtree. Returns false off a heading.
204    @discardableResult
205    public func cycleAtCaret() -> Bool {
206        guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
207        setFolds(Presentation.cycle(heading, in: document.tree, foldState))
208        return true
209    }
210
211    /// Shift-TAB: overview, contents, show all.
212    public func cycleGlobal() {
213        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
214        globalVisibility = visibility
215        setFolds(state)
216    }
217
218    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
219    public func reveal(_ offset: Int) {
220        let target = max(0, min(offset, utf16Length))
221        var state = foldState
222        for entry in Presentation.outline(document.tree) where entry.start < target && target < entry.end {
223            state.folds.remove(entry.start)
224            state.bodyFolds.remove(entry.start)
225        }
226        setFolds(state)
227        setCaret(target)
228        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
229    }
230
231    private func setCaret(_ offset: Int) {
232        let clamped = max(0, min(offset, utf16Length))
233        previousSelection = clamped
234        textView.setSelectedRange(NSRange(location: clamped, length: 0))
235    }
236
237    // MARK: - Styling
238
239    private func restyleOutsideEditing(_ range: Range<Int>) {
240        guard let storage = textView.textStorage else { return }
241        storage.beginEditing()
242        restyle(range, in: storage)
243        storage.endEditing()
244    }
245
246    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
247    /// attribute changes are allowed and characters must not change.
248    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
249        guard !range.isEmpty else { return }
250        let whole = NSRange(range)
251        storage.setAttributes(theme.base, range: whole)
252        let text = storage.string as NSString
253        for run in Presentation.indents(document.tree, in: range) {
254            guard let clipped = clip(run.range, to: range) else { continue }
255            guard run.firstLine == run.wrapped else {
256                storage.addAttribute(.paragraphStyle, value: theme.paragraphStyle(firstLine: run.firstLine, wrapped: run.wrapped), range: clipped)
257                continue
258            }
259            // Body lines wrap under their own text: past leading blanks, and past a list bullet
260            // and checkbox, as adaptive-wrap does in Emacs.
261            var location = clipped.location
262            while location < NSMaxRange(clipped) {
263                let line = text.lineRange(for: NSRange(location: location, length: 0))
264                let hanging = Self.hangingColumns(text.substring(with: line))
265                let lineRange = NSIntersectionRange(line, clipped)
266                storage.addAttribute(.paragraphStyle, value: theme.paragraphStyle(firstLine: run.firstLine, wrapped: run.wrapped + hanging), range: lineRange)
267                location = NSMaxRange(line)
268            }
269        }
270        for run in Presentation.styles(document.tree, in: range) {
271            guard let clipped = clip(run.range, to: range) else { continue }
272            theme.apply(run.role, to: storage, range: clipped)
273        }
274    }
275
276    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
277        let clipped = run.clamped(to: range)
278        return clipped.isEmpty ? nil : NSRange(clipped)
279    }
280
281    /// The region an edit affects in one version of the tree: inside the innermost section
282    /// holding the edited lines (plus the line after), every element that overlaps them or the
283    /// line on either side. A changed heading line, or an added or removed heading, widens it
284    /// to that section's whole own body. Run on the old and the new tree, the union covers
285    /// elements that grew and elements that shrank.
286    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
287        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
288        let lineRange = lines.location..<(lines.location + lines.length)
289        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
290        var container = tree.root
291        while let child = container.child(containing: lineRange.lowerBound),
292              child.kind == .section || child.kind == .zerothSection,
293              lineRange.upperBound <= child.range.upperBound {
294            container = child
295        }
296        var lower = lineRange.lowerBound
297        var upper = lineRange.upperBound
298        // Tables and lists carry no styling of their own, so inside them only the rows or
299        // items around the edit change, however large they are.
300        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
301            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
302                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
303                let inner = overlapping(node.children(overlapping: around))
304                return inner.isEmpty ? [node] : inner
305            }
306        }
307        for child in overlapping(container.children(overlapping: around)) {
308            lower = min(lower, child.range.lowerBound)
309            upper = max(upper, child.range.upperBound)
310        }
311        let heading = container.firstChild(.heading)
312        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
313            lower = min(lower, container.range.lowerBound)
314            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
315        }
316        return lower..<min(upper, text.length)
317    }
318
319    // MARK: - Editing
320
321    fileprivate func storageEdited(range: NSRange, delta: Int) {
322        guard !isLoading, let storage = textView.textStorage else { return }
323        let clock = ContinuousClock()
324        let start = clock.now
325        let replacement = (storage.string as NSString).substring(with: range)
326        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
327        let oldText = document.text as NSString
328        let newText = storage.string as NSString
329        let newEnd = edit.range.lowerBound + replacement.utf16.count
330        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
331            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
332        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
333        do {
334            try document.apply([edit], baseRevision: document.revision)
335        } catch {
336            assertionFailure("text view and document disagree: \(error)")
337            return
338        }
339        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
340        // edited line when the edit reaches into unstyled text.
341        if styledUpTo >= edit.range.upperBound {
342            styledUpTo += edit.replacement.utf16.count - edit.range.count
343        } else if styledUpTo > edit.range.lowerBound {
344            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
345        }
346        let oldHidden = hidden.all
347        view = view.mapped(through: [edit]).pruned(to: document.tree)
348        folded.set(view.folds)
349        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
350        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
351        let delta = edit.replacement.utf16.count - edit.range.count
352        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
353        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
354        if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
355            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
356        }
357        onEditTiming?(clock.now - start)
358    }
359
360    /// Columns a wrapped continuation of `line` should start past the line's own start.
361    nonisolated static func hangingColumns(_ line: String) -> Int {
362        var columns = 0
363        var rest = Substring(line)
364        while let c = rest.first, c == " " || c == "\t" {
365            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
366            rest = rest.dropFirst()
367        }
368        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
369        var bullet = 0
370        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
371            bullet = 1
372        } else {
373            let digits = rest.prefix { $0.isASCII && $0.isNumber }
374            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
375                bullet = digits.count + 1
376            }
377        }
378        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
379        columns += bullet + 1
380        let afterBullet = rest.dropFirst(bullet + 1)
381        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
382           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
383            columns += 4
384        }
385        return columns
386    }
387
388    /// Whether a heading line touches `start..<end` or starts right after it, where joining
389    /// lines could take it away.
390    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
391        let length = min(end + 1, text.length) - start
392        guard length >= 0 else { return false }
393        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
394        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
395            let stars = line.prefix { $0 == "*" }
396            let after = line.dropFirst(stars.count)
397            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
398        }
399    }
400
401    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
402        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
403        return mapped
404    }
405
406    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
407    /// back jumps to the end of the heading line.
408    fileprivate func selectionChanged() {
409        let selection = textView.selectedRange()
410        defer { previousSelection = selection.location }
411        guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
412        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
413    }
414}
415
416extension OrgEditor: NSTextViewDelegate {
417    public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
418        switch selector {
419        case #selector(NSResponder.insertTab(_:)): return cycleAtCaret()
420        case #selector(NSResponder.insertBacktab(_:)):
421            cycleGlobal()
422            return true
423        default: return false
424        }
425    }
426
427    public func textViewDidChangeSelection(_ notification: Notification) {
428        selectionChanged()
429    }
430}
431
432extension OrgEditor: NSTextStorageDelegate {
433    public nonisolated func textStorage(
434        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
435    ) {
436        guard editedMask.contains(.editedCharacters) else { return }
437        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
438    }
439}
440
441extension OrgEditor: NSTextContentStorageDelegate {
442    /// Folded text isn't enumerated, so it isn't laid out or drawn.
443    public nonisolated func textContentManager(
444        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
445    ) -> Bool {
446        guard let range = textElement.elementRange else { return true }
447        let documentStart = textContentManager.documentRange.location
448        let start = textContentManager.offset(from: documentStart, to: range.location)
449        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
450        return !hidden.covers(start, end)
451    }
452}
453
454extension OrgEditor: NSTextLayoutManagerDelegate {
455    public nonisolated func textLayoutManager(
456        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
457    ) -> NSTextLayoutFragment {
458        let range = textElement.elementRange
459        if let range, let manager = textLayoutManager.textContentManager {
460            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
461            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
462        }
463        return NSTextLayoutFragment(textElement: textElement, range: range)
464    }
465}
466
467/// A heading line drawn with an ellipsis after it, like org's folded headings.
468final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
469    override func draw(at point: CGPoint, in context: CGContext) {
470        super.draw(at: point, in: context)
471        guard let line = textLineFragments.first else { return }
472        let bounds = line.typographicBounds
473        let ellipsis = NSAttributedString(string: " …", attributes: [
474            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
475            .foregroundColor: NSColor.secondaryLabelColor,
476        ])
477        NSGraphicsContext.saveGraphicsState()
478        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
479        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
480        NSGraphicsContext.restoreGraphicsState()
481    }
482
483    override var renderingSurfaceBounds: CGRect {
484        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
485    }
486}
487#endif