Sources/OrgEditorAppKit/OrgEditor.swift

d4c76b8503d7069cc3c2404db3cafc46defe1a9a
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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