Sources/OrgEditorAppKit/OrgEditor.swift

71333253c9544b857c22f69f56d3af166b7ef573
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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