Sources/OrgEditorAppKit/OrgEditor.swift

15d73b1f0d2ee9cac84fe463bbeaf4b409d8f9fb
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

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

Global

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

Repository & editor

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