Sources/OrgEditorAppKit/OrgEditor.swift

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

1353 lines · 65354 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.narrow.toggle", "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            // `org-toggle-narrow-to-subtree`.
 619            case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
 620            case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
 621            default: narrowed = nil
 622            }
 623        } catch let failure as Narrowing.Failure {
 624            onMessage?(failure.message)
 625            return
 626        } catch {
 627            return
 628        }
 629        updateHidden()
 630        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
 631        orgTextView?.redrawLineNumbers()
 632        textView.needsDisplay = true
 633        if let narrowed {
 634            setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
 635            textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
 636        } else {
 637            textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
 638        }
 639    }
 640
 641    /// What narrowing hides: the text before the region, and the lines after it.
 642    private var narrowHidden: [Range<Int>] {
 643        guard let narrowed else { return [] }
 644        let length = utf16Length
 645        var ranges: [Range<Int>] = []
 646        if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
 647        let ns = textView.string as NSString
 648        let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
 649        if tail < length { ranges.append(tail..<length) }
 650        return ranges
 651    }
 652
 653    // MARK: - Shrunk table columns
 654
 655    /// Narrowed table columns (`org-table-shrink`): by table start, each column's segments.
 656    /// Recomputed as the text changes; typing into one widens its column again, as editing
 657    /// org's overlays deletes them. Commands' edits keep columns narrow, as `org-table-align`
 658    /// shrinks them again.
 659    private var shrunk: [Int: [Int: [TableShrink.Segment]]] = [:]
 660    private var commandEditing = false
 661
 662    /// Narrows `columns` of `table` and widens its others.
 663    private func setShrunk(_ columns: [Int], in table: Range<Int>) {
 664        let text = textView.string
 665        let segments = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
 666        shrunk[table.lowerBound] = segments.isEmpty ? nil : segments
 667        restyleOutsideEditing(table)
 668        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
 669        textView.needsDisplay = true
 670    }
 671
 672    /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
 673    /// `expand` for `org-table-expand`.
 674    private func tableColumnWidth(_ id: String) {
 675        let caret = textView.selectedRange().location
 676        let text = textView.string
 677        guard let table = TableShrink.table(at: caret, in: text) else {
 678            onMessage?("Not in a table")
 679            return
 680        }
 681        let current = shrunk[table.lowerBound].map { Array($0.keys) } ?? []
 682        switch id {
 683        case "org.table.shrink": setShrunk(TableShrink.cookieColumns(table, in: text), in: table)
 684        case "org.table.expand": setShrunk([], in: table)
 685        default:
 686            if let column = TableShrink.column(at: caret, in: text) {
 687                setShrunk(Array(Set(current).symmetricDifference([column])), in: table)
 688                return
 689            }
 690            let line = (text as NSString).lineRange(for: NSRange(location: caret, length: 0))
 691            onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
 692                guard let self, let answer else { return }
 693                self.setShrunk(Array(Set(current).symmetricDifference(TableShrink.columns(answer, max: line.length / 2))), in: table)
 694            }
 695        }
 696    }
 697
 698    /// `#+STARTUP: shrink`: every table's columns with width cookies start narrow.
 699    private func shrinkAtStartup() {
 700        guard Presentation.startupOptions(document.tree).contains(where: { $0.lowercased() == "shrink" }) else { return }
 701        let text = textView.string
 702        var offset = 0
 703        let ns = text as NSString
 704        while offset < ns.length {
 705            let line = ns.lineRange(for: NSRange(location: offset, length: 0))
 706            defer { offset = max(NSMaxRange(line), offset + 1) }
 707            guard ns.substring(with: line).range(of: "^[ \\t]*\\|", options: .regularExpression) != nil,
 708                  let table = TableShrink.table(at: line.location, in: text) else { continue }
 709            let columns = TableShrink.cookieColumns(table, in: text)
 710            if !columns.isEmpty { shrunk[table.lowerBound] = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) }) }
 711            offset = table.upperBound
 712        }
 713    }
 714
 715    /// Moves shrunk columns through `edit`; returns the tables to restyle.
 716    private func mapShrunk(through edit: TextEdit) -> [Range<Int>] {
 717        guard !shrunk.isEmpty else { return [] }
 718        let text = textView.string
 719        let delta = edit.replacement.utf16.count - edit.range.count
 720        var mapped: [Int: [Int: [TableShrink.Segment]]] = [:]
 721        var tables: [Range<Int>] = []
 722        for (start, columns) in shrunk {
 723            let kept = columns.filter { _, segments in
 724                commandEditing || !segments.contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
 725            }.keys
 726            let touched = columns.values.joined().contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
 727            let newStart = start < edit.range.lowerBound ? start : start >= edit.range.upperBound ? start + delta : edit.range.lowerBound
 728            guard let table = TableShrink.table(at: min(newStart, max(0, text.utf16.count - 1)), in: text) else { continue }
 729            if touched || kept.count != columns.count { tables.append(table) }
 730            guard !kept.isEmpty else { continue }
 731            mapped[table.lowerBound] = Dictionary(uniqueKeysWithValues: kept.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
 732        }
 733        shrunk = mapped
 734        return tables
 735    }
 736
 737    /// Hides each shrunk segment's text and draws its display where the text was.
 738    private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
 739        guard !shrunk.isEmpty else { return }
 740        let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
 741        for segment in shrunk.values.flatMap({ $0.values.joined() }) where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
 742            let r = segment.range
 743            let shown = segment.display.count
 744            let kept = min(shown, r.count)
 745            if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
 746            guard kept > 0 else { continue }
 747            let visible = NSRange(location: r.upperBound - kept, length: kept)
 748            storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
 749            storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
 750            if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
 751        }
 752    }
 753
 754    /// Moves drawer and block folds through `edit`, checking again only those near it.
 755    private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
 756        guard !wrapperHidden.isEmpty else { return }
 757        var mapped: [Int: Range<Int>] = [:]
 758        let entries = Array(wrapperHidden)
 759        // One pass maps every start and range.
 760        let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
 761        for i in entries.indices {
 762            let newStart = moved[2 * i].lowerBound
 763            let newRange = moved[2 * i + 1]
 764            if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
 765                if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
 766            } else {
 767                mapped[newStart] = newRange
 768            }
 769        }
 770        wrapperHidden = mapped
 771        view.wrapperFolds = Set(mapped.keys)
 772    }
 773
 774    /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
 775    /// cycles folded, children, subtree. Returns false elsewhere.
 776    @discardableResult
 777    public func cycleAtCaret() -> Bool {
 778        leaveSparseTree()
 779        let caret = textView.selectedRange().location
 780        guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
 781        setFolds(state)
 782        // Off a closing line that folding hid, to the opening line, as org does.
 783        if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
 784        return true
 785    }
 786
 787    /// Shift-TAB: overview, contents, show all.
 788    public func cycleGlobal() {
 789        leaveSparseTree()
 790        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
 791        globalVisibility = visibility
 792        setFolds(state)
 793    }
 794
 795    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
 796    public func reveal(_ offset: Int) {
 797        let target = max(0, min(offset, utf16Length))
 798        if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
 799        unfold(around: target)
 800        setCaret(target)
 801        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
 802    }
 803
 804    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
 805    func unfold(around offset: Int) {
 806        leaveSparseTree()
 807        var state = foldState
 808        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
 809            state.folds.remove(entry.start)
 810            state.bodyFolds.remove(entry.start)
 811        }
 812        for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
 813            state.wrapperFolds.remove(start)
 814        }
 815        guard state != foldState else { return }
 816        setFolds(state)
 817    }
 818
 819    /// Applies edits through the text view as one undo step, not merged with typing around it.
 820    func applyEdits(_ edits: [TextEdit]) {
 821        guard !edits.isEmpty, let storage = textView.textStorage else { return }
 822        textView.breakUndoCoalescing()
 823        textView.undoManager?.beginUndoGrouping()
 824        for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
 825            let range = NSRange(edit.range)
 826            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
 827            storage.replaceCharacters(in: range, with: edit.replacement)
 828            textView.didChangeText()
 829        }
 830        textView.undoManager?.endUndoGrouping()
 831        textView.breakUndoCoalescing()
 832    }
 833
 834    func setCaret(_ offset: Int) {
 835        let clamped = max(0, min(offset, utf16Length))
 836        previousSelection = clamped
 837        textView.setSelectedRange(NSRange(location: clamped, length: 0))
 838    }
 839
 840    // MARK: - Styling
 841
 842    private func restyleOutsideEditing(_ range: Range<Int>) {
 843        guard let storage = textView.textStorage else { return }
 844        storage.beginEditing()
 845        restyle(range, in: storage)
 846        storage.endEditing()
 847    }
 848
 849    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
 850    /// attribute changes are allowed and characters must not change.
 851    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
 852        guard !range.isEmpty else { return }
 853        let whole = NSRange(range)
 854        storage.setAttributes(theme.base, range: whole)
 855        guard isOrg else {
 856            for run in plainRuns() where run.range.overlaps(range) {
 857                guard let clipped = clip(run.range, to: range) else { continue }
 858                theme.apply(.syntax(run.category), to: storage, range: clipped)
 859            }
 860            return
 861        }
 862        let text = storage.string as NSString
 863        for run in Presentation.indents(document.tree, in: range) {
 864            guard let clipped = clip(run.range, to: range) else { continue }
 865            guard run.firstLine == run.wrapped else {
 866                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
 867                continue
 868            }
 869            // Body lines wrap under their own text: past leading blanks, and past a list bullet
 870            // and checkbox, as adaptive-wrap does in Emacs.
 871            var location = clipped.location
 872            while location < NSMaxRange(clipped) {
 873                let line = text.lineRange(for: NSRange(location: location, length: 0))
 874                let hanging = Self.hangingColumns(text.substring(with: line))
 875                let lineRange = NSIntersectionRange(line, clipped)
 876                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
 877                location = NSMaxRange(line)
 878            }
 879        }
 880        let revealed = caretLine
 881        var scriptExclusions: [Range<Int>] = []
 882        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
 883            guard let clipped = clip(run.range, to: range) else { continue }
 884            if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
 885                storage.addAttributes(theme.hidden, range: clipped)
 886            } else {
 887                theme.apply(run.role, to: storage, range: clipped)
 888            }
 889            switch run.role {
 890            case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
 891            default: break
 892            }
 893        }
 894        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
 895        applyShrunk(range, in: storage)
 896        applyHighlights(range, in: storage)
 897    }
 898
 899    /// `org-pretty-entities`: entities drawn as their character over the entity's last
 900    /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
 901    /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
 902    /// keywords, as `org-raise-scripts` leaves them.
 903    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
 904        let text = storage.string as NSString
 905        var location = range.lowerBound
 906        while location < range.upperBound {
 907            let line = text.lineRange(for: NSRange(location: location, length: 0))
 908            guard line.length > 0 else { break }
 909            location = NSMaxRange(line)
 910            if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
 911            let content = text.substring(with: line)
 912            if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
 913            for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
 914                switch run {
 915                case .entity(let r, let display):
 916                    let start = line.location + r.lowerBound
 917                    let last = line.location + r.upperBound - 1
 918                    if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
 919                    storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
 920                case .script(let markers, let body, let superscript):
 921                    let bodyStart = line.location + body.lowerBound
 922                    if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
 923                    for marker in markers {
 924                        storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
 925                    }
 926                    let size = theme.font.pointSize
 927                    storage.addAttributes([
 928                        .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
 929                        .baselineOffset: (superscript ? 0.3 : -0.3) * size,
 930                    ], range: NSRange(location: bodyStart, length: body.count))
 931                }
 932            }
 933        }
 934    }
 935
 936    /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
 937    /// markers only when Emacs hides them too.
 938    private func hides(_ role: StyleRole) -> Bool {
 939        switch role {
 940        case .linkMarkup: true
 941        case .markup: options.hideEmphasisMarkers
 942        default: false
 943        }
 944    }
 945
 946    /// Moving to another line shows its markup and hides the last one's.
 947    private func revealCaretLine() {
 948        guard !showMarkup, isOrg else { return }
 949        let line = caretLine
 950        guard line != revealedLine else { return }
 951        let text = textView.string as NSString
 952        // The old line may have moved with edits since; restyle the line now at its start.
 953        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
 954        revealedLine = line
 955        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
 956            restyleOutsideEditing(range.location..<NSMaxRange(range))
 957        }
 958    }
 959
 960    /// Code highlights for the whole file in plain mode.
 961    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
 962        guard case .plain(let language?) = mode, let highlighter else { return [] }
 963        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
 964        let runs = highlighter.highlights(language: language, code: document.text)
 965        codeRuns = (document.revision, runs)
 966        return runs
 967    }
 968
 969    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
 970        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
 971        if let style = paragraphStyles[key] { return style }
 972        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
 973        paragraphStyles[key] = style
 974        return style
 975    }
 976
 977    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
 978        let clipped = run.clamped(to: range)
 979        return clipped.isEmpty ? nil : NSRange(clipped)
 980    }
 981
 982    /// The region an edit affects in one version of the tree: inside the innermost section
 983    /// holding the edited lines (plus the line after), every element that overlaps them or the
 984    /// line on either side. A changed heading line, or an added or removed heading, widens it
 985    /// to that section's whole own body. Run on the old and the new tree, the union covers
 986    /// elements that grew and elements that shrank.
 987    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
 988        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
 989        let lineRange = lines.location..<(lines.location + lines.length)
 990        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
 991        var container = tree.root
 992        while let child = container.child(containing: lineRange.lowerBound),
 993              child.kind == .section || child.kind == .zerothSection,
 994              lineRange.upperBound <= child.range.upperBound {
 995            container = child
 996        }
 997        var lower = lineRange.lowerBound
 998        var upper = lineRange.upperBound
 999        // Tables and lists carry no styling of their own, so inside them only the rows or
1000        // items around the edit change, however large they are.
1001        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1002            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1003                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1004                let inner = overlapping(node.children(overlapping: around))
1005                return inner.isEmpty ? [node] : inner
1006            }
1007        }
1008        for child in overlapping(container.children(overlapping: around)) {
1009            lower = min(lower, child.range.lowerBound)
1010            upper = max(upper, child.range.upperBound)
1011        }
1012        let heading = container.firstChild(.heading)
1013        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1014            lower = min(lower, container.range.lowerBound)
1015            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1016        }
1017        return lower..<min(upper, text.length)
1018    }
1019
1020    // MARK: - Editing
1021
1022    private var blockCheck: DispatchWorkItem?
1023
1024    /// Looks for blocks over the whole file once typing pauses, catching what moving the
1025    /// ranges can't see (a block's end found far away).
1026    private func scheduleBlockCheck() {
1027        blockCheck?.cancel()
1028        let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
1029        blockCheck = work
1030        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
1031    }
1032
1033    func settleBlocks() {
1034        blockCheck?.cancel()
1035        guard isOrg else { return }
1036        let blocks = Presentation.shadedBlocks(document.tree)
1037        guard blocks != shaded.all else { return }
1038        shaded.set(blocks)
1039        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1040    }
1041
1042    /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
1043    /// them), hold a block delimiter or a fixed-width line.
1044    static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
1045        let start = min(range.lowerBound, text.length)
1046        let end = min(range.upperBound + 1, text.length)
1047        let lines = text.lineRange(for: NSRange(location: start, length: end - start))
1048        let content = text.substring(with: lines)
1049        return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
1050    }
1051
1052    fileprivate func storageEdited(range: NSRange, delta: Int) {
1053        guard !isLoading, let storage = textView.textStorage else { return }
1054        markActive = false
1055        let clock = ContinuousClock()
1056        let start = clock.now
1057        let replacement = (storage.string as NSString).substring(with: range)
1058        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
1059        let oldText = document.text as NSString
1060        let newText = storage.string as NSString
1061        let newEnd = edit.range.lowerBound + replacement.utf16.count
1062        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
1063            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
1064        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
1065        do {
1066            try document.apply([edit], baseRevision: document.revision)
1067        } catch {
1068            assertionFailure("text view and document disagree: \(error)")
1069            return
1070        }
1071        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
1072        // edited line when the edit reaches into unstyled text.
1073        if styledUpTo >= edit.range.upperBound {
1074            styledUpTo += edit.replacement.utf16.count - edit.range.count
1075        } else if styledUpTo > edit.range.lowerBound {
1076            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
1077        }
1078        let oldHidden = hidden.all
1079        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
1080        let delta = edit.replacement.utf16.count - edit.range.count
1081        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
1082        view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
1083        mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
1084        if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
1085        if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
1086        let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
1087        highlights = []
1088        updateHidden()
1089        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
1090        for table in mapShrunk(through: edit) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
1091        for range in oldHighlights where range.upperBound <= newText.length {
1092            let lines = newText.lineRange(for: NSRange(range))
1093            restyle(lines.location..<NSMaxRange(lines), in: storage)
1094        }
1095        let oldShaded = shaded.all
1096        if isOrg {
1097            // Walking the tree for blocks costs more than typing; only an edit on a line that
1098            // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
1099            if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
1100                shaded.set(Presentation.shadedBlocks(document.tree))
1101            } else {
1102                shaded.set(oldShaded.map { mapRange($0, through: edit) })
1103            }
1104            scheduleBlockCheck()
1105        }
1106        if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
1107            || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
1108            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1109        }
1110        onEditTiming?(clock.now - start)
1111        let lineCount = lines.lineCount
1112        lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
1113        if lines.lineCount != lineCount { orgTextView?.updateGutter() }
1114        orgTextView?.redrawLineNumbers()
1115        onChange?()
1116    }
1117
1118    /// Columns a wrapped continuation of `line` should start past the line's own start.
1119    nonisolated static func hangingColumns(_ line: String) -> Int {
1120        var columns = 0
1121        var rest = Substring(line)
1122        while let c = rest.first, c == " " || c == "\t" {
1123            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
1124            rest = rest.dropFirst()
1125        }
1126        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
1127        var bullet = 0
1128        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
1129            bullet = 1
1130        } else {
1131            let digits = rest.prefix { $0.isASCII && $0.isNumber }
1132            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
1133                bullet = digits.count + 1
1134            }
1135        }
1136        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
1137        columns += bullet + 1
1138        let afterBullet = rest.dropFirst(bullet + 1)
1139        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
1140           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
1141            columns += 4
1142        }
1143        return columns
1144    }
1145
1146    /// Whether a heading line touches `start..<end` or starts right after it, where joining
1147    /// lines could take it away.
1148    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1149        let length = min(end + 1, text.length) - start
1150        guard length >= 0 else { return false }
1151        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1152        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1153            let stars = line.prefix { $0 == "*" }
1154            let after = line.dropFirst(stars.count)
1155            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1156        }
1157    }
1158
1159    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1160        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1161        return mapped
1162    }
1163
1164    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1165    /// back jumps to the end of the heading line.
1166    fileprivate func selectionChanged() {
1167        let selection = textView.selectedRange()
1168        defer { previousSelection = selection.location }
1169        onSelectionChange?(selection)
1170        revealCaretLine()
1171        orgTextView?.redrawLineNumbers()
1172        // Narrowing keeps the caret in the region.
1173        if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
1174            setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
1175            return
1176        }
1177        // A selection reaching into folded text, as a find match does, unfolds it.
1178        if selection.length > 0 {
1179            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1180                unfold(around: selection.location)
1181                unfold(around: NSMaxRange(selection) - 1)
1182            }
1183            return
1184        }
1185        guard let range = hidden.containing(selection.location) else { return }
1186        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1187    }
1188}
1189
1190extension OrgEditor: DocumentBuffer {
1191    /// The selected text, for capture's `%i`.
1192    public var selectedText: String {
1193        let range = textView.selectedRange()
1194        guard range.length > 0 else { return "" }
1195        return (textView.string as NSString).substring(with: range)
1196    }
1197
1198    public var selection: [Range<Int>] {
1199        let selected = textView.selectedRange()
1200        return [selected.location..<NSMaxRange(selected)]
1201    }
1202
1203    /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1204    /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1205    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1206        let before = document.text
1207        let selected = textView.selectedRange()
1208        let result = try change(&document)
1209        if document.text != before {
1210            let edits = lineEdits(from: before, to: document.text)
1211            var state = view
1212            state.selection = [selected.location..<NSMaxRange(selected)]
1213            let mapped = state.mapped(through: edits)
1214            load(document.text)
1215            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1216            let selection = mapped.selection[0]
1217            setCaret(selection.lowerBound)
1218            if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1219            textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1220            textView.undoManager?.removeAllActions(withTarget: textView)
1221        }
1222        onChange?()
1223        return result
1224    }
1225}
1226
1227extension OrgEditor: NSTextViewDelegate {
1228    public func textViewDidChangeSelection(_ notification: Notification) {
1229        selectionChanged()
1230    }
1231}
1232
1233extension OrgEditor: NSTextStorageDelegate {
1234    public nonisolated func textStorage(
1235        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1236    ) {
1237        guard editedMask.contains(.editedCharacters) else { return }
1238        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1239    }
1240}
1241
1242extension OrgEditor: NSTextContentStorageDelegate {
1243    /// Folded text isn't enumerated, so it isn't laid out or drawn.
1244    public nonisolated func textContentManager(
1245        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1246    ) -> Bool {
1247        guard let range = textElement.elementRange else { return true }
1248        let documentStart = textContentManager.documentRange.location
1249        let start = textContentManager.offset(from: documentStart, to: range.location)
1250        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1251        return !hidden.covers(start, end)
1252    }
1253}
1254
1255extension OrgEditor: NSTextLayoutManagerDelegate {
1256    public nonisolated func textLayoutManager(
1257        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1258    ) -> NSTextLayoutFragment {
1259        let range = textElement.elementRange
1260        if let range, let manager = textLayoutManager.textContentManager {
1261            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1262            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1263            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1264            if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1265                return EntityFragment(textElement: textElement, range: range)
1266            }
1267        }
1268        return NSTextLayoutFragment(textElement: textElement, range: range)
1269    }
1270}
1271
1272/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1273/// `org-block` face.
1274final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1275    private var band: CGRect {
1276        let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1277        // Not under the empty line TextKit adds after a final newline.
1278        let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1279        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1280    }
1281
1282    override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1283
1284    override func draw(at point: CGPoint, in context: CGContext) {
1285        context.saveGState()
1286        context.setFillColor(Theme.blockBackground.cgColor)
1287        context.fill(band.offsetBy(dx: point.x, dy: point.y))
1288        context.restoreGState()
1289        super.draw(at: point, in: context)
1290    }
1291}
1292
1293extension NSAttributedString.Key {
1294    /// The character an entity shows as, on the entity's last character.
1295    static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1296}
1297
1298/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1299/// (now invisible) character sits, so it takes one column as in Emacs.
1300final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1301    static func hasEntities(_ string: NSAttributedString) -> Bool {
1302        var found = false
1303        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1304            if value != nil { found = true; stop.pointee = true }
1305        }
1306        return found
1307    }
1308
1309    override func draw(at point: CGPoint, in context: CGContext) {
1310        super.draw(at: point, in: context)
1311        Self.drawEntities(of: self, at: point, in: context)
1312    }
1313
1314    static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1315        guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1316        NSGraphicsContext.saveGraphicsState()
1317        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1318        string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1319            guard let display = value as? String,
1320                  let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1321            var attributes = string.attributes(at: range.location, effectiveRange: nil)
1322            attributes[.foregroundColor] = NSColor.textColor
1323            attributes[.orgEntityDisplay] = nil
1324            let x = line.locationForCharacter(at: range.location).x
1325            let bounds = line.typographicBounds
1326            NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1327        }
1328        NSGraphicsContext.restoreGraphicsState()
1329    }
1330}
1331
1332/// A heading line drawn with an ellipsis after it, like org's folded headings.
1333final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1334    override func draw(at point: CGPoint, in context: CGContext) {
1335        super.draw(at: point, in: context)
1336        EntityFragment.drawEntities(of: self, at: point, in: context)
1337        guard let line = textLineFragments.first else { return }
1338        let bounds = line.typographicBounds
1339        let ellipsis = NSAttributedString(string: " …", attributes: [
1340            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1341            .foregroundColor: NSColor.secondaryLabelColor,
1342        ])
1343        NSGraphicsContext.saveGraphicsState()
1344        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1345        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1346        NSGraphicsContext.restoreGraphicsState()
1347    }
1348
1349    override var renderingSurfaceBounds: CGRect {
1350        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1351    }
1352}
1353#endif