Sources/OrgEditorAppKit/OrgEditor.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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