Sources/OrgEditorAppKit/OrgEditor.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift history · blame · raw

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