Sources/OrgEditorAppKit/OrgEditor.swift

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