Sources/OrgEditorAppKit/OrgEditor.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

1088 lines · 51614 bytes

39 symbols in this file
   1#if os(macOS)
   2import AppKit
   3import OrgCore
   4import OrgDocument
   5import OrgPresentation
   6
   7/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
   8/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
   9///
  10/// The editor is the buffer: text, undo, folds, narrowing, sparse trees and evil state are its,
  11/// as they are a buffer's in Emacs. It can show in several text views at once (`addView`),
  12/// each with its own caret, scroll position and focus, as windows show a buffer.
  13@MainActor
  14public final class OrgEditor: NSObject {
  15    /// The text view commands act on: the one with focus, or the last to have had it.
  16    public var textView: NSTextView { active }
  17    private(set) var active: OrgTextView
  18    /// Every text view on the storage; the first was made with the editor.
  19    public private(set) var textViews: [NSTextView] = []
  20    var orgTextViews: [OrgTextView] { textViews.compactMap { $0 as? OrgTextView } }
  21    var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
  22    /// One undo history for the buffer, whichever view edits it.
  23    public let undoManager = UndoManager()
  24    /// A text view of this editor took keyboard focus.
  25    public var onFocus: ((NSTextView) -> Void)?
  26    public private(set) var document: DocumentState
  27    public internal(set) var view = ViewState()
  28    /// Called with the time from a character edit to restyled text.
  29    public var onEditTiming: ((Duration) -> Void)?
  30
  31    let hidden = HiddenRanges()
  32    let folded = FoldedHeadings()
  33    /// Where lines start, for line numbers.
  34    let lines = LineIndex()
  35    /// Blocks drawn on a shaded band.
  36    let shaded = HiddenRanges()
  37    private(set) var theme = Theme()
  38    /// Colors and type; a change restyles the file.
  39    public var themeSpec: ThemeSpec = .default {
  40        didSet {
  41            guard themeSpec != oldValue else { return }
  42            theme = Theme(themeSpec)
  43            keepingTopLine {
  44                applyThemeToView()
  45                restyleEverything()
  46                invalidateAllLayout()
  47            }
  48        }
  49    }
  50    private var isLoading = false
  51    var previousSelection = 0
  52    /// The selection shaded block lines last drew.
  53    private var previousSelectionRange = NSRange(location: 0, length: 0)
  54    /// Text before its end is styled; after it, only base attributes until the background
  55    /// passes reach it.
  56    private var styled = StyledExtent()
  57    var styledUpTo: Int { styled.end }
  58    private var stylingScheduled = false
  59    /// One paragraph style object per indent pair, shared by every line that uses it.
  60    var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
  61
  62    struct IndentKey: Hashable {
  63        let firstLine: Int
  64        let wrapped: Int
  65    }
  66
  67    /// Styled before the first render: more than a screenful.
  68    static let firstStyleChunk = 30_000
  69    /// Styled per run-loop turn afterwards.
  70    static let styleChunk = 200_000
  71
  72    /// Highlights code in src blocks; nil leaves code plain.
  73    public let highlighter: (any CodeHighlighter)?
  74
  75    /// What the file is: org, Markdown, or plain text, highlighted as code when the language
  76    /// is known.
  77    public enum Mode: Equatable, Sendable {
  78        case org
  79        case markdown
  80        case plain(language: String?)
  81    }
  82
  83    public let mode: Mode
  84    public var isOrg: Bool { mode == .org }
  85    public var isMarkdown: Bool { mode == .markdown }
  86    /// A Markdown file's structure, for the revision it was read at.
  87    var markdownCache: (revision: Int, document: MarkdownDocument)?
  88    /// The text as shown for accessibility, and the storage generation it's for.
  89    var accessibleCache: (storage: Int, text: AccessibleText)?
  90    /// Bumped on every character or attribute change to the storage.
  91    var storageGeneration = 0
  92    /// The open completion list, and the pause before one opens by itself.
  93    var completionPopup: CompletionPopup?
  94    var completionTimer: DispatchWorkItem?
  95    /// The index's answer for the completion starting at `start`, and the query running.
  96    var completionFetched: (kind: Completion.Kind, start: Int, result: CompletionResult)?
  97    var completionTask: Task<Void, Never>?
  98    /// `dabbrev-expand` being repeated.
  99    var dabbrev: DabbrevExpansion?
 100    /// The snippet whose fields are being filled in, and the range drawn for it last.
 101    var snippetSession: SnippetSession?
 102    var snippetHighlight: Range<Int>?
 103    var updatingMirrors = false
 104    /// The spell checker's skipped ranges and the text they were found in.
 105    var spellSkipCache: (text: String, ranges: [Range<Int>])?
 106    /// Highlights of the whole file in plain mode, and the revision they were made for.
 107    var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
 108
 109    public init(
 110        document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
 111        highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
 112    ) {
 113        self.document = document
 114        self.options = options
 115        self.highlighter = highlighter
 116        self.mode = mode
 117        let orgTextView = OrgTextView(usingTextLayoutManager: true)
 118        active = orgTextView
 119        textViews = [orgTextView]
 120        dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
 121        super.init()
 122        configure(orgTextView, frame: frame, editable: editable)
 123        applyThemeToView()
 124        textView.textStorage?.delegate = self
 125        textContentStorage.delegate = self
 126
 127        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
 128        let startup = isOrg ? Presentation.startupDisplay(document.tree, options: options) : nil
 129        if let startup {
 130            // What styling reads, set before the text loads: the first chunk and the
 131            // background passes style with it.
 132            indented = startup.indented
 133            hideStars = startup.hideStars
 134            shrunk = ShrunkColumns.startup(document.tree)
 135            showsImages = startup.inlineImages
 136            showsLatex = startup.latexPreview
 137        }
 138        load(document.text)
 139        // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
 140        textView.setSelectedRange(NSRange(location: 0, length: 0))
 141        if let startup {
 142            if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers, layout: false) }
 143            if startup.alignTables { _ = perform(AlignAllTables()) }
 144        }
 145        // Turning it off clears spelling marks from the whole text; a new view has none.
 146        if spellChecking != options.spellCheck { spellChecking = options.spellCheck }
 147        truncatesLines = options.startupTruncated
 148    }
 149
 150    /// A text view's settings and callbacks; the same for every view of the editor.
 151    private func configure(_ view: OrgTextView, frame: NSRect, editable: Bool) {
 152        view.keyHandler = { [weak self, unowned view] event in
 153            guard let self else { return false }
 154            self.active = view
 155            return self.handleKey(event)
 156        }
 157        view.onFocusChange = { [weak self, unowned view] in
 158            guard let self, let layout = view.textLayoutManager else { return }
 159            let id = ObjectIdentifier(layout)
 160            if view.window?.firstResponder === view, self.active !== view {
 161                self.active = view
 162                // Its caret may sit in text another view folded or narrowed away since.
 163                self.selectionChanged()
 164                self.onFocus?(view)
 165            } else if view.window?.firstResponder === view {
 166                self.onFocus?(view)
 167            }
 168            if let window = view.window, window.isKeyWindow, window.firstResponder === view {
 169                Theme.focusedLayouts.insert(id)
 170            } else {
 171                Theme.focusedLayouts.remove(id)
 172            }
 173            self.redrawShaded([view.selectedRange()])
 174        }
 175        view.onCommandClick = { [weak self, unowned view] offset in
 176            guard let self else { return false }
 177            if !self.isOrg {
 178                // Only Denote's links are followed outside org.
 179                guard Denote.link(at: offset, in: self.document.text, markdown: self.isMarkdown) != nil else { return false }
 180            } else {
 181                guard Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
 182                    || Links.citation(at: offset, text: self.document.text, tree: self.document.tree) != nil
 183                    || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
 184            }
 185            self.active = view
 186            self.setCaret(offset)
 187            self.run("org.link.open")
 188            return true
 189        }
 190        view.onClick = { [weak self, unowned view] offset in
 191            self?.active = view
 192            return self?.click(at: offset) ?? false
 193        }
 194        view.accessibleText = { [weak self] in
 195            guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
 196            if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
 197            let text = AccessibleText(storage)
 198            self.accessibleCache = (self.storageGeneration, text)
 199            return text
 200        }
 201        view.onFiles = { [weak self, unowned view] files in
 202            guard let self, let onFiles = self.onFiles, self.isOrg else { return false }
 203            self.active = view
 204            onFiles(files)
 205            return true
 206        }
 207        view.onImage = { [weak self, unowned view] data, ext in
 208            guard let self, let onImage = self.onImage, self.isOrg else { return false }
 209            self.active = view
 210            onImage(data, ext)
 211            return true
 212        }
 213        view.onWidthChange = { [weak self] in
 214            self?.fitImages()
 215            self?.refitTagGaps()
 216        }
 217        view.onMouseDown = { [weak self, unowned view] in
 218            self?.active = view
 219            self?.markActive = false
 220            self?.modalMouseDown()
 221        }
 222        view.sharedUndoManager = undoManager
 223        view.usesFindBar = true
 224        view.frame = frame
 225        view.isRichText = false
 226        view.isEditable = editable
 227        view.allowsUndo = true
 228        view.isAutomaticQuoteSubstitutionEnabled = false
 229        view.isAutomaticDashSubstitutionEnabled = false
 230        view.isAutomaticTextReplacementEnabled = false
 231        view.isAutomaticSpellingCorrectionEnabled = false
 232        view.isVerticallyResizable = true
 233        view.autoresizingMask = [.width]
 234        view.textContainer?.widthTracksTextView = true
 235        view.delegate = self
 236        view.textLayoutManager?.delegate = self
 237    }
 238
 239    /// Another text view on the same text, with its own layout, caret and scroll position.
 240    /// Its layout manager's delegate is set before its first layout, which TextKit needs.
 241    public func addView(frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800)) -> NSTextView {
 242        let layout = NSTextLayoutManager()
 243        layout.delegate = self
 244        textContentStorage.addTextLayoutManager(layout)
 245        let container = NSTextContainer(size: NSSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude))
 246        layout.textContainer = container
 247        let view = OrgTextView(frame: frame, textContainer: container)
 248        textViews.append(view)
 249        configure(view, frame: frame, editable: active.isEditable)
 250        view.lineIndex = lines
 251        view.showsLineNumbers = showLineNumbers
 252        view.lineNumbersType = lineNumbersType
 253        view.isContinuousSpellCheckingEnabled = active.isContinuousSpellCheckingEnabled
 254        view.blockCursor = active.blockCursor
 255        applyThemeToView()
 256        return view
 257    }
 258
 259    /// Takes a view made by `addView` off the storage. The first view stays.
 260    public func removeView(_ view: NSTextView) {
 261        guard let index = textViews.firstIndex(where: { $0 === view }), index > 0 else { return }
 262        textViews.remove(at: index)
 263        if active === view { active = orgTextViews[0] }
 264        if let layout = view.textLayoutManager {
 265            Theme.focusedLayouts.remove(ObjectIdentifier(layout))
 266            textContentStorage.removeTextLayoutManager(layout)
 267        }
 268    }
 269
 270    /// Lays every view out again.
 271    func invalidateAllLayout() {
 272        for layout in layoutManagers { layout.invalidateLayout(for: layout.documentRange) }
 273    }
 274
 275    /// Redraws every view, line numbers included.
 276    func redrawViews() {
 277        for view in orgTextViews {
 278            view.redrawLineNumbers()
 279            view.needsDisplay = true
 280        }
 281    }
 282
 283    /// Replaces the storage's text. Setting the attributed string directly is about 100x
 284    /// faster than `NSTextView.string` for large files.
 285    private func load(_ text: String) {
 286        isLoading = true
 287        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
 288        isLoading = false
 289        if isMarkdown { shaded.set(markdown.structure.blocks) }
 290        lines.reset(text as NSString)
 291        for view in orgTextViews {
 292            view.lineIndex = lines
 293            view.updateGutter()
 294        }
 295        styled.reset()
 296        revealedLine = caretLine
 297        styleNextChunk(Self.firstStyleChunk)
 298        scheduleStyling()
 299    }
 300
 301    // MARK: - Initial styling
 302
 303    /// Styles whole lines from the watermark onward, about `size` units.
 304    func styleNextChunk(_ size: Int) {
 305        guard let range = styled.next(size, in: textView.textStorage!.string as NSString) else { return }
 306        restyleOutsideEditing(range)
 307    }
 308
 309    /// Every text view's own colors and font, and the line numbers'.
 310    private func applyThemeToView() {
 311        Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
 312        for view in orgTextViews {
 313            view.font = theme.body
 314            view.typingAttributes = theme.base
 315            view.textWidth = CGFloat(max(0, theme.spec.textWidth)) * theme.column
 316            view.drawsBackground = true
 317            view.backgroundColor = theme.color("background") ?? .textBackgroundColor
 318            view.insertionPointColor = theme.color("cursor") ?? .textColor
 319            view.selectedTextAttributes = [.backgroundColor: Theme.selection]
 320            view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
 321            view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
 322            view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
 323            view.updateGutter()
 324            view.needsDisplay = true
 325        }
 326    }
 327
 328    /// Styles the whole file again, a screenful now and the rest in the background.
 329    private func restyleEverything() {
 330        styled.reset()
 331        revealedLine = caretLine
 332        styleNextChunk(Self.firstStyleChunk)
 333        scheduleStyling()
 334    }
 335
 336    var caretLine: NSRange {
 337        let text = textView.string as NSString
 338        return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
 339    }
 340
 341    private func scheduleStyling() {
 342        guard !stylingScheduled, styledUpTo < utf16Length else { return }
 343        stylingScheduled = true
 344        DispatchQueue.main.async { [weak self] in
 345            guard let self else { return }
 346            self.stylingScheduled = false
 347            self.styleNextChunk(Self.styleChunk)
 348            self.scheduleStyling()
 349        }
 350    }
 351
 352    /// Styles everything still waiting for a background pass.
 353    public func finishStyling() {
 354        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
 355    }
 356
 357    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
 358    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
 359    var utf16Length: Int { (textView.string as NSString).length }
 360
 361    /// A scroll view holding `view` (the active text view by default), ready for a window.
 362    public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView {
 363        let textView = view ?? self.textView
 364        let scroll = NSScrollView(frame: textView.frame)
 365        scroll.hasVerticalScroller = true
 366        scroll.documentView = textView
 367        (textView as? OrgTextView)?.showsLineNumbers = showLineNumbers
 368        (textView as? OrgTextView)?.lineNumbersType = lineNumbersType
 369        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
 370        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
 371        return scroll
 372    }
 373
 374    // MARK: - Saving
 375
 376    /// Saves through `saver`. A merge that changes the buffer reloads the text view.
 377    @discardableResult
 378    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
 379        try update { try saver.save(&$0, to: url) }
 380    }
 381
 382    /// Called after every change to the document, typed or not.
 383    public var onChange: (() -> Void)?
 384
 385    // MARK: - Commands
 386
 387    /// Called with messages commands report, such as why one couldn't run here.
 388    public var onMessage: ((String) -> Void)?
 389    /// Called with the pending prefix and what can follow it, and with nil when it ends.
 390    /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
 391    public var onModeChange: ((String?) -> Void)?
 392    /// The selection moved.
 393    public var onSelectionChange: ((NSRange) -> Void)?
 394    var reportedMode: String?
 395    public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
 396    /// Called with `app.*` commands, which the app carries out.
 397    public var onAppCommand: ((String) -> Void)?
 398    /// `:e FILE`: the path as typed, for the app to open.
 399    public var onOpenFile: ((String) -> Void)?
 400    /// Called when a command asks a question; reply with the answer, or nil to cancel.
 401    public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
 402    /// Runs work outside the text, such as a table recalculation in Emacs.
 403    public var onExternal: ((ExternalRequest) -> Void)?
 404    /// Runs a user command, calling `finished` with its message once it has ended, nil when its
 405    /// result was applied; a keyboard macro replaying waits for that. Without it, user commands
 406    /// go to `onExternal`.
 407    public var onUserCommand: ((UserCommandRequest, _ finished: @escaping @MainActor (String?) -> Void) -> Void)?
 408    /// Tags used across the workspace, for tag completion.
 409    public var knownTags: @Sendable () -> [String] = { [] }
 410    /// Answers completion's questions to the index; run off the main actor.
 411    public var completionSource: (@Sendable (CompletionQuery) async -> CompletionResult)?
 412    /// Gives a heading in another file an ID for a link to it; nil when it can't.
 413    public var createID: ((CompletionItem) -> String?)?
 414    /// The text of the other open buffers, most recent first, for word completion.
 415    public var otherBuffers: () -> [String] = { [] }
 416    /// Effects other than messages, for the app to carry out.
 417    public var onEffect: ((Effect) -> Void)?
 418    /// Where paste looks for images and files; scripts checking the app set another.
 419    public static var pasteboard = NSPasteboard.general
 420    /// Files pasted or dropped at the caret; nil leaves them to the text view.
 421    public var onFiles: (([URL]) -> Void)?
 422    /// An image pasted or dropped at the caret, with its extension (`yank-media`).
 423    public var onImage: ((Data, String) -> Void)?
 424
 425    public var keymap: Keymap {
 426        get { dispatcher.keymap }
 427        set {
 428            dispatcher.keymap = newValue
 429            dispatcher.reset()
 430        }
 431    }
 432
 433    public var optionAsMeta: OptionAsMeta = [.left]
 434    /// Org options commands follow.
 435    public var options: EditingOptions = .org {
 436        didSet {
 437            if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
 438        }
 439    }
 440    /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
 441    /// `options`). Hidden markup shows on the caret's line, so it can be edited.
 442    public var showMarkup = true {
 443        didSet { if showMarkup != oldValue { restyleEverything() } }
 444    }
 445    /// Line numbers in a ruler beside the text.
 446    public var lineNumbersType = LineNumbersType.absolute {
 447        didSet { for view in orgTextViews { view.lineNumbersType = lineNumbersType } }
 448    }
 449    public var showLineNumbers = true {
 450        didSet { for view in orgTextViews { view.showsLineNumbers = showLineNumbers } }
 451    }
 452    var orgTextView: OrgTextView? { textView as? OrgTextView }
 453
 454    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
 455    var revealedLine: NSRange?
 456    var dispatcher: KeyDispatcher
 457    /// Evil-style editing, for modal keymaps such as Doom's.
 458    public var modal = false {
 459        didSet {
 460            guard modal != oldValue else { return }
 461            vim = Vim()
 462            dispatcher.mode = modal ? vim.mode.keymapMode : nil
 463            dispatcher.reset()
 464            updateCursor()
 465        }
 466    }
 467    var vim = Vim()
 468    /// The text and caret when insert state began, to know what was typed for `.`.
 469    var insertSnapshot: (text: String, caret: Int)?
 470    /// The evil cursor in visual states, where the selection's start isn't it.
 471    var visualCaret: Int?
 472    /// Vim's lowercase marks, mapped through edits.
 473    var vimMarks: [Character: Int] = [:]
 474    /// Uppercase marks, with the editor each is in: global, as evil's file marks are.
 475    static var fileMarks: [Character: (owner: WeakEditor, offset: Int)] = [:]
 476    /// Registers and keyboard macros, shared by every editor as evil's are global.
 477    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 478    static var vimClipboardRecord: (text: String, linewise: Bool)?
 479    static var macros: [Character: [KeyChord]] = [:]
 480    /// What `:`, `/` and `?` read, oldest first, for the command-line window (`q:`).
 481    static var promptHistory: [String: [String]] = [:]
 482    /// The last `:s`, for `&` and `g&`.
 483    static var lastSubstitute: (pattern: String, replacement: String, flags: String)?
 484    /// The file's path, for the `%` register.
 485    public var fileName: String?
 486    /// Shows `editor`'s buffer with the caret at the offset, for a jump to a file mark set
 487    /// there.
 488    public var onJumpToEditor: ((OrgEditor, Int) -> Void)?
 489    /// Jump positions, oldest first, mapped through edits; `jumpIndex` is where C-o and C-i are.
 490    var jumpList: [Int] = []
 491    var jumpIndex = 0
 492    /// The register keys go into while `q` records, and its keys so far.
 493    var recordingRegister: Character?
 494    var recordedKeys: [KeyChord] = []
 495    var replayingMacro = 0
 496    /// Keyboard macros: the keys left in the one being replayed, how deep replays are nested,
 497    /// the error that stops them, the key that runs the last one again right after (`e` after
 498    /// C-x e), and the keys of the command running, nil when a menu or the palette ran it.
 499    var macroKeys: [KeyChord] = []
 500    var kmacroDepth = 0
 501    var macroError: String?
 502    /// Work the last replayed key started, which the replay waits for.
 503    var macroWait: MacroWait?
 504    var macroRepeatKey: KeyChord?
 505    var commandKeys: [KeyChord]?
 506    /// Named macros (`macros.toml`).
 507    public var namedMacros = NamedMacros.shared
 508    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
 509    private(set) var markActive = false
 510    /// An incremental search in progress, and whether Vim's `/` or `?` started it.
 511    var isearch: ISearch?
 512    var isearchVim = false
 513    /// The last search string, for C-s C-s.
 514    static var lastISearch: String?
 515
 516    public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
 517        let selected = textView.selectedRange()
 518        return EditContext(
 519            revision: document.revision, text: document.text, tree: document.tree,
 520            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
 521            hidden: hidden.all, options: options, knownTags: knownTags,
 522            lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
 523        )
 524    }
 525
 526    /// Offers a key press to the keymap. False lets the text system have it.
 527    func handleKey(_ event: NSEvent) -> Bool {
 528        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
 529        return handleChord(chord)
 530    }
 531
 532    /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
 533    func handleChord(_ chord: KeyChord) -> Bool {
 534        if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
 535        if let key = macroRepeatKey {
 536            macroRepeatKey = nil
 537            if chord == key, dispatcher.pending.isEmpty, isearch == nil {
 538                callLastMacro(count: 1, repeatKey: key)
 539                return true
 540            }
 541        }
 542        if isearch != nil, isearchKey(chord) { return true }
 543        if let handled = completionKey(chord) { return handled }
 544        if let handled = snippetKey(chord) { return handled }
 545        if modal { return handleModal(chord) }
 546        switch dispatcher.feed(chord) {
 547        case .pending(let keys):
 548            let context = context()
 549            let next = keymap.continuations(of: keys) { runs($0, in: context) }.map { item in
 550                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.localizedTitle ?? $0 } ?? "+prefix")
 551            }
 552            onKeysPending?(KeySequence.format(keys), next)
 553            return true
 554        case .cancelled:
 555            onKeysPending?(nil, [])
 556            fail("Quit")
 557            return true
 558        case .undefined(let keys):
 559            onKeysPending?(nil, [])
 560            fail("\(KeySequence.format(keys)) is undefined")
 561            return true
 562        case .unbound:
 563            return snippetTab(chord) || electricPair(chord) || autoFill(chord)
 564        case .complete(let keys, let candidates):
 565            let argument = dispatcher.argument != nil
 566            if keys.count > 1 || argument { onKeysPending?(nil, []) }
 567            let context = context()
 568            let runnable = candidates.first { runs($0, in: context) }
 569            if let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) {
 570                // A prefix argument (C-u, C-u 3) counts keyboard macros only.
 571                if argument, !binding.command.hasPrefix("macro.") {
 572                    fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
 573                    return true
 574                }
 575                commandKeys = keys
 576                defer { commandKeys = nil }
 577                run(binding.command)
 578                return true
 579            }
 580            return keys.count == 1 && (snippetTab(chord) || electricPair(chord) || autoFill(chord))
 581        }
 582    }
 583
 584    /// `auto-fill-mode` for this buffer: the settings' unless toggled here.
 585    public var autoFillOverride: Bool?
 586    public var autoFills: Bool { isOrg && (autoFillOverride ?? options.autoFill) }
 587
 588    /// SPC with `auto-fill-mode`: true when it typed the space and filled the line.
 589    func autoFill(_ key: KeyChord) -> Bool {
 590        guard autoFills, key.key == "SPC", key.modifiers.isEmpty, !textView.hasMarkedText() else { return false }
 591        _ = perform(AutoFillSpace())
 592        return true
 593    }
 594
 595    func toggleAutoFill() {
 596        autoFillOverride = !autoFills
 597        onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
 598    }
 599
 600    /// `electric-pair-mode` for a key the keymap leaves to the text system: true when it
 601    /// typed the key itself.
 602    func electricPair(_ key: KeyChord) -> Bool {
 603        guard isOrg, options.electricPair, key.modifiers.isEmpty, !textView.hasMarkedText(),
 604              key.key == "DEL" || key.key == "RET" || ElectricPairKey.characters.contains(key.key) else { return false }
 605        let command = ElectricPairKey(key: key.key)
 606        guard command.applies(in: context()) else { return false }
 607        _ = perform(command)
 608        return true
 609    }
 610
 611    /// Whether a key's `binding` runs in `context`: its context holds and its command applies.
 612    private func runs(_ binding: KeyBinding, in context: EditContext) -> Bool {
 613        (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
 614    }
 615
 616    private func applies(_ id: String, in context: EditContext) -> Bool {
 617        if refuses(id) { return false }
 618        return switch EditorCommands.command(id)?.action {
 619        case .text(let command): command.applies(in: context)
 620        case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
 621        case .view where id.hasPrefix("org.snippet."): snippetSession != nil
 622        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: foldTree) != nil
 623            || Wrappers.toggleable(at: context.caret, in: foldTree) != nil
 624        case .edit, .mark, .app, .find: true
 625        case nil: true
 626        }
 627    }
 628
 629    /// Whether `id` is refused because the file isn't org: in Markdown only the fold commands
 630    /// of org's run, so none writes org into the file.
 631    func refuses(_ id: String) -> Bool {
 632        !isOrg && OrgOnlyCommands.refuses(id, markdown: isMarkdown, path: options.filePath)
 633    }
 634
 635    /// The file's structure for folding: the org tree, or for Markdown a tree of its headings.
 636    var foldTree: OrgTree { isMarkdown ? markdown.foldTree : document.tree }
 637
 638    /// The Markdown file's structure now.
 639    var markdown: MarkdownDocument {
 640        if let markdownCache, markdownCache.revision == document.revision { return markdownCache.document }
 641        let made = MarkdownDocument(document.text)
 642        markdownCache = (document.revision, made)
 643        return made
 644    }
 645
 646    /// The last command run and the revision it left, for `last-command`.
 647    var lastCommand: (id: String, revision: Int)?
 648
 649    /// Runs a command by id, as a key, a menu item or the palette would.
 650    public func run(_ id: String) {
 651        defer { lastCommand = (id, document.revision) }
 652        if let snippet = Snippets.command(id), isOrg {
 653            perform(snippet)
 654            return
 655        }
 656        guard let command = EditorCommands.command(id) else {
 657            fail("Unknown command \(id)")
 658            return
 659        }
 660        if refuses(id) {
 661            fail("Not an org file")
 662            return
 663        }
 664        // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
 665        if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
 666            clearHighlights()
 667            return
 668        }
 669        var keepMark = false
 670        switch command.action {
 671        case .text(let text):
 672            perform(text)
 673        case .view:
 674            switch id {
 675            case "org.cycle": cycleAtCaret()
 676            case "org.cycle-global": cycleGlobal()
 677            case _ where id.hasPrefix("org.fold."): fold(id)
 678            case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
 679            case "org.toggle-inline-images": toggleImages()
 680            case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
 681            case "org.latex-preview": toggleLatex()
 682            case "editor.toggle-spell-check": toggleSpellCheck()
 683            case "editor.complete": completeAtPoint()
 684            case "editor.dabbrev-expand": dabbrevExpand()
 685            case "editor.dabbrev-completion": completeWord(last: false)
 686            case "editor.dabbrev-completion-previous": completeWord(last: true)
 687            case "org.snippet.next-field": nextSnippetField()
 688            case "org.snippet.previous-field": previousSnippetField()
 689            case "editor.toggle-truncate-lines": toggleTruncateLines()
 690            case "editor.toggle-auto-fill": toggleAutoFill()
 691            case "edit.isearch-forward": startISearch(forward: true)
 692            case "edit.isearch-backward": startISearch(forward: false)
 693            case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
 694            case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
 695            case _ where id.hasPrefix("macro."): macroCommand(id)
 696            default: tableColumnWidth(id)
 697            }
 698        case .edit(let selector, let extending):
 699            let before = textView.selectedRange()
 700            if markActive, let extending {
 701                keepMark = true
 702                textView.doCommand(by: NSSelectorFromString(extending))
 703            } else {
 704                textView.doCommand(by: NSSelectorFromString(selector))
 705            }
 706            if kmacroDepth > 0 { checkMovement(id, from: before) }
 707        case .find(let action):
 708            let item = NSMenuItem()
 709            item.tag = action.rawValue
 710            textView.performTextFinderAction(item)
 711        case .mark:
 712            if id == "edit.set-mark" {
 713                let caret = textView.selectedRange().location
 714                textView.setSelectedRange(NSRange(location: caret, length: 0))
 715                keepMark = true
 716                onMessage?("Mark set")
 717            } else {
 718                let selected = textView.selectedRange()
 719                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
 720                onMessage?("Quit")
 721            }
 722        case .app:
 723            onAppCommand?(id)
 724        }
 725        markActive = keepMark
 726    }
 727
 728    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
 729    /// they form one undo step and reach the document through the same path.
 730    @discardableResult
 731    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
 732        let context = context(now: now, answers: answers)
 733        let step = command.run(in: context)
 734        switch step {
 735        case .commit(let result):
 736            guard textView.isEditable || result.edits.isEmpty else {
 737                fail("This file is read-only.")
 738                return .failed("read-only")
 739            }
 740            commandEditing = true
 741            applyEdits(result.edits)
 742            commandEditing = false
 743            if let selection = result.selection?.first {
 744                if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
 745                setCaret(selection.lowerBound)
 746                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
 747            }
 748            for effect in result.effects {
 749                switch effect {
 750                case .message(let text): onMessage?(text)
 751                case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
 752                case .fold(let start):
 753                    var state = foldState
 754                    state.folds.insert(start)
 755                    setFolds(state)
 756                case .snippet(let session): startSnippet(session)
 757                default: onEffect?(effect)
 758                }
 759            }
 760        case .failed(let message):
 761            fail(message)
 762        case .external(.userCommand(let request)) where onUserCommand != nil:
 763            let wait = kmacroDepth > 0 ? MacroWait() : nil
 764            macroWait = wait
 765            onUserCommand?(request) { wait?.finish($0) }
 766        case .external(let request):
 767            if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) }
 768        case .prompt(let prompt):
 769            ask(prompt) { [weak self] answer in
 770                guard let self else { return }
 771                guard let answer else {
 772                    self.onMessage?("Quit")
 773                    return
 774                }
 775                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
 776            }
 777        }
 778        return step
 779    }
 780
 781    // MARK: - Disk
 782
 783    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
 784    /// its headings.
 785    @discardableResult
 786    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
 787        update { $0.diskChanged(to: bytes) }
 788    }
 789
 790    // MARK: - Folding
 791
 792    var globalVisibility: GlobalVisibility?
 793    /// What each folded drawer and block hides, by opening-line start; kept in step with
 794    /// `view.wrapperFolds` and mapped through edits.
 795    var wrapperHidden: [Int: Range<Int>] = [:]
 796
 797    // MARK: - Sparse trees
 798
 799    /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
 800    /// fold change. Mapped through edits.
 801    var sparseHidden: [Range<Int>]?
 802    /// Sparse tree matches, highlighted until the next edit or C-c C-c.
 803    var highlights: [Range<Int>] = []
 804
 805    // MARK: - STARTUP display
 806
 807    /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
 808    var indented = true
 809    /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
 810    var hideStars = false
 811
 812    // MARK: - Inline images
 813
 814    /// `org-toggle-inline-images`: image links show their image.
 815    public internal(set) var showsImages = false
 816    /// Links with a description show their image too.
 817    var imagesIncludeLinked = false
 818    /// The width images were last sized for, and whether sizing them again is waiting.
 819    var imageWidth: CGFloat = 0
 820    var fittingImages = false
 821    /// The text width heading tag gaps were last drawn for, and whether drawing them again is waiting.
 822    var tagGapWidth: CGFloat = 0
 823    var fittingTagGaps = false
 824    /// `org-latex-preview`: LaTeX fragments show as typeset math.
 825    public internal(set) var showsLatex = false
 826    /// An `attachment:` link's file, from its name, offset and the tree: the app's
 827    /// `org-attach-expand`. Nil leaves those links as text.
 828    public var attachmentPath: ((String, Int, OrgTree) -> String?)?
 829    /// The file's folder, for relative image paths.
 830    public var baseDirectory: URL? {
 831        didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
 832    }
 833
 834    // MARK: - Narrowing
 835
 836    /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
 837    /// rest is hidden until `widen`. Mapped through edits.
 838    public internal(set) var narrowed: Range<Int>?
 839
 840    // MARK: - Shrunk table columns
 841
 842    /// Narrowed table columns (`org-table-shrink`).
 843    var shrunk = ShrunkColumns()
 844    private var commandEditing = false
 845
 846    // MARK: - Editing
 847
 848    private var blockCheck: DispatchWorkItem?
 849
 850    /// Looks for blocks over the whole file once typing pauses, catching what moving the
 851    /// ranges can't see (a block's end found far away).
 852    private func scheduleBlockCheck() {
 853        blockCheck?.cancel()
 854        let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
 855        blockCheck = work
 856        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
 857    }
 858
 859    func settleBlocks() {
 860        blockCheck?.cancel()
 861        guard isOrg || isMarkdown else { return }
 862        let blocks = isMarkdown ? markdown.structure.blocks : Presentation.shadedBlocks(document.tree)
 863        guard blocks != shaded.all else { return }
 864        let old = shaded.all
 865        shaded.set(blocks)
 866        invalidateLayout(from: old, to: blocks)
 867    }
 868
 869    fileprivate func storageEdited(range: NSRange, delta: Int) {
 870        guard !isLoading, let storage = textView.textStorage else { return }
 871        markActive = false
 872        let clock = ContinuousClock()
 873        let start = clock.now
 874        let replacement = (storage.string as NSString).substring(with: range)
 875        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
 876        let oldText = document.text as NSString
 877        let newText = storage.string as NSString
 878        let newEnd = edit.range.lowerBound + replacement.utf16.count
 879        let oldTree = document.tree
 880        let oldMarkdown = isMarkdown ? markdown : nil
 881        do {
 882            try document.apply([edit], baseRevision: document.revision)
 883            if let oldMarkdown { markdownCache = (document.revision, oldMarkdown.applying(edit)) }
 884        } catch {
 885            assertionFailure("text view and document disagree: \(error)")
 886            return
 887        }
 888        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
 889        // edited line when the edit reaches into unstyled text.
 890        styled.map(through: edit, in: newText)
 891        let oldHidden = hidden.all
 892        var affected = isMarkdown
 893            ? Presentation.markdownRestyleRange(for: edit, oldBlocks: oldMarkdown?.structure.blocks ?? [], new: markdown, newText: newText)
 894            : Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
 895        // A fence opened or closed far up restyles what follows in the background passes.
 896        if isMarkdown, affected.count > Self.styleChunk {
 897            let lines = newText.lineRange(for: NSRange(location: edit.range.lowerBound, length: newEnd - edit.range.lowerBound))
 898            styled.unstyle(from: NSMaxRange(lines))
 899            affected = affected.lowerBound..<NSMaxRange(lines)
 900            scheduleStyling()
 901        }
 902        view = pruned(view.mapped(through: [edit]))
 903        mapWrapperFolds(through: edit, near: affected)
 904        if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
 905        mapVimPositions(through: edit)
 906        vim.changed(edit)
 907        snippetEdited(edit)
 908        if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
 909        let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
 910        highlights = []
 911        updateHidden()
 912        restyle(affected.lowerBound..<min(affected.upperBound, newText.length), in: storage)
 913        for table in shrunk.map(through: edit, in: storage.string, command: commandEditing) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
 914        for range in oldHighlights where range.upperBound <= newText.length {
 915            let lines = newText.lineRange(for: NSRange(range))
 916            restyle(lines.location..<NSMaxRange(lines), in: storage)
 917        }
 918        let oldShaded = shaded.all
 919        if isOrg {
 920            // Walking the tree for blocks costs more than typing; only an edit on a line that
 921            // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
 922            if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
 923                shaded.set(Presentation.shadedBlocks(document.tree))
 924            } else {
 925                shaded.set(oldShaded.map { mapRange($0, through: edit) })
 926            }
 927            scheduleBlockCheck()
 928        } else if isMarkdown {
 929            shaded.set(markdown.structure.blocks)
 930        }
 931        invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
 932        invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
 933        onEditTiming?(clock.now - start)
 934        let lineCount = lines.lineCount
 935        lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
 936        for view in orgTextViews {
 937            if lines.lineCount != lineCount { view.updateGutter() }
 938            view.redrawLineNumbers()
 939        }
 940        onChange?()
 941    }
 942
 943    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
 944        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
 945        return mapped
 946    }
 947
 948    /// Shaded block lines the old or new selection covers are drawn again, as they draw the
 949    /// selection over their band.
 950    private func redrawShadedSelection(_ selection: NSRange) {
 951        defer { previousSelectionRange = selection }
 952        redrawShaded([previousSelectionRange, selection])
 953    }
 954
 955    private func redrawShaded(_ ranges: [NSRange]) {
 956        let manager = textContentStorage
 957        for old in ranges where old.length > 0 {
 958            for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
 959                let lower = max(block.lowerBound, old.location)
 960                let upper = min(block.upperBound, NSMaxRange(old))
 961                guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
 962                      let end = manager.location(start, offsetBy: upper - lower),
 963                      let range = NSTextRange(location: start, end: end) else { continue }
 964                for layout in layoutManagers { layout.invalidateLayout(for: range) }
 965            }
 966        }
 967    }
 968
 969    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
 970    /// back jumps to the end of the heading line.
 971    func selectionChanged() {
 972        // Replacing the text moves the caret while the folds are still the old text's; the
 973        // loader sets the caret afterwards.
 974        guard !isLoading else { return }
 975        let selection = textView.selectedRange()
 976        defer { previousSelection = selection.location }
 977        snippetSelectionChanged()
 978        redrawShadedSelection(selection)
 979        onSelectionChange?(selection)
 980        revealCaretLine()
 981        orgTextView?.redrawLineNumbers()
 982        // Narrowing keeps the caret in the region.
 983        if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
 984            setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
 985            return
 986        }
 987        // A selection reaching into folded text, as a find match does, unfolds it.
 988        if selection.length > 0 {
 989            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
 990                unfold(around: selection.location)
 991                unfold(around: NSMaxRange(selection) - 1)
 992            }
 993            return
 994        }
 995        guard let range = hidden.containing(selection.location) else { return }
 996        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
 997    }
 998}
 999
1000extension OrgEditor: DocumentBuffer {
1001    /// The selected text, for capture's `%i`.
1002    public var selectedText: String {
1003        let range = textView.selectedRange()
1004        guard range.length > 0 else { return "" }
1005        return (textView.string as NSString).substring(with: range)
1006    }
1007
1008    public var selection: [Range<Int>] {
1009        let selected = textView.selectedRange()
1010        return [selected.location..<NSMaxRange(selected)]
1011    }
1012
1013    /// Runs `change`; if it changed the text, reloads the views with folds and each view's
1014    /// selection mapped through the change. Undo refers to the old text, so it is cleared.
1015    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1016        let before = document.text
1017        let defaultsBefore = document.defaults
1018        let selections = textViews.map(\.selectedRange)
1019        let result = try change(&document)
1020        if document.text != before {
1021            let edits = lineEdits(from: before, to: document.text)
1022            var state = view
1023            state.selection = selections.map { $0.location..<NSMaxRange($0) }
1024            let mapped = state.mapped(through: edits)
1025            // Shrunk columns were measured on the old text.
1026            shrunk = ShrunkColumns()
1027            load(document.text)
1028            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1029            for (view, selection) in zip(textViews, mapped.selection) {
1030                if view === active { setCaret(selection.lowerBound) } else { view.setSelectedRange(NSRange(location: selection.lowerBound, length: 0)) }
1031                if !selection.isEmpty { view.setSelectedRange(NSRange(selection)) }
1032            }
1033            undoManager.removeAllActions()
1034        } else if document.defaults != defaultsBefore {
1035            // New settings for the same text: TODO keywords may color differently.
1036            restyleEverything()
1037        }
1038        onChange?()
1039        return result
1040    }
1041}
1042
1043extension OrgEditor: NSTextStorageDelegate {
1044    public nonisolated func textStorage(
1045        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1046    ) {
1047        MainActor.assumeIsolated { storageGeneration += 1 }
1048        guard editedMask.contains(.editedCharacters) else { return }
1049        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1050    }
1051}
1052
1053extension OrgEditor: NSTextContentStorageDelegate {
1054    /// Folded text isn't enumerated, so it isn't laid out or drawn.
1055    public nonisolated func textContentManager(
1056        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1057    ) -> Bool {
1058        guard let range = textElement.elementRange else { return true }
1059        let documentStart = textContentManager.documentRange.location
1060        let start = textContentManager.offset(from: documentStart, to: range.location)
1061        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1062        return !hidden.covers(start, end)
1063    }
1064}
1065
1066extension OrgEditor: NSTextLayoutManagerDelegate {
1067    public nonisolated func textLayoutManager(
1068        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1069    ) -> NSTextLayoutFragment {
1070        let range = textElement.elementRange
1071        if let range, let manager = textLayoutManager.textContentManager {
1072            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1073            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1074            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1075            if let paragraph = textElement as? NSTextParagraph, ImageFragment.hasImages(paragraph.attributedString) {
1076                return ImageFragment(textElement: textElement, range: range)
1077            }
1078            if let paragraph = textElement as? NSTextParagraph, LatexFragment.hasLatex(paragraph.attributedString) {
1079                return LatexFragment(textElement: textElement, range: range)
1080            }
1081            if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1082                return EntityFragment(textElement: textElement, range: range)
1083            }
1084        }
1085        return NSTextLayoutFragment(textElement: textElement, range: range)
1086    }
1087}
1088#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form