Sources/OrgEditorAppKit/OrgEditor.swift

1566 lines · 77388 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    var all: Set<Int> {
  43        lock.withLock { starts }
  44    }
  45}
  46
  47/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
  48/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
  49@MainActor
  50public final class OrgEditor: NSObject {
  51    public let textView: NSTextView
  52    public private(set) var document: DocumentState
  53    public private(set) var view = ViewState()
  54    /// Called with the time from a character edit to restyled text.
  55    public var onEditTiming: ((Duration) -> Void)?
  56
  57    let hidden = HiddenRanges()
  58    let folded = FoldedHeadings()
  59    /// Where lines start, for line numbers.
  60    let lines = LineIndex()
  61    /// Blocks drawn on a shaded band.
  62    let shaded = HiddenRanges()
  63    private(set) var theme = Theme()
  64    /// Colors and type; a change restyles the file.
  65    public var themeSpec: ThemeSpec = .default {
  66        didSet {
  67            guard themeSpec != oldValue else { return }
  68            theme = Theme(themeSpec)
  69            keepingTopLine {
  70                applyThemeToView()
  71                restyleEverything()
  72                textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
  73            }
  74        }
  75    }
  76    private var isLoading = false
  77    private var previousSelection = 0
  78    /// The selection shaded block lines last drew.
  79    private var previousSelectionRange = NSRange(location: 0, length: 0)
  80    /// Text before this offset is styled; after it, only base attributes until the background
  81    /// passes reach it. Always at a line start.
  82    private(set) var styledUpTo = 0
  83    private var stylingScheduled = false
  84    /// One paragraph style object per indent pair, shared by every line that uses it.
  85    private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
  86
  87    private struct IndentKey: Hashable {
  88        let firstLine: Int
  89        let wrapped: Int
  90    }
  91
  92    /// Styled before the first render: more than a screenful.
  93    static let firstStyleChunk = 30_000
  94    /// Styled per run-loop turn afterwards.
  95    static let styleChunk = 200_000
  96
  97    /// Highlights code in src blocks; nil leaves code plain.
  98    public let highlighter: (any CodeHighlighter)?
  99
 100    /// What the file is: org, or plain text, highlighted as code when the language is known.
 101    public enum Mode: Equatable, Sendable {
 102        case org
 103        case plain(language: String?)
 104    }
 105
 106    public let mode: Mode
 107    public var isOrg: Bool { mode == .org }
 108    /// The text as shown for accessibility, and the storage generation it's for.
 109    var accessibleCache: (storage: Int, text: AccessibleText)?
 110    /// Bumped on every character or attribute change to the storage.
 111    var storageGeneration = 0
 112    /// The open completion list, and the pause before one opens by itself.
 113    var completionPopup: CompletionPopup?
 114    var completionTimer: DispatchWorkItem?
 115    /// The spell checker's skipped ranges and the text they were found in.
 116    var spellSkipCache: (text: String, ranges: [Range<Int>])?
 117    /// Highlights of the whole file in plain mode, and the revision they were made for.
 118    private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
 119
 120    public init(
 121        document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
 122        highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
 123    ) {
 124        self.document = document
 125        self.options = options
 126        self.highlighter = highlighter
 127        self.mode = mode
 128        let orgTextView = OrgTextView(usingTextLayoutManager: true)
 129        textView = orgTextView
 130        dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
 131        super.init()
 132        orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
 133        orgTextView.onFocusChange = { [weak self] in
 134            guard let self else { return }
 135            let id = ObjectIdentifier(self.textLayoutManager)
 136            if let window = self.textView.window, window.isKeyWindow, window.firstResponder === self.textView {
 137                Theme.focusedLayouts.insert(id)
 138            } else {
 139                Theme.focusedLayouts.remove(id)
 140            }
 141            self.redrawShaded([self.textView.selectedRange()])
 142        }
 143        orgTextView.onCommandClick = { [weak self] offset in
 144            guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
 145                || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
 146            self.setCaret(offset)
 147            self.run("org.link.open")
 148            return true
 149        }
 150        orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false }
 151        orgTextView.accessibleText = { [weak self] in
 152            guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
 153            if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
 154            let text = AccessibleText(storage)
 155            self.accessibleCache = (self.storageGeneration, text)
 156            return text
 157        }
 158        orgTextView.onMouseDown = { [weak self] in
 159            self?.markActive = false
 160            self?.modalMouseDown()
 161        }
 162        textView.usesFindBar = true
 163        textView.frame = frame
 164        textView.isRichText = false
 165        textView.isEditable = editable
 166        textView.allowsUndo = true
 167        textView.isAutomaticQuoteSubstitutionEnabled = false
 168        textView.isAutomaticDashSubstitutionEnabled = false
 169        textView.isAutomaticTextReplacementEnabled = false
 170        textView.isAutomaticSpellingCorrectionEnabled = false
 171        applyThemeToView()
 172        textView.isVerticallyResizable = true
 173        textView.autoresizingMask = [.width]
 174        textView.textContainer?.widthTracksTextView = true
 175        textView.delegate = self
 176        textView.textStorage?.delegate = self
 177        textLayoutManager.delegate = self
 178        textContentStorage.delegate = self
 179
 180        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
 181        load(document.text)
 182        // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
 183        textView.setSelectedRange(NSRange(location: 0, length: 0))
 184        if isOrg {
 185            let startup = Presentation.startupDisplay(document.tree, options: options)
 186            indented = startup.indented
 187            hideStars = startup.hideStars
 188            if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) }
 189            shrunk = ShrunkColumns.startup(document.tree)
 190            if startup.inlineImages { showsImages = true }
 191            if startup.alignTables { _ = perform(AlignAllTables()) }
 192            if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
 193        }
 194        spellChecking = options.spellCheck
 195        truncatesLines = options.startupTruncated
 196    }
 197
 198    /// Replaces the storage's text. Setting the attributed string directly is about 100x
 199    /// faster than `NSTextView.string` for large files.
 200    private func load(_ text: String) {
 201        isLoading = true
 202        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
 203        isLoading = false
 204        lines.reset(text as NSString)
 205        orgTextView?.lineIndex = lines
 206        orgTextView?.updateGutter()
 207        styledUpTo = 0
 208        styleNextChunk(Self.firstStyleChunk)
 209        scheduleStyling()
 210    }
 211
 212    // MARK: - Initial styling
 213
 214    /// Styles whole lines from the watermark onward, about `size` units.
 215    private func styleNextChunk(_ size: Int) {
 216        let text = textView.textStorage!.string as NSString
 217        guard styledUpTo < text.length else { return }
 218        let target = min(text.length, styledUpTo + size)
 219        let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
 220        restyleOutsideEditing(styledUpTo..<end)
 221        styledUpTo = end
 222    }
 223
 224    /// The text view's own colors and font, and the line numbers'.
 225    private func applyThemeToView() {
 226        textView.font = theme.font
 227        textView.typingAttributes = theme.base
 228        textView.drawsBackground = true
 229        textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
 230        textView.insertionPointColor = theme.color("cursor") ?? .textColor
 231        Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
 232        textView.selectedTextAttributes = [.backgroundColor: Theme.selection]
 233        if let view = orgTextView {
 234            view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
 235            view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
 236            view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
 237            view.updateGutter()
 238            view.needsDisplay = true
 239        }
 240    }
 241
 242    /// Styles the whole file again, a screenful now and the rest in the background.
 243    private func restyleEverything() {
 244        styledUpTo = 0
 245        revealedLine = caretLine
 246        styleNextChunk(Self.firstStyleChunk)
 247        scheduleStyling()
 248    }
 249
 250    private var caretLine: NSRange {
 251        let text = textView.string as NSString
 252        return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
 253    }
 254
 255    private func scheduleStyling() {
 256        guard !stylingScheduled, styledUpTo < utf16Length else { return }
 257        stylingScheduled = true
 258        DispatchQueue.main.async { [weak self] in
 259            guard let self else { return }
 260            self.stylingScheduled = false
 261            self.styleNextChunk(Self.styleChunk)
 262            self.scheduleStyling()
 263        }
 264    }
 265
 266    /// Styles everything still waiting for a background pass.
 267    public func finishStyling() {
 268        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
 269    }
 270
 271    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
 272    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
 273    var utf16Length: Int { (textView.string as NSString).length }
 274
 275    /// A scroll view holding the text view, ready for a window.
 276    public func makeScrollView() -> NSScrollView {
 277        let scroll = NSScrollView(frame: textView.frame)
 278        scroll.hasVerticalScroller = true
 279        scroll.documentView = textView
 280        orgTextView?.showsLineNumbers = showLineNumbers
 281        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
 282        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
 283        return scroll
 284    }
 285
 286    // MARK: - Saving
 287
 288    /// Saves through `saver`. A merge that changes the buffer reloads the text view.
 289    @discardableResult
 290    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
 291        try update { try saver.save(&$0, to: url) }
 292    }
 293
 294    /// Called after every change to the document, typed or not.
 295    public var onChange: (() -> Void)?
 296
 297    // MARK: - Commands
 298
 299    /// Called with messages commands report, such as why one couldn't run here.
 300    public var onMessage: ((String) -> Void)?
 301    /// Called with the pending prefix and what can follow it, and with nil when it ends.
 302    /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
 303    public var onModeChange: ((String?) -> Void)?
 304    /// The selection moved.
 305    public var onSelectionChange: ((NSRange) -> Void)?
 306    var reportedMode: String?
 307    public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
 308    /// Called with `app.*` commands, which the app carries out.
 309    public var onAppCommand: ((String) -> Void)?
 310    /// `:e FILE`: the path as typed, for the app to open.
 311    public var onOpenFile: ((String) -> Void)?
 312    /// Called when a command asks a question; reply with the answer, or nil to cancel.
 313    public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
 314    /// Runs work outside the text, such as a table recalculation in Emacs.
 315    public var onExternal: ((ExternalRequest) -> Void)?
 316    /// Tags used across the workspace, for tag completion.
 317    public var knownTags: @Sendable () -> [String] = { [] }
 318    /// Effects other than messages, for the app to carry out.
 319    public var onEffect: ((Effect) -> Void)?
 320
 321    public var keymap: Keymap {
 322        get { dispatcher.keymap }
 323        set {
 324            dispatcher.keymap = newValue
 325            dispatcher.reset()
 326        }
 327    }
 328
 329    public var optionAsMeta: OptionAsMeta = [.left]
 330    /// Org options commands follow.
 331    public var options: EditingOptions = .org {
 332        didSet {
 333            if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
 334        }
 335    }
 336    /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
 337    /// `options`). Hidden markup shows on the caret's line, so it can be edited.
 338    public var showMarkup = true {
 339        didSet { if showMarkup != oldValue { restyleEverything() } }
 340    }
 341    /// Line numbers in a ruler beside the text.
 342    public var showLineNumbers = true {
 343        didSet { orgTextView?.showsLineNumbers = showLineNumbers }
 344    }
 345    var orgTextView: OrgTextView? { textView as? OrgTextView }
 346
 347    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
 348    private var revealedLine: NSRange?
 349    var dispatcher: KeyDispatcher
 350    /// Evil-style editing, for modal keymaps such as Doom's.
 351    public var modal = false {
 352        didSet {
 353            guard modal != oldValue else { return }
 354            vim = Vim()
 355            dispatcher.mode = modal ? vim.mode.keymapMode : nil
 356            dispatcher.reset()
 357            updateCursor()
 358        }
 359    }
 360    var vim = Vim()
 361    /// The text and caret when insert state began, to know what was typed for `.`.
 362    var insertSnapshot: (text: String, caret: Int)?
 363    /// The evil cursor in visual states, where the selection's start isn't it.
 364    var visualCaret: Int?
 365    /// Vim's lowercase marks, mapped through edits.
 366    var vimMarks: [Character: Int] = [:]
 367    /// Uppercase marks, with the editor each is in: global, as evil's file marks are.
 368    static var fileMarks: [Character: (owner: WeakEditor, offset: Int)] = [:]
 369    /// Registers and keyboard macros, shared by every editor as evil's are global.
 370    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 371    static var vimClipboardRecord: (text: String, linewise: Bool)?
 372    static var macros: [Character: [KeyChord]] = [:]
 373    /// Shows `editor`'s buffer with the caret at the offset, for a jump to a file mark set
 374    /// there.
 375    public var onJumpToEditor: ((OrgEditor, Int) -> Void)?
 376    /// Jump positions, oldest first, mapped through edits; `jumpIndex` is where C-o and C-i are.
 377    var jumpList: [Int] = []
 378    var jumpIndex = 0
 379    /// The register keys go into while `q` records, and its keys so far.
 380    var recordingRegister: Character?
 381    var recordedKeys: [KeyChord] = []
 382    var replayingMacro = 0
 383    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
 384    private(set) var markActive = false
 385
 386    public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
 387        let selected = textView.selectedRange()
 388        return EditContext(
 389            revision: document.revision, text: document.text, tree: document.tree,
 390            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
 391            hidden: hidden.all, options: options, knownTags: knownTags,
 392            lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
 393        )
 394    }
 395
 396    /// Offers a key press to the keymap. False lets the text system have it.
 397    func handleKey(_ event: NSEvent) -> Bool {
 398        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
 399        if let handled = completionKey(chord) { return handled }
 400        if modal { return handleModal(chord) }
 401        switch dispatcher.feed(chord) {
 402        case .pending(let keys):
 403            let context = context()
 404            let next = keymap.continuations(of: keys) { runs($0, in: context) }.map { item in
 405                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
 406            }
 407            onKeysPending?(KeySequence.format(keys), next)
 408            return true
 409        case .cancelled:
 410            onKeysPending?(nil, [])
 411            onMessage?("Quit")
 412            return true
 413        case .undefined(let keys):
 414            onKeysPending?(nil, [])
 415            onMessage?("\(KeySequence.format(keys)) is undefined")
 416            return true
 417        case .unbound:
 418            return electricPair(chord)
 419        case .complete(let keys, let candidates):
 420            if keys.count > 1 { onKeysPending?(nil, []) }
 421            let context = context()
 422            let runnable = candidates.first { runs($0, in: context) }
 423            if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
 424                run(binding.command)
 425                return true
 426            }
 427            return keys.count == 1 && electricPair(chord)
 428        }
 429    }
 430
 431    /// `electric-pair-mode` for a key the keymap leaves to the text system: true when it
 432    /// typed the key itself.
 433    func electricPair(_ key: KeyChord) -> Bool {
 434        guard isOrg, options.electricPair, key.modifiers.isEmpty, !textView.hasMarkedText(),
 435              key.key == "DEL" || key.key == "RET" || ElectricPairKey.characters.contains(key.key) else { return false }
 436        let command = ElectricPairKey(key: key.key)
 437        guard command.applies(in: context()) else { return false }
 438        _ = perform(command)
 439        return true
 440    }
 441
 442    /// Whether a key's `binding` runs in `context`: its context holds and its command applies.
 443    private func runs(_ binding: KeyBinding, in context: EditContext) -> Bool {
 444        (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
 445    }
 446
 447    private func applies(_ id: String, in context: EditContext) -> Bool {
 448        if !isOrg, id.hasPrefix("org.") { return false }
 449        return switch EditorCommands.command(id)?.action {
 450        case .text(let command): command.applies(in: context)
 451        case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
 452        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
 453            || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
 454        case .edit, .mark, .app, .find: true
 455        case nil: true
 456        }
 457    }
 458
 459    /// The last command run and the revision it left, for `last-command`.
 460    private var lastCommand: (id: String, revision: Int)?
 461
 462    /// Runs a command by id, as a key, a menu item or the palette would.
 463    public func run(_ id: String) {
 464        defer { lastCommand = (id, document.revision) }
 465        guard let command = EditorCommands.command(id) else {
 466            onMessage?("Unknown command \(id)")
 467            return
 468        }
 469        if !isOrg, id.hasPrefix("org.") {
 470            onMessage?("Not an org file")
 471            return
 472        }
 473        // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
 474        if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
 475            clearHighlights()
 476            return
 477        }
 478        var keepMark = false
 479        switch command.action {
 480        case .text(let text):
 481            perform(text)
 482        case .view:
 483            switch id {
 484            case "org.cycle": cycleAtCaret()
 485            case "org.cycle-global": cycleGlobal()
 486            case "org.fold.toggle", "org.fold.open", "org.fold.close": fold(id)
 487            case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
 488            case "org.toggle-inline-images": toggleImages()
 489            case "editor.toggle-spell-check": toggleSpellCheck()
 490            case "editor.complete": completeAtPoint()
 491            case "editor.toggle-truncate-lines": toggleTruncateLines()
 492            default: tableColumnWidth(id)
 493            }
 494        case .edit(let selector, let extending):
 495            if markActive, let extending {
 496                keepMark = true
 497                textView.doCommand(by: NSSelectorFromString(extending))
 498            } else {
 499                textView.doCommand(by: NSSelectorFromString(selector))
 500            }
 501        case .find(let action):
 502            let item = NSMenuItem()
 503            item.tag = action.rawValue
 504            textView.performTextFinderAction(item)
 505        case .mark:
 506            if id == "edit.set-mark" {
 507                let caret = textView.selectedRange().location
 508                textView.setSelectedRange(NSRange(location: caret, length: 0))
 509                keepMark = true
 510                onMessage?("Mark set")
 511            } else {
 512                let selected = textView.selectedRange()
 513                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
 514                onMessage?("Quit")
 515            }
 516        case .app:
 517            onAppCommand?(id)
 518        }
 519        markActive = keepMark
 520    }
 521
 522    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
 523    /// they form one undo step and reach the document through the same path.
 524    @discardableResult
 525    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
 526        let context = context(now: now, answers: answers)
 527        let step = command.run(in: context)
 528        switch step {
 529        case .commit(let result):
 530            guard textView.isEditable || result.edits.isEmpty else {
 531                onMessage?("This file is read-only.")
 532                return .failed("read-only")
 533            }
 534            commandEditing = true
 535            applyEdits(result.edits)
 536            commandEditing = false
 537            if let selection = result.selection?.first {
 538                if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
 539                setCaret(selection.lowerBound)
 540                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
 541            }
 542            for effect in result.effects {
 543                switch effect {
 544                case .message(let text): onMessage?(text)
 545                case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
 546                case .fold(let start):
 547                    var state = foldState
 548                    state.folds.insert(start)
 549                    setFolds(state)
 550                default: onEffect?(effect)
 551                }
 552            }
 553        case .failed(let message):
 554            onMessage?(message)
 555        case .external(let request):
 556            if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
 557        case .prompt(let prompt):
 558            onPrompt?(prompt) { [weak self] answer in
 559                guard let self else { return }
 560                guard let answer else {
 561                    self.onMessage?("Quit")
 562                    return
 563                }
 564                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
 565            }
 566        }
 567        return step
 568    }
 569
 570    // MARK: - Disk
 571
 572    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
 573    /// its headings.
 574    @discardableResult
 575    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
 576        update { $0.diskChanged(to: bytes) }
 577    }
 578
 579    // MARK: - Folding
 580
 581    public var foldState: FoldState {
 582        FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
 583    }
 584
 585    private var globalVisibility: GlobalVisibility?
 586
 587    public func setFolds(_ state: FoldState) {
 588        setFolds(state, wrappers: nil)
 589    }
 590
 591    /// `wrappers`, when given, holds every folded drawer and block.
 592    private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
 593        sparseHidden = nil
 594        view.folds = state.folds
 595        view.bodyFolds = state.bodyFolds
 596        view = view.pruned(to: document.tree, wrappers: false)
 597        // Found one by one, or all at once when there are many.
 598        let found = wrappers ?? (state.wrapperFolds.count > 32
 599            ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
 600            : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
 601        wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
 602        view.wrapperFolds = Set(wrapperHidden.keys)
 603        updateHiddenAndLayout()
 604        orgTextView?.redrawLineNumbers()
 605        textView.needsDisplay = true
 606        let caret = textView.selectedRange().location
 607        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
 608    }
 609
 610    /// What each folded drawer and block hides, by opening-line start; kept in step with
 611    /// `view.wrapperFolds` and mapped through edits.
 612    private var wrapperHidden: [Int: Range<Int>] = [:]
 613
 614    private func updateHidden() {
 615        if let sparseHidden {
 616            let ns = textView.string as NSString
 617            // Headings whose next line is hidden show the fold ellipsis.
 618            let headings = Presentation.outline(document.tree).map(\.start).filter { start in
 619                let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
 620                return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
 621            }
 622            folded.set(Set(headings).union(view.wrapperFolds))
 623            hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
 624            return
 625        }
 626        folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
 627        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
 628    }
 629
 630    /// `updateHidden`, laying out again only the text that changed between hidden and shown
 631    /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit
 632    /// estimate the height of everything above the window afresh, which moves the text under it.
 633    private func updateHiddenAndLayout() {
 634        let oldHidden = hidden.all
 635        let oldFolded = folded.all
 636        updateHidden()
 637        invalidateLayout(from: oldHidden, to: hidden.all)
 638        invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 })
 639    }
 640
 641    /// Lays out again the ranges in `old` and not in `new`, and the other way round.
 642    private func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) {
 643        invalidateLayout(lines: Array(Set(old).symmetricDifference(new)))
 644    }
 645
 646    /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
 647    /// heading or opening line of a fold, whose fragment draws the fold mark.
 648    private func invalidateLayout(lines ranges: [Range<Int>]) {
 649        guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return }
 650        let text = textView.string as NSString
 651        for range in ranges {
 652            let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
 653            let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
 654            guard let start = content.location(content.documentRange.location, offsetBy: lower),
 655                  let end = content.location(start, offsetBy: upper - lower),
 656                  let textRange = NSTextRange(location: start, end: end) else { continue }
 657            textLayoutManager.invalidateLayout(for: textRange)
 658        }
 659    }
 660
 661    /// Runs `change`, which lays the whole file out again, and brings the line that was at the
 662    /// top of the window back there. TextKit estimates the height of text it hasn't laid out,
 663    /// so the same scroll position lands on different text after a fresh layout.
 664    func keepingTopLine(_ change: () -> Void) {
 665        guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() }
 666        let visible = scroll.documentVisibleRect
 667        let top = visible.minY - textView.textContainerOrigin.y
 668        let start = content.documentRange.location
 669        let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
 670            (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
 671        }
 672        change()
 673        guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
 674              let above = NSTextRange(location: start, end: location) else { return }
 675        // Styled now, not in the background passes, which would lay the text out again.
 676        while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) }
 677        textLayoutManager.ensureLayout(for: above)
 678        guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return }
 679        let frame = fragment.layoutFragmentFrame
 680        let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height))
 681        textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height))
 682        // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
 683        let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height
 684        if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) }
 685        textView.scroll(NSPoint(x: visible.minX, y: y))
 686        scroll.reflectScrolledClipView(scroll.contentView)
 687    }
 688
 689    // MARK: - Sparse trees
 690
 691    /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
 692    /// fold change. Mapped through edits.
 693    private var sparseHidden: [Range<Int>]?
 694    /// Sparse tree matches, highlighted until the next edit or C-c C-c.
 695    private var highlights: [Range<Int>] = []
 696
 697    private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
 698        let text = textView.string
 699        var state = foldState
 700        for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
 701            state.wrapperFolds.remove(start)
 702        }
 703        sparseHidden = nil
 704        setFolds(state)
 705        sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
 706        self.highlights = highlights
 707        keepingTopLine {
 708            updateHiddenAndLayout()
 709            restyleOutsideEditing(0..<utf16Length)
 710        }
 711        orgTextView?.redrawLineNumbers()
 712        textView.needsDisplay = true
 713        let caret = textView.selectedRange().location
 714        if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
 715    }
 716
 717    /// Leaves a sparse tree for ordinary folds: headings with something shown below them
 718    /// open, the others folded.
 719    private func leaveSparseTree() {
 720        guard let sparse = sparseHidden else { return }
 721        sparseHidden = nil
 722        let outline = Presentation.outline(document.tree)
 723        let ns = textView.string as NSString
 724        var open: Set<Int> = []
 725        for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
 726            var parent = entry.parent
 727            while let p = parent {
 728                open.insert(outline[p].start)
 729                parent = outline[p].parent
 730            }
 731            let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
 732            if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
 733        }
 734        var state = foldState
 735        state.folds = Set(outline.map(\.start)).subtracting(open)
 736        state.bodyFolds = []
 737        setFolds(state)
 738    }
 739
 740    private func clearHighlights() {
 741        guard !highlights.isEmpty else { return }
 742        let old = highlights
 743        highlights = []
 744        for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
 745    }
 746
 747    private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
 748        for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
 749            storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
 750        }
 751    }
 752
 753    // MARK: - STARTUP display
 754
 755    /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
 756    private var indented = true
 757    /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
 758    private var hideStars = false
 759
 760    // MARK: - Inline images
 761
 762    /// `org-toggle-inline-images`: lines that are only an image link show the image.
 763    public private(set) var showsImages = false
 764    /// The file's folder, for relative image paths.
 765    public var baseDirectory: URL? {
 766        didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
 767    }
 768    private static let imageCache = NSCache<NSString, NSImage>()
 769
 770    private func toggleImages() {
 771        showsImages.toggle()
 772        refreshImages()
 773        if showsImages {
 774            let ns = textView.string as NSString
 775            var count = 0
 776            var offset = 0
 777            while offset < ns.length {
 778                let line = ns.lineRange(for: NSRange(location: offset, length: 0))
 779                if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
 780                offset = NSMaxRange(line)
 781            }
 782            onMessage?("\(count) images displayed inline")
 783        } else {
 784            onMessage?("Inline image display turned off")
 785        }
 786    }
 787
 788    private func refreshImages() {
 789        keepingTopLine {
 790            restyleOutsideEditing(0..<utf16Length)
 791            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
 792        }
 793        textView.needsDisplay = true
 794    }
 795
 796    private func loadImage(_ path: String) -> NSImage? {
 797        let expanded = (path as NSString).expandingTildeInPath
 798        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
 799        let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
 800        let key = "\(url.path)|\(modified)" as NSString
 801        if let cached = Self.imageCache.object(forKey: key) { return cached }
 802        guard let image = NSImage(contentsOf: url) else { return nil }
 803        Self.imageCache.setObject(image, forKey: key)
 804        return image
 805    }
 806
 807    /// Image lines in `range` show the image over the link, which is hidden unless the caret is
 808    /// on the line.
 809    private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
 810        guard showsImages, isOrg else { return }
 811        let text = storage.string as NSString
 812        let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
 813        var location = range.lowerBound
 814        while location < range.upperBound, location < text.length {
 815            let line = text.lineRange(for: NSRange(location: location, length: 0))
 816            location = NSMaxRange(line)
 817            guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
 818            var width = image.width.map(CGFloat.init) ?? picture.size.width
 819            width = min(width, maxWidth)
 820            let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
 821            let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
 822            // Invisible, keeping the line's height, so line numbers stay apart.
 823            if line.location != revealed.location, content.length > 0 {
 824                storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
 825            }
 826            storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
 827            let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
 828            // The image sits where the line is; the spacing makes room for the rest of it.
 829            style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
 830            storage.addAttribute(.paragraphStyle, value: style, range: line)
 831        }
 832    }
 833
 834    // MARK: - Narrowing
 835
 836    /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
 837    /// rest is hidden until `widen`. Mapped through edits.
 838    public private(set) var narrowed: Range<Int>?
 839
 840    private func narrow(_ id: String) {
 841        let caret = textView.selectedRange().location
 842        do {
 843            switch id {
 844            case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
 845            // `org-toggle-narrow-to-subtree`.
 846            case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
 847            case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
 848            default: narrowed = nil
 849            }
 850        } catch let failure as Narrowing.Failure {
 851            onMessage?(failure.message)
 852            return
 853        } catch {
 854            return
 855        }
 856        updateHiddenAndLayout()
 857        orgTextView?.redrawLineNumbers()
 858        textView.needsDisplay = true
 859        if let narrowed {
 860            setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
 861            textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
 862        } else {
 863            textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
 864        }
 865    }
 866
 867    /// What narrowing hides: the text before the region, and the lines after it.
 868    private var narrowHidden: [Range<Int>] {
 869        guard let narrowed else { return [] }
 870        let length = utf16Length
 871        var ranges: [Range<Int>] = []
 872        if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
 873        let ns = textView.string as NSString
 874        let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
 875        if tail < length { ranges.append(tail..<length) }
 876        return ranges
 877    }
 878
 879    // MARK: - Shrunk table columns
 880
 881    /// Narrowed table columns (`org-table-shrink`).
 882    private var shrunk = ShrunkColumns()
 883    private var commandEditing = false
 884
 885    /// Narrows `columns` of `table` and widens its others.
 886    private func setShrunk(_ columns: [Int], in table: Range<Int>) {
 887        shrunk.set(columns, in: table, text: textView.string)
 888        restyleOutsideEditing(table)
 889        invalidateLayout(lines: [table])
 890        textView.needsDisplay = true
 891    }
 892
 893    /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
 894    /// `expand` for `org-table-expand`.
 895    private func tableColumnWidth(_ id: String) {
 896        switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) {
 897        case .notInTable: onMessage?("Not in a table")
 898        case .set(let columns, let table): setShrunk(columns, in: table)
 899        case .ask(let table, let current, let max):
 900            onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
 901                guard let self, let answer else { return }
 902                self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
 903            }
 904        }
 905    }
 906
 907    /// Hides each shrunk segment's text and draws its display where the text was.
 908    private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
 909        guard !shrunk.isEmpty else { return }
 910        let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
 911        for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
 912            let r = segment.range
 913            let shown = segment.display.count
 914            let kept = min(shown, r.count)
 915            if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
 916            guard kept > 0 else { continue }
 917            let visible = NSRange(location: r.upperBound - kept, length: kept)
 918            storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
 919            storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
 920            if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
 921        }
 922    }
 923
 924    /// Moves drawer and block folds through `edit`, checking again only those near it.
 925    private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
 926        guard !wrapperHidden.isEmpty else { return }
 927        var mapped: [Int: Range<Int>] = [:]
 928        let entries = Array(wrapperHidden)
 929        // One pass maps every start and range.
 930        let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
 931        for i in entries.indices {
 932            let newStart = moved[2 * i].lowerBound
 933            let newRange = moved[2 * i + 1]
 934            if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
 935                if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
 936            } else {
 937                mapped[newStart] = newRange
 938            }
 939        }
 940        wrapperHidden = mapped
 941        view.wrapperFolds = Set(mapped.keys)
 942    }
 943
 944    /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
 945    /// cycles folded, children, subtree. Returns false elsewhere.
 946    @discardableResult
 947    public func cycleAtCaret() -> Bool {
 948        leaveSparseTree()
 949        let caret = textView.selectedRange().location
 950        guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
 951        setFolds(state)
 952        // Off a closing line that folding hid, to the opening line, as org does.
 953        if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
 954        return true
 955    }
 956
 957    /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree).
 958    func fold(_ id: String) {
 959        leaveSparseTree()
 960        let caret = textView.selectedRange().location
 961        let tree = document.tree
 962        let next: FoldState?
 963        if id == "org.fold.close" {
 964            next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) }
 965                .map { Presentation.hideSubtree($0.start, foldState) }
 966        } else {
 967            next = Presentation.heading(containing: caret, in: tree).map {
 968                id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState)
 969            }
 970        }
 971        if let next, next != foldState { setFolds(next) }
 972    }
 973
 974    /// Shift-TAB: overview, contents, show all.
 975    public func cycleGlobal() {
 976        leaveSparseTree()
 977        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
 978        globalVisibility = visibility
 979        setFolds(state)
 980    }
 981
 982    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
 983    public func reveal(_ offset: Int) {
 984        let target = max(0, min(offset, utf16Length))
 985        if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
 986        unfold(around: target)
 987        setCaret(target)
 988        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
 989    }
 990
 991    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
 992    func unfold(around offset: Int) {
 993        leaveSparseTree()
 994        var state = foldState
 995        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
 996            state.folds.remove(entry.start)
 997            state.bodyFolds.remove(entry.start)
 998        }
 999        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
1000            state.wrapperFolds.remove(start)
1001        }
1002        guard state != foldState else { return }
1003        setFolds(state)
1004    }
1005
1006    /// Applies edits through the text view as one undo step, not merged with typing around it.
1007    func applyEdits(_ edits: [TextEdit]) {
1008        guard !edits.isEmpty, let storage = textView.textStorage else { return }
1009        textView.breakUndoCoalescing()
1010        textView.undoManager?.beginUndoGrouping()
1011        // By lines, so a fold between two changes stays.
1012        let text = storage.string
1013        for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
1014            let range = NSRange(edit.range)
1015            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
1016            storage.replaceCharacters(in: range, with: edit.replacement)
1017            textView.didChangeText()
1018        }
1019        textView.undoManager?.endUndoGrouping()
1020        textView.breakUndoCoalescing()
1021    }
1022
1023    func setCaret(_ offset: Int) {
1024        let clamped = max(0, min(offset, utf16Length))
1025        previousSelection = clamped
1026        textView.setSelectedRange(NSRange(location: clamped, length: 0))
1027    }
1028
1029    // MARK: - Styling
1030
1031    private func restyleOutsideEditing(_ range: Range<Int>) {
1032        guard let storage = textView.textStorage else { return }
1033        storage.beginEditing()
1034        restyle(range, in: storage)
1035        storage.endEditing()
1036    }
1037
1038    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
1039    /// attribute changes are allowed and characters must not change.
1040    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
1041        guard !range.isEmpty else { return }
1042        let whole = NSRange(range)
1043        storage.setAttributes(theme.base, range: whole)
1044        guard isOrg else {
1045            for run in plainRuns() where run.range.overlaps(range) {
1046                guard let clipped = clip(run.range, to: range) else { continue }
1047                theme.apply(.syntax(run.category), to: storage, range: clipped)
1048            }
1049            return
1050        }
1051        if indented {
1052            for line in Presentation.lineIndents(document.tree, in: range) {
1053                storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
1054            }
1055        }
1056        let revealed = caretLine
1057        var scriptExclusions: [Range<Int>] = []
1058        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
1059            guard let clipped = clip(run.range, to: range) else { continue }
1060            if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
1061            if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
1062                storage.addAttributes(theme.hidden, range: clipped)
1063            } else {
1064                theme.apply(run.role, to: storage, range: clipped)
1065            }
1066            if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
1067        }
1068        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
1069        applyShrunk(range, in: storage)
1070        applyHighlights(range, in: storage)
1071        applyImages(range, in: storage, revealed: revealed)
1072    }
1073
1074    /// `org-pretty-entities`: entities drawn as their character over the entity's last
1075    /// character (the rest hidden), sub/superscripts raised without their markers.
1076    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
1077        let runs = Presentation.prettyRuns(
1078            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
1079            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
1080        )
1081        for (lineStart, run) in runs {
1082            switch run {
1083            case .entity(let r, let display):
1084                let start = lineStart + r.lowerBound
1085                let last = lineStart + r.upperBound - 1
1086                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
1087                storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
1088            case .script(let markers, let body, let superscript):
1089                for marker in markers {
1090                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
1091                }
1092                let size = theme.font.pointSize
1093                storage.addAttributes([
1094                    .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
1095                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
1096                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
1097            }
1098        }
1099    }
1100
1101    /// Moving to another line shows its markup and hides the last one's.
1102    private func revealCaretLine() {
1103        guard !showMarkup, isOrg else { return }
1104        let line = caretLine
1105        guard line != revealedLine else { return }
1106        let text = textView.string as NSString
1107        // The old line may have moved with edits since; restyle the line now at its start.
1108        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
1109        revealedLine = line
1110        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
1111            restyleOutsideEditing(range.location..<NSMaxRange(range))
1112        }
1113    }
1114
1115    /// Code highlights for the whole file in plain mode.
1116    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
1117        guard case .plain(let language?) = mode, let highlighter else { return [] }
1118        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
1119        let runs = highlighter.highlights(language: language, code: document.text)
1120        codeRuns = (document.revision, runs)
1121        return runs
1122    }
1123
1124    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
1125        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
1126        if let style = paragraphStyles[key] { return style }
1127        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
1128        paragraphStyles[key] = style
1129        return style
1130    }
1131
1132    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
1133        let clipped = run.clamped(to: range)
1134        return clipped.isEmpty ? nil : NSRange(clipped)
1135    }
1136
1137    /// The region an edit affects in one version of the tree: inside the innermost section
1138    /// holding the edited lines (plus the line after), every element that overlaps them or the
1139    /// line on either side. A changed heading line, or an added or removed heading, widens it
1140    /// to that section's whole own body. Run on the old and the new tree, the union covers
1141    /// elements that grew and elements that shrank.
1142    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
1143        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
1144        let lineRange = lines.location..<(lines.location + lines.length)
1145        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
1146        var container = tree.root
1147        while let child = container.child(containing: lineRange.lowerBound),
1148              child.kind == .section || child.kind == .zerothSection,
1149              lineRange.upperBound <= child.range.upperBound {
1150            container = child
1151        }
1152        var lower = lineRange.lowerBound
1153        var upper = lineRange.upperBound
1154        // Tables and lists carry no styling of their own, so inside them only the rows or
1155        // items around the edit change, however large they are.
1156        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1157            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1158                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1159                let inner = overlapping(node.children(overlapping: around))
1160                return inner.isEmpty ? [node] : inner
1161            }
1162        }
1163        for child in overlapping(container.children(overlapping: around)) {
1164            lower = min(lower, child.range.lowerBound)
1165            upper = max(upper, child.range.upperBound)
1166        }
1167        let heading = container.firstChild(.heading)
1168        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1169            lower = min(lower, container.range.lowerBound)
1170            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1171        }
1172        return lower..<min(upper, text.length)
1173    }
1174
1175    // MARK: - Editing
1176
1177    private var blockCheck: DispatchWorkItem?
1178
1179    /// Looks for blocks over the whole file once typing pauses, catching what moving the
1180    /// ranges can't see (a block's end found far away).
1181    private func scheduleBlockCheck() {
1182        blockCheck?.cancel()
1183        let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
1184        blockCheck = work
1185        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
1186    }
1187
1188    func settleBlocks() {
1189        blockCheck?.cancel()
1190        guard isOrg else { return }
1191        let blocks = Presentation.shadedBlocks(document.tree)
1192        guard blocks != shaded.all else { return }
1193        let old = shaded.all
1194        shaded.set(blocks)
1195        invalidateLayout(from: old, to: blocks)
1196    }
1197
1198    /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
1199    /// them), hold a block delimiter or a fixed-width line.
1200    static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
1201        let start = min(range.lowerBound, text.length)
1202        let end = min(range.upperBound + 1, text.length)
1203        let lines = text.lineRange(for: NSRange(location: start, length: end - start))
1204        let content = text.substring(with: lines)
1205        return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
1206    }
1207
1208    fileprivate func storageEdited(range: NSRange, delta: Int) {
1209        guard !isLoading, let storage = textView.textStorage else { return }
1210        markActive = false
1211        let clock = ContinuousClock()
1212        let start = clock.now
1213        let replacement = (storage.string as NSString).substring(with: range)
1214        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
1215        let oldText = document.text as NSString
1216        let newText = storage.string as NSString
1217        let newEnd = edit.range.lowerBound + replacement.utf16.count
1218        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
1219            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
1220        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
1221        do {
1222            try document.apply([edit], baseRevision: document.revision)
1223        } catch {
1224            assertionFailure("text view and document disagree: \(error)")
1225            return
1226        }
1227        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
1228        // edited line when the edit reaches into unstyled text.
1229        if styledUpTo >= edit.range.upperBound {
1230            styledUpTo += edit.replacement.utf16.count - edit.range.count
1231        } else if styledUpTo > edit.range.lowerBound {
1232            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
1233        }
1234        let oldHidden = hidden.all
1235        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
1236        let delta = edit.replacement.utf16.count - edit.range.count
1237        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
1238        view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
1239        mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
1240        if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
1241        mapVimPositions(through: edit)
1242        if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
1243        let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
1244        highlights = []
1245        updateHidden()
1246        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
1247        for table in shrunk.map(through: edit, in: storage.string, command: commandEditing) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
1248        for range in oldHighlights where range.upperBound <= newText.length {
1249            let lines = newText.lineRange(for: NSRange(range))
1250            restyle(lines.location..<NSMaxRange(lines), in: storage)
1251        }
1252        let oldShaded = shaded.all
1253        if isOrg {
1254            // Walking the tree for blocks costs more than typing; only an edit on a line that
1255            // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
1256            if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
1257                shaded.set(Presentation.shadedBlocks(document.tree))
1258            } else {
1259                shaded.set(oldShaded.map { mapRange($0, through: edit) })
1260            }
1261            scheduleBlockCheck()
1262        }
1263        invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
1264        invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
1265        onEditTiming?(clock.now - start)
1266        let lineCount = lines.lineCount
1267        lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
1268        if lines.lineCount != lineCount { orgTextView?.updateGutter() }
1269        orgTextView?.redrawLineNumbers()
1270        onChange?()
1271    }
1272
1273    /// Whether a heading line touches `start..<end` or starts right after it, where joining
1274    /// lines could take it away.
1275    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1276        let length = min(end + 1, text.length) - start
1277        guard length >= 0 else { return false }
1278        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1279        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1280            let stars = line.prefix { $0 == "*" }
1281            let after = line.dropFirst(stars.count)
1282            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1283        }
1284    }
1285
1286    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1287        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1288        return mapped
1289    }
1290
1291    /// Shaded block lines the old or new selection covers are drawn again, as they draw the
1292    /// selection over their band.
1293    private func redrawShadedSelection(_ selection: NSRange) {
1294        defer { previousSelectionRange = selection }
1295        redrawShaded([previousSelectionRange, selection])
1296    }
1297
1298    private func redrawShaded(_ ranges: [NSRange]) {
1299        guard let manager = textLayoutManager.textContentManager else { return }
1300        for old in ranges where old.length > 0 {
1301            for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
1302                let lower = max(block.lowerBound, old.location)
1303                let upper = min(block.upperBound, NSMaxRange(old))
1304                guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
1305                      let end = manager.location(start, offsetBy: upper - lower),
1306                      let range = NSTextRange(location: start, end: end) else { continue }
1307                textLayoutManager.invalidateLayout(for: range)
1308            }
1309        }
1310    }
1311
1312    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1313    /// back jumps to the end of the heading line.
1314    func selectionChanged() {
1315        let selection = textView.selectedRange()
1316        defer { previousSelection = selection.location }
1317        redrawShadedSelection(selection)
1318        onSelectionChange?(selection)
1319        revealCaretLine()
1320        orgTextView?.redrawLineNumbers()
1321        // Narrowing keeps the caret in the region.
1322        if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
1323            setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
1324            return
1325        }
1326        // A selection reaching into folded text, as a find match does, unfolds it.
1327        if selection.length > 0 {
1328            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1329                unfold(around: selection.location)
1330                unfold(around: NSMaxRange(selection) - 1)
1331            }
1332            return
1333        }
1334        guard let range = hidden.containing(selection.location) else { return }
1335        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1336    }
1337}
1338
1339extension OrgEditor: DocumentBuffer {
1340    /// The selected text, for capture's `%i`.
1341    public var selectedText: String {
1342        let range = textView.selectedRange()
1343        guard range.length > 0 else { return "" }
1344        return (textView.string as NSString).substring(with: range)
1345    }
1346
1347    public var selection: [Range<Int>] {
1348        let selected = textView.selectedRange()
1349        return [selected.location..<NSMaxRange(selected)]
1350    }
1351
1352    /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1353    /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1354    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1355        let before = document.text
1356        let defaultsBefore = document.defaults
1357        let selected = textView.selectedRange()
1358        let result = try change(&document)
1359        if document.text != before {
1360            let edits = lineEdits(from: before, to: document.text)
1361            var state = view
1362            state.selection = [selected.location..<NSMaxRange(selected)]
1363            let mapped = state.mapped(through: edits)
1364            // Shrunk columns were measured on the old text.
1365            shrunk = ShrunkColumns()
1366            load(document.text)
1367            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1368            let selection = mapped.selection[0]
1369            setCaret(selection.lowerBound)
1370            if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1371            textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1372            textView.undoManager?.removeAllActions(withTarget: textView)
1373        } else if document.defaults != defaultsBefore {
1374            // New settings for the same text: TODO keywords may color differently.
1375            restyleEverything()
1376        }
1377        onChange?()
1378        return result
1379    }
1380}
1381
1382extension OrgEditor: NSTextStorageDelegate {
1383    public nonisolated func textStorage(
1384        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1385    ) {
1386        MainActor.assumeIsolated { storageGeneration += 1 }
1387        guard editedMask.contains(.editedCharacters) else { return }
1388        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1389    }
1390}
1391
1392extension OrgEditor: NSTextContentStorageDelegate {
1393    /// Folded text isn't enumerated, so it isn't laid out or drawn.
1394    public nonisolated func textContentManager(
1395        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1396    ) -> Bool {
1397        guard let range = textElement.elementRange else { return true }
1398        let documentStart = textContentManager.documentRange.location
1399        let start = textContentManager.offset(from: documentStart, to: range.location)
1400        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1401        return !hidden.covers(start, end)
1402    }
1403}
1404
1405extension OrgEditor: NSTextLayoutManagerDelegate {
1406    public nonisolated func textLayoutManager(
1407        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1408    ) -> NSTextLayoutFragment {
1409        let range = textElement.elementRange
1410        if let range, let manager = textLayoutManager.textContentManager {
1411            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1412            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1413            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1414            if let paragraph = textElement as? NSTextParagraph, ImageFragment.image(paragraph.attributedString) != nil {
1415                return ImageFragment(textElement: textElement, range: range)
1416            }
1417            if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1418                return EntityFragment(textElement: textElement, range: range)
1419            }
1420        }
1421        return NSTextLayoutFragment(textElement: textElement, range: range)
1422    }
1423}
1424
1425/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1426/// `org-block` face.
1427final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1428    private var band: CGRect {
1429        let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1430        // Not under the empty line TextKit adds after a final newline.
1431        let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1432        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1433    }
1434
1435    override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1436
1437    override func draw(at point: CGPoint, in context: CGContext) {
1438        context.saveGState()
1439        context.setFillColor(Theme.blockBackground.cgColor)
1440        context.fill(band.offsetBy(dx: point.x, dy: point.y))
1441        // The band covers the view's selection highlight, so the selected text is drawn on it,
1442        // in the color the view uses: the theme's when focused, the system's muted one when not.
1443        if let manager = textLayoutManager {
1444            let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
1445            context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
1446            let single = textLineFragments.count == 1
1447            for selection in manager.textSelections {
1448                for range in selection.textRanges where !range.isEmpty {
1449                    guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
1450                    manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
1451                        var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
1452                        // A one-line fragment's selection covers its band, leaving no gap to the next line.
1453                        if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
1454                        context.fill(rect)
1455                        return true
1456                    }
1457                }
1458            }
1459        }
1460        context.restoreGState()
1461        super.draw(at: point, in: context)
1462    }
1463}
1464
1465extension NSAttributedString.Key {
1466    /// The character an entity shows as, on the entity's last character.
1467    static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1468    /// The image an image link's line shows under it.
1469    static let orgImage = NSAttributedString.Key("OrgImage")
1470}
1471
1472final class InlineImageBox: NSObject, @unchecked Sendable {
1473    let image: NSImage
1474    let size: CGSize
1475    init(image: NSImage, size: CGSize) {
1476        self.image = image
1477        self.size = size
1478    }
1479}
1480
1481/// An image link's line drawn as the image, with the paragraph spacing making room for its
1482/// height.
1483final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
1484    static func image(_ string: NSAttributedString) -> InlineImageBox? {
1485        var found: InlineImageBox?
1486        string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1487            if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1488        }
1489        return found
1490    }
1491
1492    private var frame: CGRect? {
1493        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
1494        return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
1495    }
1496
1497    override var renderingSurfaceBounds: CGRect {
1498        frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
1499    }
1500
1501    override func draw(at point: CGPoint, in context: CGContext) {
1502        super.draw(at: point, in: context)
1503        guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
1504        NSGraphicsContext.saveGraphicsState()
1505        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1506        box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
1507        NSGraphicsContext.restoreGraphicsState()
1508    }
1509}
1510
1511/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1512/// (now invisible) character sits, so it takes one column as in Emacs.
1513final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1514    static func hasEntities(_ string: NSAttributedString) -> Bool {
1515        var found = false
1516        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1517            if value != nil { found = true; stop.pointee = true }
1518        }
1519        return found
1520    }
1521
1522    override func draw(at point: CGPoint, in context: CGContext) {
1523        super.draw(at: point, in: context)
1524        Self.drawEntities(of: self, at: point, in: context)
1525    }
1526
1527    static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1528        guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1529        NSGraphicsContext.saveGraphicsState()
1530        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1531        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1532            guard let display = value as? String,
1533                  let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1534            var attributes = string.attributes(at: range.location, effectiveRange: nil)
1535            attributes[.foregroundColor] = NSColor.textColor
1536            attributes[.orgEntityDisplay] = nil
1537            let x = line.locationForCharacter(at: range.location).x
1538            let bounds = line.typographicBounds
1539            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1540        }
1541        NSGraphicsContext.restoreGraphicsState()
1542    }
1543}
1544
1545/// A heading line drawn with an ellipsis after it, like org's folded headings.
1546final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1547    override func draw(at point: CGPoint, in context: CGContext) {
1548        super.draw(at: point, in: context)
1549        EntityFragment.drawEntities(of: self, at: point, in: context)
1550        guard let line = textLineFragments.first else { return }
1551        let bounds = line.typographicBounds
1552        let ellipsis = NSAttributedString(string: " …", attributes: [
1553            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1554            .foregroundColor: NSColor.secondaryLabelColor,
1555        ])
1556        NSGraphicsContext.saveGraphicsState()
1557        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1558        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1559        NSGraphicsContext.restoreGraphicsState()
1560    }
1561
1562    override var renderingSurfaceBounds: CGRect {
1563        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1564    }
1565}
1566#endif