Sources/OrgEditorAppKit/OrgEditor.swift

980 lines · 46532 bytes

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