Sources/OrgEditorAppKit/OrgEditor.swift

6dc096637db6e263db38fad845d46bc852cd3962
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

759 lines · 34132 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    /// One paragraph style object per indent pair, shared by every line that uses it.
 63    private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
 64
 65    private struct IndentKey: Hashable {
 66        let firstLine: Int
 67        let wrapped: Int
 68    }
 69
 70    /// Styled before the first render: more than a screenful.
 71    static let firstStyleChunk = 30_000
 72    /// Styled per run-loop turn afterwards.
 73    static let styleChunk = 200_000
 74
 75    /// Highlights code in src blocks; nil leaves code plain.
 76    public let highlighter: (any CodeHighlighter)?
 77
 78    /// What the file is: org, or plain text, highlighted as code when the language is known.
 79    public enum Mode: Equatable, Sendable {
 80        case org
 81        case plain(language: String?)
 82    }
 83
 84    public let mode: Mode
 85    public var isOrg: Bool { mode == .org }
 86    /// Highlights of the whole file in plain mode, and the revision they were made for.
 87    private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
 88
 89    public init(
 90        document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
 91        highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org
 92    ) {
 93        self.document = document
 94        self.highlighter = highlighter
 95        self.mode = mode
 96        let orgTextView = OrgTextView(usingTextLayoutManager: true)
 97        textView = orgTextView
 98        dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
 99        super.init()
100        orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
101        orgTextView.onMouseDown = { [weak self] in
102            self?.markActive = false
103            self?.modalMouseDown()
104        }
105        textView.usesFindBar = true
106        textView.frame = frame
107        textView.isRichText = false
108        textView.isEditable = editable
109        textView.allowsUndo = true
110        textView.isAutomaticQuoteSubstitutionEnabled = false
111        textView.isAutomaticDashSubstitutionEnabled = false
112        textView.isAutomaticTextReplacementEnabled = false
113        textView.isAutomaticSpellingCorrectionEnabled = false
114        textView.font = theme.font
115        textView.typingAttributes = theme.base
116        textView.isVerticallyResizable = true
117        textView.autoresizingMask = [.width]
118        textView.textContainer?.widthTracksTextView = true
119        textView.delegate = self
120        textView.textStorage?.delegate = self
121        textLayoutManager.delegate = self
122        textContentStorage.delegate = self
123
124        load(document.text)
125        if isOrg, let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
126    }
127
128    /// Replaces the storage's text. Setting the attributed string directly is about 100x
129    /// faster than `NSTextView.string` for large files.
130    private func load(_ text: String) {
131        isLoading = true
132        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
133        isLoading = false
134        styledUpTo = 0
135        styleNextChunk(Self.firstStyleChunk)
136        scheduleStyling()
137    }
138
139    // MARK: - Initial styling
140
141    /// Styles whole lines from the watermark onward, about `size` units.
142    private func styleNextChunk(_ size: Int) {
143        let text = textView.textStorage!.string as NSString
144        guard styledUpTo < text.length else { return }
145        let target = min(text.length, styledUpTo + size)
146        let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
147        restyleOutsideEditing(styledUpTo..<end)
148        styledUpTo = end
149    }
150
151    private func scheduleStyling() {
152        guard !stylingScheduled, styledUpTo < utf16Length else { return }
153        stylingScheduled = true
154        DispatchQueue.main.async { [weak self] in
155            guard let self else { return }
156            self.stylingScheduled = false
157            self.styleNextChunk(Self.styleChunk)
158            self.scheduleStyling()
159        }
160    }
161
162    /// Styles everything still waiting for a background pass.
163    public func finishStyling() {
164        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
165    }
166
167    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
168    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
169    var utf16Length: Int { (textView.string as NSString).length }
170
171    /// A scroll view holding the text view, ready for a window.
172    public func makeScrollView() -> NSScrollView {
173        let scroll = NSScrollView(frame: textView.frame)
174        scroll.hasVerticalScroller = true
175        scroll.documentView = textView
176        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
177        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
178        return scroll
179    }
180
181    // MARK: - Saving
182
183    /// Saves through `saver`. A merge that changes the buffer reloads the text view.
184    @discardableResult
185    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
186        try update { try saver.save(&$0, to: url) }
187    }
188
189    /// Called after every change to the document, typed or not.
190    public var onChange: (() -> Void)?
191
192    // MARK: - Commands
193
194    /// Called with messages commands report, such as why one couldn't run here.
195    public var onMessage: ((String) -> Void)?
196    /// Called with the pending prefix and what can follow it, and with nil when it ends.
197    /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
198    public var onModeChange: ((String?) -> Void)?
199    /// The selection moved.
200    public var onSelectionChange: ((NSRange) -> Void)?
201    var reportedMode: String?
202    public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
203    /// Called with `app.*` commands, which the app carries out.
204    public var onAppCommand: ((String) -> Void)?
205    /// Called when a command asks a question; reply with the answer, or nil to cancel.
206    public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
207    /// Runs work outside the text, such as a table recalculation in Emacs.
208    public var onExternal: ((ExternalRequest) -> Void)?
209
210    public var keymap: Keymap {
211        get { dispatcher.keymap }
212        set {
213            dispatcher.keymap = newValue
214            dispatcher.reset()
215        }
216    }
217
218    public var optionAsMeta: OptionAsMeta = [.left]
219    /// Org options commands follow.
220    public var options: EditingOptions = .org
221    var dispatcher: KeyDispatcher
222    /// Evil-style editing, for modal keymaps such as Doom's.
223    public var modal = false {
224        didSet {
225            guard modal != oldValue else { return }
226            vim = Vim()
227            dispatcher.mode = modal ? vim.mode.keymapMode : nil
228            dispatcher.reset()
229            updateCursor()
230        }
231    }
232    var vim = Vim()
233    /// The text and caret when insert state began, to know what was typed for `.`.
234    var insertSnapshot: (text: String, caret: Int)?
235    /// The evil cursor in visual states, where the selection's start isn't it.
236    var visualCaret: Int?
237    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
238    private(set) var markActive = false
239
240    private func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
241        let selected = textView.selectedRange()
242        return EditContext(
243            revision: document.revision, text: document.text, tree: document.tree,
244            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
245            hidden: hidden.all, options: options
246        )
247    }
248
249    /// Offers a key press to the keymap. False lets the text system have it.
250    func handleKey(_ event: NSEvent) -> Bool {
251        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
252        if modal { return handleModal(chord) }
253        switch dispatcher.feed(chord) {
254        case .pending(let keys):
255            let next = keymap.continuations(of: keys).map { item in
256                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
257            }
258            onKeysPending?(KeySequence.format(keys), next)
259            return true
260        case .cancelled:
261            onKeysPending?(nil, [])
262            onMessage?("Quit")
263            return true
264        case .undefined(let keys):
265            onKeysPending?(nil, [])
266            onMessage?("\(KeySequence.format(keys)) is undefined")
267            return true
268        case .unbound:
269            return false
270        case .complete(let keys, let candidates):
271            if keys.count > 1 { onKeysPending?(nil, []) }
272            let context = context()
273            let runnable = candidates.first { binding in
274                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
275            }
276            if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
277                run(binding.command)
278                return true
279            }
280            return false
281        }
282    }
283
284    private func applies(_ id: String, in context: EditContext) -> Bool {
285        if !isOrg, id.hasPrefix("org.") { return false }
286        return switch EditorCommands.command(id)?.action {
287        case .text(let command): command.applies(in: context)
288        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
289        case .edit, .mark, .app: true
290        case nil: true
291        }
292    }
293
294    /// Runs a command by id, as a key, a menu item or the palette would.
295    public func run(_ id: String) {
296        guard let command = EditorCommands.command(id) else {
297            onMessage?("Unknown command \(id)")
298            return
299        }
300        if !isOrg, id.hasPrefix("org.") {
301            onMessage?("Not an org file")
302            return
303        }
304        var keepMark = false
305        switch command.action {
306        case .text(let text):
307            perform(text)
308        case .view:
309            if id == "org.cycle" { cycleAtCaret() } else { cycleGlobal() }
310        case .edit(let selector, let extending):
311            if markActive, let extending {
312                keepMark = true
313                textView.doCommand(by: NSSelectorFromString(extending))
314            } else if selector == "performTextFinderAction:" {
315                let item = NSMenuItem()
316                item.tag = NSTextFinder.Action.showFindInterface.rawValue
317                textView.performTextFinderAction(item)
318            } else {
319                textView.doCommand(by: NSSelectorFromString(selector))
320            }
321        case .mark:
322            if id == "edit.set-mark" {
323                let caret = textView.selectedRange().location
324                textView.setSelectedRange(NSRange(location: caret, length: 0))
325                keepMark = true
326                onMessage?("Mark set")
327            } else {
328                let selected = textView.selectedRange()
329                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
330                onMessage?("Quit")
331            }
332        case .app:
333            onAppCommand?(id)
334        }
335        markActive = keepMark
336    }
337
338    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
339    /// they form one undo step and reach the document through the same path.
340    @discardableResult
341    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
342        let context = context(now: now, answers: answers)
343        let step = command.run(in: context)
344        switch step {
345        case .commit(let result):
346            guard textView.isEditable || result.edits.isEmpty else {
347                onMessage?("This file is read-only.")
348                return .failed("read-only")
349            }
350            applyEdits(result.edits)
351            if let selection = result.selection?.first {
352                setCaret(selection.lowerBound)
353                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
354            }
355            for case .message(let text) in result.effects { onMessage?(text) }
356        case .failed(let message):
357            onMessage?(message)
358        case .external(let request):
359            if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
360        case .prompt(let prompt):
361            onPrompt?(prompt) { [weak self] answer in
362                guard let self else { return }
363                guard let answer else {
364                    self.onMessage?("Quit")
365                    return
366                }
367                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
368            }
369        }
370        return step
371    }
372
373    // MARK: - Disk
374
375    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
376    /// its headings.
377    @discardableResult
378    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
379        update { $0.diskChanged(to: bytes) }
380    }
381
382    // MARK: - Folding
383
384    public var foldState: FoldState {
385        FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
386    }
387
388    private var globalVisibility: GlobalVisibility?
389
390    public func setFolds(_ state: FoldState) {
391        view.folds = state.folds
392        view.bodyFolds = state.bodyFolds
393        view = view.pruned(to: document.tree)
394        updateHidden()
395        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
396        textView.needsDisplay = true
397        let caret = textView.selectedRange().location
398        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
399    }
400
401    private func updateHidden() {
402        folded.set(view.folds.union(view.bodyFolds))
403        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
404    }
405
406    /// TAB on a heading: folded, children, subtree. Returns false off a heading.
407    @discardableResult
408    public func cycleAtCaret() -> Bool {
409        guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
410        setFolds(Presentation.cycle(heading, in: document.tree, foldState))
411        return true
412    }
413
414    /// Shift-TAB: overview, contents, show all.
415    public func cycleGlobal() {
416        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
417        globalVisibility = visibility
418        setFolds(state)
419    }
420
421    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
422    public func reveal(_ offset: Int) {
423        let target = max(0, min(offset, utf16Length))
424        var state = foldState
425        for entry in Presentation.outline(document.tree) where entry.start < target && target < entry.end {
426            state.folds.remove(entry.start)
427            state.bodyFolds.remove(entry.start)
428        }
429        setFolds(state)
430        setCaret(target)
431        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
432    }
433
434    /// Applies edits through the text view as one undo step, not merged with typing around it.
435    func applyEdits(_ edits: [TextEdit]) {
436        guard !edits.isEmpty, let storage = textView.textStorage else { return }
437        textView.breakUndoCoalescing()
438        textView.undoManager?.beginUndoGrouping()
439        for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
440            let range = NSRange(edit.range)
441            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
442            storage.replaceCharacters(in: range, with: edit.replacement)
443            textView.didChangeText()
444        }
445        textView.undoManager?.endUndoGrouping()
446        textView.breakUndoCoalescing()
447    }
448
449    func setCaret(_ offset: Int) {
450        let clamped = max(0, min(offset, utf16Length))
451        previousSelection = clamped
452        textView.setSelectedRange(NSRange(location: clamped, length: 0))
453    }
454
455    // MARK: - Styling
456
457    private func restyleOutsideEditing(_ range: Range<Int>) {
458        guard let storage = textView.textStorage else { return }
459        storage.beginEditing()
460        restyle(range, in: storage)
461        storage.endEditing()
462    }
463
464    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
465    /// attribute changes are allowed and characters must not change.
466    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
467        guard !range.isEmpty else { return }
468        let whole = NSRange(range)
469        storage.setAttributes(theme.base, range: whole)
470        guard isOrg else {
471            for run in plainRuns() where run.range.overlaps(range) {
472                guard let clipped = clip(run.range, to: range) else { continue }
473                theme.apply(.syntax(run.category), to: storage, range: clipped)
474            }
475            return
476        }
477        let text = storage.string as NSString
478        for run in Presentation.indents(document.tree, in: range) {
479            guard let clipped = clip(run.range, to: range) else { continue }
480            guard run.firstLine == run.wrapped else {
481                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
482                continue
483            }
484            // Body lines wrap under their own text: past leading blanks, and past a list bullet
485            // and checkbox, as adaptive-wrap does in Emacs.
486            var location = clipped.location
487            while location < NSMaxRange(clipped) {
488                let line = text.lineRange(for: NSRange(location: location, length: 0))
489                let hanging = Self.hangingColumns(text.substring(with: line))
490                let lineRange = NSIntersectionRange(line, clipped)
491                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
492                location = NSMaxRange(line)
493            }
494        }
495        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
496            guard let clipped = clip(run.range, to: range) else { continue }
497            theme.apply(run.role, to: storage, range: clipped)
498        }
499    }
500
501    /// Code highlights for the whole file in plain mode.
502    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
503        guard case .plain(let language?) = mode, let highlighter else { return [] }
504        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
505        let runs = highlighter.highlights(language: language, code: document.text)
506        codeRuns = (document.revision, runs)
507        return runs
508    }
509
510    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
511        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
512        if let style = paragraphStyles[key] { return style }
513        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
514        paragraphStyles[key] = style
515        return style
516    }
517
518    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
519        let clipped = run.clamped(to: range)
520        return clipped.isEmpty ? nil : NSRange(clipped)
521    }
522
523    /// The region an edit affects in one version of the tree: inside the innermost section
524    /// holding the edited lines (plus the line after), every element that overlaps them or the
525    /// line on either side. A changed heading line, or an added or removed heading, widens it
526    /// to that section's whole own body. Run on the old and the new tree, the union covers
527    /// elements that grew and elements that shrank.
528    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
529        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
530        let lineRange = lines.location..<(lines.location + lines.length)
531        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
532        var container = tree.root
533        while let child = container.child(containing: lineRange.lowerBound),
534              child.kind == .section || child.kind == .zerothSection,
535              lineRange.upperBound <= child.range.upperBound {
536            container = child
537        }
538        var lower = lineRange.lowerBound
539        var upper = lineRange.upperBound
540        // Tables and lists carry no styling of their own, so inside them only the rows or
541        // items around the edit change, however large they are.
542        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
543            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
544                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
545                let inner = overlapping(node.children(overlapping: around))
546                return inner.isEmpty ? [node] : inner
547            }
548        }
549        for child in overlapping(container.children(overlapping: around)) {
550            lower = min(lower, child.range.lowerBound)
551            upper = max(upper, child.range.upperBound)
552        }
553        let heading = container.firstChild(.heading)
554        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
555            lower = min(lower, container.range.lowerBound)
556            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
557        }
558        return lower..<min(upper, text.length)
559    }
560
561    // MARK: - Editing
562
563    fileprivate func storageEdited(range: NSRange, delta: Int) {
564        guard !isLoading, let storage = textView.textStorage else { return }
565        markActive = false
566        let clock = ContinuousClock()
567        let start = clock.now
568        let replacement = (storage.string as NSString).substring(with: range)
569        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
570        let oldText = document.text as NSString
571        let newText = storage.string as NSString
572        let newEnd = edit.range.lowerBound + replacement.utf16.count
573        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
574            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
575        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
576        do {
577            try document.apply([edit], baseRevision: document.revision)
578        } catch {
579            assertionFailure("text view and document disagree: \(error)")
580            return
581        }
582        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
583        // edited line when the edit reaches into unstyled text.
584        if styledUpTo >= edit.range.upperBound {
585            styledUpTo += edit.replacement.utf16.count - edit.range.count
586        } else if styledUpTo > edit.range.lowerBound {
587            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
588        }
589        let oldHidden = hidden.all
590        view = view.mapped(through: [edit]).pruned(to: document.tree)
591        folded.set(view.folds)
592        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
593        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
594        let delta = edit.replacement.utf16.count - edit.range.count
595        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
596        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
597        if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
598            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
599        }
600        onEditTiming?(clock.now - start)
601        onChange?()
602    }
603
604    /// Columns a wrapped continuation of `line` should start past the line's own start.
605    nonisolated static func hangingColumns(_ line: String) -> Int {
606        var columns = 0
607        var rest = Substring(line)
608        while let c = rest.first, c == " " || c == "\t" {
609            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
610            rest = rest.dropFirst()
611        }
612        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
613        var bullet = 0
614        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
615            bullet = 1
616        } else {
617            let digits = rest.prefix { $0.isASCII && $0.isNumber }
618            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
619                bullet = digits.count + 1
620            }
621        }
622        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
623        columns += bullet + 1
624        let afterBullet = rest.dropFirst(bullet + 1)
625        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
626           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
627            columns += 4
628        }
629        return columns
630    }
631
632    /// Whether a heading line touches `start..<end` or starts right after it, where joining
633    /// lines could take it away.
634    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
635        let length = min(end + 1, text.length) - start
636        guard length >= 0 else { return false }
637        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
638        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
639            let stars = line.prefix { $0 == "*" }
640            let after = line.dropFirst(stars.count)
641            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
642        }
643    }
644
645    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
646        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
647        return mapped
648    }
649
650    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
651    /// back jumps to the end of the heading line.
652    fileprivate func selectionChanged() {
653        let selection = textView.selectedRange()
654        defer { previousSelection = selection.location }
655        onSelectionChange?(selection)
656        guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
657        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
658    }
659}
660
661extension OrgEditor: DocumentBuffer {
662    /// The selected text, for capture's `%i`.
663    public var selectedText: String {
664        let range = textView.selectedRange()
665        guard range.length > 0 else { return "" }
666        return (textView.string as NSString).substring(with: range)
667    }
668
669    public var selection: [Range<Int>] {
670        let selected = textView.selectedRange()
671        return [selected.location..<NSMaxRange(selected)]
672    }
673
674    /// Runs `change`; if it changed the text, reloads the view with folds and the selection
675    /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
676    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
677        let before = document.text
678        let selected = textView.selectedRange()
679        let result = try change(&document)
680        if document.text != before {
681            let edits = lineEdits(from: before, to: document.text)
682            var state = view
683            state.selection = [selected.location..<NSMaxRange(selected)]
684            let mapped = state.mapped(through: edits)
685            load(document.text)
686            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
687            let selection = mapped.selection[0]
688            setCaret(selection.lowerBound)
689            if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
690            textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
691            textView.undoManager?.removeAllActions(withTarget: textView)
692        }
693        onChange?()
694        return result
695    }
696}
697
698extension OrgEditor: NSTextViewDelegate {
699    public func textViewDidChangeSelection(_ notification: Notification) {
700        selectionChanged()
701    }
702}
703
704extension OrgEditor: NSTextStorageDelegate {
705    public nonisolated func textStorage(
706        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
707    ) {
708        guard editedMask.contains(.editedCharacters) else { return }
709        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
710    }
711}
712
713extension OrgEditor: NSTextContentStorageDelegate {
714    /// Folded text isn't enumerated, so it isn't laid out or drawn.
715    public nonisolated func textContentManager(
716        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
717    ) -> Bool {
718        guard let range = textElement.elementRange else { return true }
719        let documentStart = textContentManager.documentRange.location
720        let start = textContentManager.offset(from: documentStart, to: range.location)
721        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
722        return !hidden.covers(start, end)
723    }
724}
725
726extension OrgEditor: NSTextLayoutManagerDelegate {
727    public nonisolated func textLayoutManager(
728        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
729    ) -> NSTextLayoutFragment {
730        let range = textElement.elementRange
731        if let range, let manager = textLayoutManager.textContentManager {
732            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
733            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
734        }
735        return NSTextLayoutFragment(textElement: textElement, range: range)
736    }
737}
738
739/// A heading line drawn with an ellipsis after it, like org's folded headings.
740final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
741    override func draw(at point: CGPoint, in context: CGContext) {
742        super.draw(at: point, in: context)
743        guard let line = textLineFragments.first else { return }
744        let bounds = line.typographicBounds
745        let ellipsis = NSAttributedString(string: " …", attributes: [
746            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
747            .foregroundColor: NSColor.secondaryLabelColor,
748        ])
749        NSGraphicsContext.saveGraphicsState()
750        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
751        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
752        NSGraphicsContext.restoreGraphicsState()
753    }
754
755    override var renderingSurfaceBounds: CGRect {
756        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
757    }
758}
759#endif