Sources/OrgEditorAppKit/OrgEditor.swift

3959d9c38d34f2d30757a8c9c88309a5328522e5
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

980 lines · 45546 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    /// Blocks drawn on a shaded band.
 56    let shaded = HiddenRanges()
 57    private(set) var theme = Theme()
 58    /// Colors and type; a change restyles the file.
 59    public var themeSpec: ThemeSpec = .default {
 60        didSet {
 61            guard themeSpec != oldValue else { return }
 62            theme = Theme(themeSpec)
 63            applyThemeToView()
 64            restyleEverything()
 65            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
 66        }
 67    }
 68    private var isLoading = false
 69    private var previousSelection = 0
 70    /// Text before this offset is styled; after it, only base attributes until the background
 71    /// passes reach it. Always at a line start.
 72    private(set) var styledUpTo = 0
 73    private var stylingScheduled = false
 74    /// One paragraph style object per indent pair, shared by every line that uses it.
 75    private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
 76
 77    private struct IndentKey: Hashable {
 78        let firstLine: Int
 79        let wrapped: Int
 80    }
 81
 82    /// Styled before the first render: more than a screenful.
 83    static let firstStyleChunk = 30_000
 84    /// Styled per run-loop turn afterwards.
 85    static let styleChunk = 200_000
 86
 87    /// Highlights code in src blocks; nil leaves code plain.
 88    public let highlighter: (any CodeHighlighter)?
 89
 90    /// What the file is: org, or plain text, highlighted as code when the language is known.
 91    public enum Mode: Equatable, Sendable {
 92        case org
 93        case plain(language: String?)
 94    }
 95
 96    public let mode: Mode
 97    public var isOrg: Bool { mode == .org }
 98    /// Highlights of the whole file in plain mode, and the revision they were made for.
 99    private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
100
101    public init(
102        document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
103        highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org
104    ) {
105        self.document = document
106        self.highlighter = highlighter
107        self.mode = mode
108        let orgTextView = OrgTextView(usingTextLayoutManager: true)
109        textView = orgTextView
110        dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
111        super.init()
112        orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
113        orgTextView.onMouseDown = { [weak self] in
114            self?.markActive = false
115            self?.modalMouseDown()
116        }
117        textView.usesFindBar = true
118        textView.frame = frame
119        textView.isRichText = false
120        textView.isEditable = editable
121        textView.allowsUndo = true
122        textView.isAutomaticQuoteSubstitutionEnabled = false
123        textView.isAutomaticDashSubstitutionEnabled = false
124        textView.isAutomaticTextReplacementEnabled = false
125        textView.isAutomaticSpellingCorrectionEnabled = false
126        applyThemeToView()
127        textView.isVerticallyResizable = true
128        textView.autoresizingMask = [.width]
129        textView.textContainer?.widthTracksTextView = true
130        textView.delegate = self
131        textView.textStorage?.delegate = self
132        textLayoutManager.delegate = self
133        textContentStorage.delegate = self
134
135        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
136        load(document.text)
137        if isOrg, let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
138    }
139
140    /// Replaces the storage's text. Setting the attributed string directly is about 100x
141    /// faster than `NSTextView.string` for large files.
142    private func load(_ text: String) {
143        isLoading = true
144        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
145        isLoading = false
146        styledUpTo = 0
147        styleNextChunk(Self.firstStyleChunk)
148        scheduleStyling()
149    }
150
151    // MARK: - Initial styling
152
153    /// Styles whole lines from the watermark onward, about `size` units.
154    private func styleNextChunk(_ size: Int) {
155        let text = textView.textStorage!.string as NSString
156        guard styledUpTo < text.length else { return }
157        let target = min(text.length, styledUpTo + size)
158        let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
159        restyleOutsideEditing(styledUpTo..<end)
160        styledUpTo = end
161    }
162
163    /// The text view's own colors and font, and the line numbers'.
164    private func applyThemeToView() {
165        textView.font = theme.font
166        textView.typingAttributes = theme.base
167        textView.drawsBackground = true
168        textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
169        textView.insertionPointColor = theme.color("cursor") ?? .textColor
170        textView.selectedTextAttributes = [.backgroundColor: theme.color("selection") ?? .selectedTextBackgroundColor]
171        if let view = orgTextView {
172            view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
173            view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
174            view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
175            view.updateGutter()
176            view.needsDisplay = true
177        }
178    }
179
180    /// Styles the whole file again, a screenful now and the rest in the background.
181    private func restyleEverything() {
182        styledUpTo = 0
183        revealedLine = caretLine
184        styleNextChunk(Self.firstStyleChunk)
185        scheduleStyling()
186    }
187
188    private var caretLine: NSRange {
189        let text = textView.string as NSString
190        return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
191    }
192
193    private func scheduleStyling() {
194        guard !stylingScheduled, styledUpTo < utf16Length else { return }
195        stylingScheduled = true
196        DispatchQueue.main.async { [weak self] in
197            guard let self else { return }
198            self.stylingScheduled = false
199            self.styleNextChunk(Self.styleChunk)
200            self.scheduleStyling()
201        }
202    }
203
204    /// Styles everything still waiting for a background pass.
205    public func finishStyling() {
206        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
207    }
208
209    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
210    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
211    var utf16Length: Int { (textView.string as NSString).length }
212
213    /// A scroll view holding the text view, ready for a window.
214    public func makeScrollView() -> NSScrollView {
215        let scroll = NSScrollView(frame: textView.frame)
216        scroll.hasVerticalScroller = true
217        scroll.documentView = textView
218        orgTextView?.showsLineNumbers = showLineNumbers
219        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
220        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
221        return scroll
222    }
223
224    // MARK: - Saving
225
226    /// Saves through `saver`. A merge that changes the buffer reloads the text view.
227    @discardableResult
228    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
229        try update { try saver.save(&$0, to: url) }
230    }
231
232    /// Called after every change to the document, typed or not.
233    public var onChange: (() -> Void)?
234
235    // MARK: - Commands
236
237    /// Called with messages commands report, such as why one couldn't run here.
238    public var onMessage: ((String) -> Void)?
239    /// Called with the pending prefix and what can follow it, and with nil when it ends.
240    /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
241    public var onModeChange: ((String?) -> Void)?
242    /// The selection moved.
243    public var onSelectionChange: ((NSRange) -> Void)?
244    var reportedMode: String?
245    public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
246    /// Called with `app.*` commands, which the app carries out.
247    public var onAppCommand: ((String) -> Void)?
248    /// Called when a command asks a question; reply with the answer, or nil to cancel.
249    public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
250    /// Runs work outside the text, such as a table recalculation in Emacs.
251    public var onExternal: ((ExternalRequest) -> Void)?
252
253    public var keymap: Keymap {
254        get { dispatcher.keymap }
255        set {
256            dispatcher.keymap = newValue
257            dispatcher.reset()
258        }
259    }
260
261    public var optionAsMeta: OptionAsMeta = [.left]
262    /// Org options commands follow.
263    public var options: EditingOptions = .org {
264        didSet {
265            if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
266        }
267    }
268    /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
269    /// `options`). Hidden markup shows on the caret's line, so it can be edited.
270    public var showMarkup = true {
271        didSet { if showMarkup != oldValue { restyleEverything() } }
272    }
273    /// Line numbers in a ruler beside the text.
274    public var showLineNumbers = true {
275        didSet { orgTextView?.showsLineNumbers = showLineNumbers }
276    }
277    var orgTextView: OrgTextView? { textView as? OrgTextView }
278
279    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
280    private var revealedLine: NSRange?
281    var dispatcher: KeyDispatcher
282    /// Evil-style editing, for modal keymaps such as Doom's.
283    public var modal = false {
284        didSet {
285            guard modal != oldValue else { return }
286            vim = Vim()
287            dispatcher.mode = modal ? vim.mode.keymapMode : nil
288            dispatcher.reset()
289            updateCursor()
290        }
291    }
292    var vim = Vim()
293    /// The text and caret when insert state began, to know what was typed for `.`.
294    var insertSnapshot: (text: String, caret: Int)?
295    /// The evil cursor in visual states, where the selection's start isn't it.
296    var visualCaret: Int?
297    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
298    private(set) var markActive = false
299
300    private func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
301        let selected = textView.selectedRange()
302        return EditContext(
303            revision: document.revision, text: document.text, tree: document.tree,
304            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
305            hidden: hidden.all, options: options
306        )
307    }
308
309    /// Offers a key press to the keymap. False lets the text system have it.
310    func handleKey(_ event: NSEvent) -> Bool {
311        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
312        if modal { return handleModal(chord) }
313        switch dispatcher.feed(chord) {
314        case .pending(let keys):
315            let next = keymap.continuations(of: keys).map { item in
316                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
317            }
318            onKeysPending?(KeySequence.format(keys), next)
319            return true
320        case .cancelled:
321            onKeysPending?(nil, [])
322            onMessage?("Quit")
323            return true
324        case .undefined(let keys):
325            onKeysPending?(nil, [])
326            onMessage?("\(KeySequence.format(keys)) is undefined")
327            return true
328        case .unbound:
329            return false
330        case .complete(let keys, let candidates):
331            if keys.count > 1 { onKeysPending?(nil, []) }
332            let context = context()
333            let runnable = candidates.first { binding in
334                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
335            }
336            if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
337                run(binding.command)
338                return true
339            }
340            return false
341        }
342    }
343
344    private func applies(_ id: String, in context: EditContext) -> Bool {
345        if !isOrg, id.hasPrefix("org.") { return false }
346        return switch EditorCommands.command(id)?.action {
347        case .text(let command): command.applies(in: context)
348        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
349        case .edit, .mark, .app, .find: true
350        case nil: true
351        }
352    }
353
354    /// Runs a command by id, as a key, a menu item or the palette would.
355    public func run(_ id: String) {
356        guard let command = EditorCommands.command(id) else {
357            onMessage?("Unknown command \(id)")
358            return
359        }
360        if !isOrg, id.hasPrefix("org.") {
361            onMessage?("Not an org file")
362            return
363        }
364        var keepMark = false
365        switch command.action {
366        case .text(let text):
367            perform(text)
368        case .view:
369            if id == "org.cycle" { cycleAtCaret() } else { cycleGlobal() }
370        case .edit(let selector, let extending):
371            if markActive, let extending {
372                keepMark = true
373                textView.doCommand(by: NSSelectorFromString(extending))
374            } else {
375                textView.doCommand(by: NSSelectorFromString(selector))
376            }
377        case .find(let action):
378            let item = NSMenuItem()
379            item.tag = action.rawValue
380            textView.performTextFinderAction(item)
381        case .mark:
382            if id == "edit.set-mark" {
383                let caret = textView.selectedRange().location
384                textView.setSelectedRange(NSRange(location: caret, length: 0))
385                keepMark = true
386                onMessage?("Mark set")
387            } else {
388                let selected = textView.selectedRange()
389                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
390                onMessage?("Quit")
391            }
392        case .app:
393            onAppCommand?(id)
394        }
395        markActive = keepMark
396    }
397
398    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
399    /// they form one undo step and reach the document through the same path.
400    @discardableResult
401    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
402        let context = context(now: now, answers: answers)
403        let step = command.run(in: context)
404        switch step {
405        case .commit(let result):
406            guard textView.isEditable || result.edits.isEmpty else {
407                onMessage?("This file is read-only.")
408                return .failed("read-only")
409            }
410            applyEdits(result.edits)
411            if let selection = result.selection?.first {
412                setCaret(selection.lowerBound)
413                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
414            }
415            for case .message(let text) in result.effects { onMessage?(text) }
416        case .failed(let message):
417            onMessage?(message)
418        case .external(let request):
419            if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
420        case .prompt(let prompt):
421            onPrompt?(prompt) { [weak self] answer in
422                guard let self else { return }
423                guard let answer else {
424                    self.onMessage?("Quit")
425                    return
426                }
427                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
428            }
429        }
430        return step
431    }
432
433    // MARK: - Disk
434
435    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
436    /// its headings.
437    @discardableResult
438    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
439        update { $0.diskChanged(to: bytes) }
440    }
441
442    // MARK: - Folding
443
444    public var foldState: FoldState {
445        FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
446    }
447
448    private var globalVisibility: GlobalVisibility?
449
450    public func setFolds(_ state: FoldState) {
451        view.folds = state.folds
452        view.bodyFolds = state.bodyFolds
453        view = view.pruned(to: document.tree)
454        updateHidden()
455        orgTextView?.redrawLineNumbers()
456        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
457        textView.needsDisplay = true
458        let caret = textView.selectedRange().location
459        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
460    }
461
462    private func updateHidden() {
463        folded.set(view.folds.union(view.bodyFolds))
464        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
465    }
466
467    /// TAB on a heading: folded, children, subtree. Returns false off a heading.
468    @discardableResult
469    public func cycleAtCaret() -> Bool {
470        guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
471        setFolds(Presentation.cycle(heading, in: document.tree, foldState))
472        return true
473    }
474
475    /// Shift-TAB: overview, contents, show all.
476    public func cycleGlobal() {
477        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
478        globalVisibility = visibility
479        setFolds(state)
480    }
481
482    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
483    public func reveal(_ offset: Int) {
484        let target = max(0, min(offset, utf16Length))
485        unfold(around: target)
486        setCaret(target)
487        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
488    }
489
490    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
491    func unfold(around offset: Int) {
492        var state = foldState
493        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
494            state.folds.remove(entry.start)
495            state.bodyFolds.remove(entry.start)
496        }
497        guard state != foldState else { return }
498        setFolds(state)
499    }
500
501    /// Applies edits through the text view as one undo step, not merged with typing around it.
502    func applyEdits(_ edits: [TextEdit]) {
503        guard !edits.isEmpty, let storage = textView.textStorage else { return }
504        textView.breakUndoCoalescing()
505        textView.undoManager?.beginUndoGrouping()
506        for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
507            let range = NSRange(edit.range)
508            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
509            storage.replaceCharacters(in: range, with: edit.replacement)
510            textView.didChangeText()
511        }
512        textView.undoManager?.endUndoGrouping()
513        textView.breakUndoCoalescing()
514    }
515
516    func setCaret(_ offset: Int) {
517        let clamped = max(0, min(offset, utf16Length))
518        previousSelection = clamped
519        textView.setSelectedRange(NSRange(location: clamped, length: 0))
520    }
521
522    // MARK: - Styling
523
524    private func restyleOutsideEditing(_ range: Range<Int>) {
525        guard let storage = textView.textStorage else { return }
526        storage.beginEditing()
527        restyle(range, in: storage)
528        storage.endEditing()
529    }
530
531    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
532    /// attribute changes are allowed and characters must not change.
533    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
534        guard !range.isEmpty else { return }
535        let whole = NSRange(range)
536        storage.setAttributes(theme.base, range: whole)
537        guard isOrg else {
538            for run in plainRuns() where run.range.overlaps(range) {
539                guard let clipped = clip(run.range, to: range) else { continue }
540                theme.apply(.syntax(run.category), to: storage, range: clipped)
541            }
542            return
543        }
544        let text = storage.string as NSString
545        for run in Presentation.indents(document.tree, in: range) {
546            guard let clipped = clip(run.range, to: range) else { continue }
547            guard run.firstLine == run.wrapped else {
548                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
549                continue
550            }
551            // Body lines wrap under their own text: past leading blanks, and past a list bullet
552            // and checkbox, as adaptive-wrap does in Emacs.
553            var location = clipped.location
554            while location < NSMaxRange(clipped) {
555                let line = text.lineRange(for: NSRange(location: location, length: 0))
556                let hanging = Self.hangingColumns(text.substring(with: line))
557                let lineRange = NSIntersectionRange(line, clipped)
558                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
559                location = NSMaxRange(line)
560            }
561        }
562        let revealed = caretLine
563        var scriptExclusions: [Range<Int>] = []
564        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
565            guard let clipped = clip(run.range, to: range) else { continue }
566            if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
567                storage.addAttributes(theme.hidden, range: clipped)
568            } else {
569                theme.apply(run.role, to: storage, range: clipped)
570            }
571            switch run.role {
572            case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
573            default: break
574            }
575        }
576        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
577    }
578
579    /// `org-pretty-entities`: entities drawn as their character over the entity's last
580    /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
581    /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
582    /// keywords, as `org-raise-scripts` leaves them.
583    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
584        let text = storage.string as NSString
585        var location = range.lowerBound
586        while location < range.upperBound {
587            let line = text.lineRange(for: NSRange(location: location, length: 0))
588            guard line.length > 0 else { break }
589            location = NSMaxRange(line)
590            if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
591            let content = text.substring(with: line)
592            if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
593            for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
594                switch run {
595                case .entity(let r, let display):
596                    let start = line.location + r.lowerBound
597                    let last = line.location + r.upperBound - 1
598                    if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
599                    storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
600                case .script(let markers, let body, let superscript):
601                    let bodyStart = line.location + body.lowerBound
602                    if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
603                    for marker in markers {
604                        storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
605                    }
606                    let size = theme.font.pointSize
607                    storage.addAttributes([
608                        .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
609                        .baselineOffset: (superscript ? 0.3 : -0.3) * size,
610                    ], range: NSRange(location: bodyStart, length: body.count))
611                }
612            }
613        }
614    }
615
616    /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
617    /// markers only when Emacs hides them too.
618    private func hides(_ role: StyleRole) -> Bool {
619        switch role {
620        case .linkMarkup: true
621        case .markup: options.hideEmphasisMarkers
622        default: false
623        }
624    }
625
626    /// Moving to another line shows its markup and hides the last one's.
627    private func revealCaretLine() {
628        guard !showMarkup, isOrg else { return }
629        let line = caretLine
630        guard line != revealedLine else { return }
631        let text = textView.string as NSString
632        // The old line may have moved with edits since; restyle the line now at its start.
633        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
634        revealedLine = line
635        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
636            restyleOutsideEditing(range.location..<NSMaxRange(range))
637        }
638    }
639
640    /// Code highlights for the whole file in plain mode.
641    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
642        guard case .plain(let language?) = mode, let highlighter else { return [] }
643        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
644        let runs = highlighter.highlights(language: language, code: document.text)
645        codeRuns = (document.revision, runs)
646        return runs
647    }
648
649    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
650        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
651        if let style = paragraphStyles[key] { return style }
652        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
653        paragraphStyles[key] = style
654        return style
655    }
656
657    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
658        let clipped = run.clamped(to: range)
659        return clipped.isEmpty ? nil : NSRange(clipped)
660    }
661
662    /// The region an edit affects in one version of the tree: inside the innermost section
663    /// holding the edited lines (plus the line after), every element that overlaps them or the
664    /// line on either side. A changed heading line, or an added or removed heading, widens it
665    /// to that section's whole own body. Run on the old and the new tree, the union covers
666    /// elements that grew and elements that shrank.
667    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
668        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
669        let lineRange = lines.location..<(lines.location + lines.length)
670        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
671        var container = tree.root
672        while let child = container.child(containing: lineRange.lowerBound),
673              child.kind == .section || child.kind == .zerothSection,
674              lineRange.upperBound <= child.range.upperBound {
675            container = child
676        }
677        var lower = lineRange.lowerBound
678        var upper = lineRange.upperBound
679        // Tables and lists carry no styling of their own, so inside them only the rows or
680        // items around the edit change, however large they are.
681        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
682            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
683                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
684                let inner = overlapping(node.children(overlapping: around))
685                return inner.isEmpty ? [node] : inner
686            }
687        }
688        for child in overlapping(container.children(overlapping: around)) {
689            lower = min(lower, child.range.lowerBound)
690            upper = max(upper, child.range.upperBound)
691        }
692        let heading = container.firstChild(.heading)
693        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
694            lower = min(lower, container.range.lowerBound)
695            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
696        }
697        return lower..<min(upper, text.length)
698    }
699
700    // MARK: - Editing
701
702    fileprivate func storageEdited(range: NSRange, delta: Int) {
703        guard !isLoading, let storage = textView.textStorage else { return }
704        markActive = false
705        let clock = ContinuousClock()
706        let start = clock.now
707        let replacement = (storage.string as NSString).substring(with: range)
708        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
709        let oldText = document.text as NSString
710        let newText = storage.string as NSString
711        let newEnd = edit.range.lowerBound + replacement.utf16.count
712        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
713            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
714        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
715        do {
716            try document.apply([edit], baseRevision: document.revision)
717        } catch {
718            assertionFailure("text view and document disagree: \(error)")
719            return
720        }
721        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
722        // edited line when the edit reaches into unstyled text.
723        if styledUpTo >= edit.range.upperBound {
724            styledUpTo += edit.replacement.utf16.count - edit.range.count
725        } else if styledUpTo > edit.range.lowerBound {
726            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
727        }
728        let oldHidden = hidden.all
729        view = view.mapped(through: [edit]).pruned(to: document.tree)
730        folded.set(view.folds)
731        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
732        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
733        let delta = edit.replacement.utf16.count - edit.range.count
734        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
735        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
736        let oldShaded = shaded.all
737        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
738        if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
739            || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
740            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
741        }
742        onEditTiming?(clock.now - start)
743        if edit.replacement.contains("\n") || (oldText.substring(with: NSRange(edit.range)) as String).contains("\n") {
744            orgTextView?.updateGutter()
745        }
746        orgTextView?.redrawLineNumbers()
747        onChange?()
748    }
749
750    /// Columns a wrapped continuation of `line` should start past the line's own start.
751    nonisolated static func hangingColumns(_ line: String) -> Int {
752        var columns = 0
753        var rest = Substring(line)
754        while let c = rest.first, c == " " || c == "\t" {
755            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
756            rest = rest.dropFirst()
757        }
758        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
759        var bullet = 0
760        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
761            bullet = 1
762        } else {
763            let digits = rest.prefix { $0.isASCII && $0.isNumber }
764            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
765                bullet = digits.count + 1
766            }
767        }
768        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
769        columns += bullet + 1
770        let afterBullet = rest.dropFirst(bullet + 1)
771        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
772           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
773            columns += 4
774        }
775        return columns
776    }
777
778    /// Whether a heading line touches `start..<end` or starts right after it, where joining
779    /// lines could take it away.
780    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
781        let length = min(end + 1, text.length) - start
782        guard length >= 0 else { return false }
783        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
784        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
785            let stars = line.prefix { $0 == "*" }
786            let after = line.dropFirst(stars.count)
787            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
788        }
789    }
790
791    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
792        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
793        return mapped
794    }
795
796    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
797    /// back jumps to the end of the heading line.
798    fileprivate func selectionChanged() {
799        let selection = textView.selectedRange()
800        defer { previousSelection = selection.location }
801        onSelectionChange?(selection)
802        revealCaretLine()
803        orgTextView?.redrawLineNumbers()
804        // A selection reaching into folded text, as a find match does, unfolds it.
805        if selection.length > 0 {
806            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
807                unfold(around: selection.location)
808                unfold(around: NSMaxRange(selection) - 1)
809            }
810            return
811        }
812        guard let range = hidden.containing(selection.location) else { return }
813        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
814    }
815}
816
817extension OrgEditor: DocumentBuffer {
818    /// The selected text, for capture's `%i`.
819    public var selectedText: String {
820        let range = textView.selectedRange()
821        guard range.length > 0 else { return "" }
822        return (textView.string as NSString).substring(with: range)
823    }
824
825    public var selection: [Range<Int>] {
826        let selected = textView.selectedRange()
827        return [selected.location..<NSMaxRange(selected)]
828    }
829
830    /// Runs `change`; if it changed the text, reloads the view with folds and the selection
831    /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
832    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
833        let before = document.text
834        let selected = textView.selectedRange()
835        let result = try change(&document)
836        if document.text != before {
837            let edits = lineEdits(from: before, to: document.text)
838            var state = view
839            state.selection = [selected.location..<NSMaxRange(selected)]
840            let mapped = state.mapped(through: edits)
841            load(document.text)
842            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
843            let selection = mapped.selection[0]
844            setCaret(selection.lowerBound)
845            if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
846            textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
847            textView.undoManager?.removeAllActions(withTarget: textView)
848        }
849        onChange?()
850        return result
851    }
852}
853
854extension OrgEditor: NSTextViewDelegate {
855    public func textViewDidChangeSelection(_ notification: Notification) {
856        selectionChanged()
857    }
858}
859
860extension OrgEditor: NSTextStorageDelegate {
861    public nonisolated func textStorage(
862        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
863    ) {
864        guard editedMask.contains(.editedCharacters) else { return }
865        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
866    }
867}
868
869extension OrgEditor: NSTextContentStorageDelegate {
870    /// Folded text isn't enumerated, so it isn't laid out or drawn.
871    public nonisolated func textContentManager(
872        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
873    ) -> Bool {
874        guard let range = textElement.elementRange else { return true }
875        let documentStart = textContentManager.documentRange.location
876        let start = textContentManager.offset(from: documentStart, to: range.location)
877        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
878        return !hidden.covers(start, end)
879    }
880}
881
882extension OrgEditor: NSTextLayoutManagerDelegate {
883    public nonisolated func textLayoutManager(
884        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
885    ) -> NSTextLayoutFragment {
886        let range = textElement.elementRange
887        if let range, let manager = textLayoutManager.textContentManager {
888            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
889            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
890            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
891            if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
892                return EntityFragment(textElement: textElement, range: range)
893            }
894        }
895        return NSTextLayoutFragment(textElement: textElement, range: range)
896    }
897}
898
899/// A line of a block, on a band across the whole width of the view, as Emacs extends the
900/// `org-block` face.
901final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
902    private var band: CGRect {
903        let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
904        // Not under the empty line TextKit adds after a final newline.
905        let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
906        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
907    }
908
909    override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
910
911    override func draw(at point: CGPoint, in context: CGContext) {
912        context.saveGState()
913        context.setFillColor(Theme.blockBackground.cgColor)
914        context.fill(band.offsetBy(dx: point.x, dy: point.y))
915        context.restoreGState()
916        super.draw(at: point, in: context)
917    }
918}
919
920extension NSAttributedString.Key {
921    /// The character an entity shows as, on the entity's last character.
922    static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
923}
924
925/// A paragraph with pretty entities: each is drawn as its character where the entity's last
926/// (now invisible) character sits, so it takes one column as in Emacs.
927final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
928    static func hasEntities(_ string: NSAttributedString) -> Bool {
929        var found = false
930        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
931            if value != nil { found = true; stop.pointee = true }
932        }
933        return found
934    }
935
936    override func draw(at point: CGPoint, in context: CGContext) {
937        super.draw(at: point, in: context)
938        Self.drawEntities(of: self, at: point, in: context)
939    }
940
941    static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
942        guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
943        NSGraphicsContext.saveGraphicsState()
944        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
945        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
946            guard let display = value as? String,
947                  let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
948            var attributes = string.attributes(at: range.location, effectiveRange: nil)
949            attributes[.foregroundColor] = NSColor.textColor
950            attributes[.orgEntityDisplay] = nil
951            let x = line.locationForCharacter(at: range.location).x
952            let bounds = line.typographicBounds
953            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
954        }
955        NSGraphicsContext.restoreGraphicsState()
956    }
957}
958
959/// A heading line drawn with an ellipsis after it, like org's folded headings.
960final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
961    override func draw(at point: CGPoint, in context: CGContext) {
962        super.draw(at: point, in: context)
963        EntityFragment.drawEntities(of: self, at: point, in: context)
964        guard let line = textLineFragments.first else { return }
965        let bounds = line.typographicBounds
966        let ellipsis = NSAttributedString(string: " …", attributes: [
967            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
968            .foregroundColor: NSColor.secondaryLabelColor,
969        ])
970        NSGraphicsContext.saveGraphicsState()
971        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
972        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
973        NSGraphicsContext.restoreGraphicsState()
974    }
975
976    override var renderingSurfaceBounds: CGRect {
977        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
978    }
979}
980#endif