Sources/OrgEditorAppKit/OrgEditor.swift

4b4dc0135e1d59d493a0a49865fcd155aeea59e0
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

1476 lines · 71966 bytes

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