Sources/OrgEditorAppKit/OrgEditor.swift

2cef47f82373d81f99d371b9aceb8bdc702f54c1
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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