Sources/OrgEditorAppKit/OrgEditor.swift

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

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