Sources/OrgEditorAppKit/OrgEditor.swift

8c221170c5ed1f01bcb7cabccac77177aa399d9a
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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