Sources/OrgEditorAppKit/OrgEditor.swift

9c8e4f9667c239dbcda0a122d127aa0620db4d35
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

1006 lines · 46960 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    /// Keyboard macros: the keys left in the one being replayed, how deep replays are nested,
 465    /// the error that stops them, the key that runs the last one again right after (`e` after
 466    /// C-x e), and the keys of the command running, nil when a menu or the palette ran it.
 467    var macroKeys: [KeyChord] = []
 468    var kmacroDepth = 0
 469    var macroError: String?
 470    var macroRepeatKey: KeyChord?
 471    var commandKeys: [KeyChord]?
 472    /// Named macros (`macros.toml`).
 473    public var namedMacros = NamedMacros.shared
 474    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
 475    private(set) var markActive = false
 476    /// An incremental search in progress, and whether Vim's `/` or `?` started it.
 477    var isearch: ISearch?
 478    var isearchVim = false
 479    /// The last search string, for C-s C-s.
 480    static var lastISearch: String?
 481
 482    public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
 483        let selected = textView.selectedRange()
 484        return EditContext(
 485            revision: document.revision, text: document.text, tree: document.tree,
 486            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
 487            hidden: hidden.all, options: options, knownTags: knownTags,
 488            lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
 489        )
 490    }
 491
 492    /// Offers a key press to the keymap. False lets the text system have it.
 493    func handleKey(_ event: NSEvent) -> Bool {
 494        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
 495        return handleChord(chord)
 496    }
 497
 498    /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
 499    func handleChord(_ chord: KeyChord) -> Bool {
 500        if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
 501        if let key = macroRepeatKey {
 502            macroRepeatKey = nil
 503            if chord == key, dispatcher.pending.isEmpty, isearch == nil {
 504                callLastMacro(count: 1, repeatKey: key)
 505                return true
 506            }
 507        }
 508        if isearch != nil, isearchKey(chord) { return true }
 509        if let handled = completionKey(chord) { return handled }
 510        if modal { return handleModal(chord) }
 511        switch dispatcher.feed(chord) {
 512        case .pending(let keys):
 513            let context = context()
 514            let next = keymap.continuations(of: keys) { runs($0, in: context) }.map { item in
 515                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.localizedTitle ?? $0 } ?? "+prefix")
 516            }
 517            onKeysPending?(KeySequence.format(keys), next)
 518            return true
 519        case .cancelled:
 520            onKeysPending?(nil, [])
 521            fail("Quit")
 522            return true
 523        case .undefined(let keys):
 524            onKeysPending?(nil, [])
 525            fail("\(KeySequence.format(keys)) is undefined")
 526            return true
 527        case .unbound:
 528            return electricPair(chord) || autoFill(chord)
 529        case .complete(let keys, let candidates):
 530            let argument = dispatcher.argument != nil
 531            if keys.count > 1 || argument { onKeysPending?(nil, []) }
 532            let context = context()
 533            let runnable = candidates.first { runs($0, in: context) }
 534            if let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) {
 535                // A prefix argument (C-u, C-u 3) counts keyboard macros only.
 536                if argument, !binding.command.hasPrefix("macro.") {
 537                    fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
 538                    return true
 539                }
 540                commandKeys = keys
 541                defer { commandKeys = nil }
 542                run(binding.command)
 543                return true
 544            }
 545            return keys.count == 1 && (electricPair(chord) || autoFill(chord))
 546        }
 547    }
 548
 549    /// `auto-fill-mode` for this buffer: the settings' unless toggled here.
 550    public var autoFillOverride: Bool?
 551    public var autoFills: Bool { isOrg && (autoFillOverride ?? options.autoFill) }
 552
 553    /// SPC with `auto-fill-mode`: true when it typed the space and filled the line.
 554    func autoFill(_ key: KeyChord) -> Bool {
 555        guard autoFills, key.key == "SPC", key.modifiers.isEmpty, !textView.hasMarkedText() else { return false }
 556        _ = perform(AutoFillSpace())
 557        return true
 558    }
 559
 560    func toggleAutoFill() {
 561        autoFillOverride = !autoFills
 562        onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
 563    }
 564
 565    /// `electric-pair-mode` for a key the keymap leaves to the text system: true when it
 566    /// typed the key itself.
 567    func electricPair(_ key: KeyChord) -> Bool {
 568        guard isOrg, options.electricPair, key.modifiers.isEmpty, !textView.hasMarkedText(),
 569              key.key == "DEL" || key.key == "RET" || ElectricPairKey.characters.contains(key.key) else { return false }
 570        let command = ElectricPairKey(key: key.key)
 571        guard command.applies(in: context()) else { return false }
 572        _ = perform(command)
 573        return true
 574    }
 575
 576    /// Whether a key's `binding` runs in `context`: its context holds and its command applies.
 577    private func runs(_ binding: KeyBinding, in context: EditContext) -> Bool {
 578        (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
 579    }
 580
 581    private func applies(_ id: String, in context: EditContext) -> Bool {
 582        if !isOrg, id.hasPrefix("org.") { return false }
 583        return switch EditorCommands.command(id)?.action {
 584        case .text(let command): command.applies(in: context)
 585        case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
 586        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
 587            || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
 588        case .edit, .mark, .app, .find: true
 589        case nil: true
 590        }
 591    }
 592
 593    /// The last command run and the revision it left, for `last-command`.
 594    private var lastCommand: (id: String, revision: Int)?
 595
 596    /// Runs a command by id, as a key, a menu item or the palette would.
 597    public func run(_ id: String) {
 598        defer { lastCommand = (id, document.revision) }
 599        guard let command = EditorCommands.command(id) else {
 600            fail("Unknown command \(id)")
 601            return
 602        }
 603        if !isOrg, id.hasPrefix("org.") {
 604            fail("Not an org file")
 605            return
 606        }
 607        // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
 608        if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
 609            clearHighlights()
 610            return
 611        }
 612        var keepMark = false
 613        switch command.action {
 614        case .text(let text):
 615            perform(text)
 616        case .view:
 617            switch id {
 618            case "org.cycle": cycleAtCaret()
 619            case "org.cycle-global": cycleGlobal()
 620            case _ where id.hasPrefix("org.fold."): fold(id)
 621            case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
 622            case "org.toggle-inline-images": toggleImages()
 623            case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
 624            case "org.latex-preview": toggleLatex()
 625            case "editor.toggle-spell-check": toggleSpellCheck()
 626            case "editor.complete": completeAtPoint()
 627            case "editor.toggle-truncate-lines": toggleTruncateLines()
 628            case "editor.toggle-auto-fill": toggleAutoFill()
 629            case "edit.isearch-forward": startISearch(forward: true)
 630            case "edit.isearch-backward": startISearch(forward: false)
 631            case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
 632            case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
 633            case _ where id.hasPrefix("macro."): macroCommand(id)
 634            default: tableColumnWidth(id)
 635            }
 636        case .edit(let selector, let extending):
 637            let before = textView.selectedRange()
 638            if markActive, let extending {
 639                keepMark = true
 640                textView.doCommand(by: NSSelectorFromString(extending))
 641            } else {
 642                textView.doCommand(by: NSSelectorFromString(selector))
 643            }
 644            if kmacroDepth > 0 { checkMovement(id, from: before) }
 645        case .find(let action):
 646            let item = NSMenuItem()
 647            item.tag = action.rawValue
 648            textView.performTextFinderAction(item)
 649        case .mark:
 650            if id == "edit.set-mark" {
 651                let caret = textView.selectedRange().location
 652                textView.setSelectedRange(NSRange(location: caret, length: 0))
 653                keepMark = true
 654                onMessage?("Mark set")
 655            } else {
 656                let selected = textView.selectedRange()
 657                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
 658                onMessage?("Quit")
 659            }
 660        case .app:
 661            onAppCommand?(id)
 662        }
 663        markActive = keepMark
 664    }
 665
 666    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
 667    /// they form one undo step and reach the document through the same path.
 668    @discardableResult
 669    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
 670        let context = context(now: now, answers: answers)
 671        let step = command.run(in: context)
 672        switch step {
 673        case .commit(let result):
 674            guard textView.isEditable || result.edits.isEmpty else {
 675                fail("This file is read-only.")
 676                return .failed("read-only")
 677            }
 678            commandEditing = true
 679            applyEdits(result.edits)
 680            commandEditing = false
 681            if let selection = result.selection?.first {
 682                if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
 683                setCaret(selection.lowerBound)
 684                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
 685            }
 686            for effect in result.effects {
 687                switch effect {
 688                case .message(let text): onMessage?(text)
 689                case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
 690                case .fold(let start):
 691                    var state = foldState
 692                    state.folds.insert(start)
 693                    setFolds(state)
 694                default: onEffect?(effect)
 695                }
 696            }
 697        case .failed(let message):
 698            fail(message)
 699        case .external(let request):
 700            if let onExternal { onExternal(request) } else { onMessage?(EmacsFallback.wording("This needs Emacs, which isn't available here.", "This isn't available here.")) }
 701        case .prompt(let prompt):
 702            ask(prompt) { [weak self] answer in
 703                guard let self else { return }
 704                guard let answer else {
 705                    self.onMessage?("Quit")
 706                    return
 707                }
 708                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
 709            }
 710        }
 711        return step
 712    }
 713
 714    // MARK: - Disk
 715
 716    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
 717    /// its headings.
 718    @discardableResult
 719    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
 720        update { $0.diskChanged(to: bytes) }
 721    }
 722
 723    // MARK: - Folding
 724
 725    var globalVisibility: GlobalVisibility?
 726    /// What each folded drawer and block hides, by opening-line start; kept in step with
 727    /// `view.wrapperFolds` and mapped through edits.
 728    var wrapperHidden: [Int: Range<Int>] = [:]
 729
 730    // MARK: - Sparse trees
 731
 732    /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
 733    /// fold change. Mapped through edits.
 734    var sparseHidden: [Range<Int>]?
 735    /// Sparse tree matches, highlighted until the next edit or C-c C-c.
 736    var highlights: [Range<Int>] = []
 737
 738    // MARK: - STARTUP display
 739
 740    /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
 741    var indented = true
 742    /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
 743    var hideStars = false
 744
 745    // MARK: - Inline images
 746
 747    /// `org-toggle-inline-images`: image links show their image.
 748    public internal(set) var showsImages = false
 749    /// Links with a description show their image too.
 750    var imagesIncludeLinked = false
 751    /// The width images were last sized for, and whether sizing them again is waiting.
 752    var imageWidth: CGFloat = 0
 753    var fittingImages = false
 754    /// The text width heading tag gaps were last drawn for, and whether drawing them again is waiting.
 755    var tagGapWidth: CGFloat = 0
 756    var fittingTagGaps = false
 757    /// `org-latex-preview`: LaTeX fragments show as typeset math.
 758    public internal(set) var showsLatex = false
 759    /// An `attachment:` link's file, from its name, offset and the tree: the app's
 760    /// `org-attach-expand`. Nil leaves those links as text.
 761    public var attachmentPath: ((String, Int, OrgTree) -> String?)?
 762    /// The file's folder, for relative image paths.
 763    public var baseDirectory: URL? {
 764        didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
 765    }
 766
 767    // MARK: - Narrowing
 768
 769    /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
 770    /// rest is hidden until `widen`. Mapped through edits.
 771    public internal(set) var narrowed: Range<Int>?
 772
 773    // MARK: - Shrunk table columns
 774
 775    /// Narrowed table columns (`org-table-shrink`).
 776    var shrunk = ShrunkColumns()
 777    private var commandEditing = false
 778
 779    // MARK: - Editing
 780
 781    private var blockCheck: DispatchWorkItem?
 782
 783    /// Looks for blocks over the whole file once typing pauses, catching what moving the
 784    /// ranges can't see (a block's end found far away).
 785    private func scheduleBlockCheck() {
 786        blockCheck?.cancel()
 787        let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
 788        blockCheck = work
 789        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
 790    }
 791
 792    func settleBlocks() {
 793        blockCheck?.cancel()
 794        guard isOrg else { return }
 795        let blocks = Presentation.shadedBlocks(document.tree)
 796        guard blocks != shaded.all else { return }
 797        let old = shaded.all
 798        shaded.set(blocks)
 799        invalidateLayout(from: old, to: blocks)
 800    }
 801
 802    fileprivate func storageEdited(range: NSRange, delta: Int) {
 803        guard !isLoading, let storage = textView.textStorage else { return }
 804        markActive = false
 805        let clock = ContinuousClock()
 806        let start = clock.now
 807        let replacement = (storage.string as NSString).substring(with: range)
 808        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
 809        let oldText = document.text as NSString
 810        let newText = storage.string as NSString
 811        let newEnd = edit.range.lowerBound + replacement.utf16.count
 812        let oldTree = document.tree
 813        do {
 814            try document.apply([edit], baseRevision: document.revision)
 815        } catch {
 816            assertionFailure("text view and document disagree: \(error)")
 817            return
 818        }
 819        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
 820        // edited line when the edit reaches into unstyled text.
 821        styled.map(through: edit, in: newText)
 822        let oldHidden = hidden.all
 823        let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
 824        view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
 825        mapWrapperFolds(through: edit, near: affected)
 826        if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
 827        mapVimPositions(through: edit)
 828        vim.changed(edit)
 829        if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
 830        let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
 831        highlights = []
 832        updateHidden()
 833        restyle(affected.lowerBound..<min(affected.upperBound, newText.length), in: storage)
 834        for table in shrunk.map(through: edit, in: storage.string, command: commandEditing) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
 835        for range in oldHighlights where range.upperBound <= newText.length {
 836            let lines = newText.lineRange(for: NSRange(range))
 837            restyle(lines.location..<NSMaxRange(lines), in: storage)
 838        }
 839        let oldShaded = shaded.all
 840        if isOrg {
 841            // Walking the tree for blocks costs more than typing; only an edit on a line that
 842            // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
 843            if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
 844                shaded.set(Presentation.shadedBlocks(document.tree))
 845            } else {
 846                shaded.set(oldShaded.map { mapRange($0, through: edit) })
 847            }
 848            scheduleBlockCheck()
 849        }
 850        invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
 851        invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
 852        onEditTiming?(clock.now - start)
 853        let lineCount = lines.lineCount
 854        lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
 855        for view in orgTextViews {
 856            if lines.lineCount != lineCount { view.updateGutter() }
 857            view.redrawLineNumbers()
 858        }
 859        onChange?()
 860    }
 861
 862    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
 863        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
 864        return mapped
 865    }
 866
 867    /// Shaded block lines the old or new selection covers are drawn again, as they draw the
 868    /// selection over their band.
 869    private func redrawShadedSelection(_ selection: NSRange) {
 870        defer { previousSelectionRange = selection }
 871        redrawShaded([previousSelectionRange, selection])
 872    }
 873
 874    private func redrawShaded(_ ranges: [NSRange]) {
 875        let manager = textContentStorage
 876        for old in ranges where old.length > 0 {
 877            for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
 878                let lower = max(block.lowerBound, old.location)
 879                let upper = min(block.upperBound, NSMaxRange(old))
 880                guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
 881                      let end = manager.location(start, offsetBy: upper - lower),
 882                      let range = NSTextRange(location: start, end: end) else { continue }
 883                for layout in layoutManagers { layout.invalidateLayout(for: range) }
 884            }
 885        }
 886    }
 887
 888    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
 889    /// back jumps to the end of the heading line.
 890    func selectionChanged() {
 891        // Replacing the text moves the caret while the folds are still the old text's; the
 892        // loader sets the caret afterwards.
 893        guard !isLoading else { return }
 894        let selection = textView.selectedRange()
 895        defer { previousSelection = selection.location }
 896        redrawShadedSelection(selection)
 897        onSelectionChange?(selection)
 898        revealCaretLine()
 899        orgTextView?.redrawLineNumbers()
 900        // Narrowing keeps the caret in the region.
 901        if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
 902            setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
 903            return
 904        }
 905        // A selection reaching into folded text, as a find match does, unfolds it.
 906        if selection.length > 0 {
 907            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
 908                unfold(around: selection.location)
 909                unfold(around: NSMaxRange(selection) - 1)
 910            }
 911            return
 912        }
 913        guard let range = hidden.containing(selection.location) else { return }
 914        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
 915    }
 916}
 917
 918extension OrgEditor: DocumentBuffer {
 919    /// The selected text, for capture's `%i`.
 920    public var selectedText: String {
 921        let range = textView.selectedRange()
 922        guard range.length > 0 else { return "" }
 923        return (textView.string as NSString).substring(with: range)
 924    }
 925
 926    public var selection: [Range<Int>] {
 927        let selected = textView.selectedRange()
 928        return [selected.location..<NSMaxRange(selected)]
 929    }
 930
 931    /// Runs `change`; if it changed the text, reloads the views with folds and each view's
 932    /// selection mapped through the change. Undo refers to the old text, so it is cleared.
 933    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
 934        let before = document.text
 935        let defaultsBefore = document.defaults
 936        let selections = textViews.map(\.selectedRange)
 937        let result = try change(&document)
 938        if document.text != before {
 939            let edits = lineEdits(from: before, to: document.text)
 940            var state = view
 941            state.selection = selections.map { $0.location..<NSMaxRange($0) }
 942            let mapped = state.mapped(through: edits)
 943            // Shrunk columns were measured on the old text.
 944            shrunk = ShrunkColumns()
 945            load(document.text)
 946            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
 947            for (view, selection) in zip(textViews, mapped.selection) {
 948                if view === active { setCaret(selection.lowerBound) } else { view.setSelectedRange(NSRange(location: selection.lowerBound, length: 0)) }
 949                if !selection.isEmpty { view.setSelectedRange(NSRange(selection)) }
 950            }
 951            undoManager.removeAllActions()
 952        } else if document.defaults != defaultsBefore {
 953            // New settings for the same text: TODO keywords may color differently.
 954            restyleEverything()
 955        }
 956        onChange?()
 957        return result
 958    }
 959}
 960
 961extension OrgEditor: NSTextStorageDelegate {
 962    public nonisolated func textStorage(
 963        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
 964    ) {
 965        MainActor.assumeIsolated { storageGeneration += 1 }
 966        guard editedMask.contains(.editedCharacters) else { return }
 967        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
 968    }
 969}
 970
 971extension OrgEditor: NSTextContentStorageDelegate {
 972    /// Folded text isn't enumerated, so it isn't laid out or drawn.
 973    public nonisolated func textContentManager(
 974        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
 975    ) -> Bool {
 976        guard let range = textElement.elementRange else { return true }
 977        let documentStart = textContentManager.documentRange.location
 978        let start = textContentManager.offset(from: documentStart, to: range.location)
 979        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
 980        return !hidden.covers(start, end)
 981    }
 982}
 983
 984extension OrgEditor: NSTextLayoutManagerDelegate {
 985    public nonisolated func textLayoutManager(
 986        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
 987    ) -> NSTextLayoutFragment {
 988        let range = textElement.elementRange
 989        if let range, let manager = textLayoutManager.textContentManager {
 990            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
 991            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
 992            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
 993            if let paragraph = textElement as? NSTextParagraph, ImageFragment.hasImages(paragraph.attributedString) {
 994                return ImageFragment(textElement: textElement, range: range)
 995            }
 996            if let paragraph = textElement as? NSTextParagraph, LatexFragment.hasLatex(paragraph.attributedString) {
 997                return LatexFragment(textElement: textElement, range: range)
 998            }
 999            if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1000                return EntityFragment(textElement: textElement, range: range)
1001            }
1002        }
1003        return NSTextLayoutFragment(textElement: textElement, range: range)
1004    }
1005}
1006#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