Sources/OrgCore/Keymap/Vim.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Keymap/Vim.swift history · blame · raw

226 lines · 9984 bytes

  1import Foundation
  2
  3/// Modal editing as Doom's evil gives it: normal, insert, visual and visual-line states;
  4/// counts, registers, operators with motions and text objects, `.` repeat, evil-snipe's `s`
  5/// and `S`, `Y` to the end of the line, and the unnamed register on the system clipboard.
  6/// Keys go in; edits, moves and commands come out for the editor to apply.
  7public struct Vim: Sendable {
  8    public enum Mode: String, Sendable {
  9        case normal, insert, visual
 10        case visualLine = "visual-line"
 11        case visualBlock = "visual-block"
 12        case replace
 13
 14        /// The keymap mode name for bindings.
 15        public var keymapMode: String {
 16            switch self {
 17            case .normal: "normal"
 18            case .insert, .replace: "insert"
 19            case .visual, .visualLine, .visualBlock: "visual"
 20            }
 21        }
 22    }
 23
 24    public enum Action: Equatable, Sendable {
 25        /// Replace text and put the caret (and, in visual states, the selection) somewhere.
 26        case edit([TextEdit], caret: Int)
 27        case move(caret: Int)
 28        /// The selection to show in a visual state, `lowerBound..<upperBound`.
 29        case select(Range<Int>)
 30        case command(String)
 31        case undo(Int)
 32        case redo(Int)
 33        case setClipboard(String)
 34        /// Ask for a search pattern (`/`, `?`) or an ex command (`:`).
 35        case prompt(String)
 36        /// `gq` and `gw`: fill these lines' paragraphs (`FillRegion`); the caret stays at
 37        /// `keep`, or without it goes to the last line's first non-blank.
 38        case fill(Range<Int>, keep: Int?)
 39        /// An ex command to run, as if typed after `:` (`ZZ` is `:wq`, `ZQ` is `:q!`).
 40        case ex(String)
 41        case message(String)
 42        /// `m`: a mark at this offset, for the editor to keep through edits.
 43        case setMark(Character, Int)
 44        /// A jump left this offset: the editor adds it to the jump list.
 45        case jumped(from: Int)
 46        /// C-o and C-i through the jump list.
 47        case jumpBack(Int)
 48        case jumpForward(Int)
 49        /// `q`: start recording keys into a register, or with nil stop.
 50        case recordMacro(Character?)
 51        /// `@`: play a register's keys, this many times.
 52        case playMacro(Character, Int)
 53        /// A block selection: one range per line.
 54        case selectBlock([Range<Int>])
 55        /// `gj`, `gk`: down (or, negative, up) by screen lines, which only the editor knows.
 56        case visualLines(Int)
 57        /// `zz`, `zt`, `zb`: scroll the caret's line to the window's middle, top or bottom.
 58        case scroll(ScrollLine)
 59        /// `q:`, `q/`, `q?`: the command-line window, the earlier commands or searches to pick
 60        /// from and edit.
 61        case commandWindow(String)
 62    }
 63
 64    public struct Context: Sendable {
 65        public var text: String
 66        public var caret: Int
 67        public var clipboard: String?
 68        /// Lines in a half page, for C-d and C-u.
 69        public var halfPage: Int
 70        /// Marks where the editor keeps them now; `'` and `` ` `` are the last jump's start.
 71        public var marks: [Character: Int]
 72        /// The text the window shows, for H, M and L; nil when unknown.
 73        public var visible: Range<Int>?
 74        /// An Org buffer, where evil-org's keys apply.
 75        public var org: Bool
 76
 77        public init(text: String, caret: Int, clipboard: String? = nil, halfPage: Int = 15, marks: [Character: Int] = [:], visible: Range<Int>? = nil, org: Bool = false) {
 78            self.org = org
 79            self.text = text
 80            self.caret = caret
 81            self.clipboard = clipboard
 82            self.halfPage = halfPage
 83            self.marks = marks
 84            self.visible = visible
 85        }
 86    }
 87
 88    public internal(set) var mode: Mode = .normal
 89    /// Keys of the command being typed.
 90    public internal(set) var pending: [KeyChord] = []
 91    /// Named registers. Evil's are global: an editor with several engines shares them.
 92    public var registers: [Character: (text: String, linewise: Bool)] = [:]
 93    /// What the clipboard held when this engine last wrote it, and whether that was whole lines.
 94    public var clipboardRecord: (text: String, linewise: Bool)?
 95    var anchor = 0
 96    var goalColumn: Int?
 97    /// The last snipe: s, S, f, F, t or T. `consume` lands on the match (s, f, F) rather
 98    /// than next to it (t, T); `keys` repeat it right after it, forward and back.
 99    var lastSnipe: (forward: Bool, chars: String, count: Int, consume: Bool, keys: (forward: KeyChord, backward: KeyChord))?
100    /// Set after a snipe: its keys repeat it as the next key, as evil-snipe's transient map has it.
101    var snipeRepeatKeys: (forward: KeyChord, backward: KeyChord)?
102    var lastSearch: (pattern: String, forward: Bool)?
103    /// The keys and inserted text of the last change, for `.`.
104    var lastChange: (keys: [KeyChord], inserted: String?)?
105    var changeKeys: [KeyChord]?
106    var insertStart = 0
107    /// The caret when the command began, for commands that keep its column.
108    var caretForApply = 0
109    /// Typed in insert state since it began, kept by `inserted(_:)`.
110    var insertedText = ""
111    /// The last visual selection, for `gv`.
112    var lastVisual: (anchor: Int, caret: Int, mode: Mode)?
113    /// Marks the engine set this run, for a context without the editor's.
114    var marks: [Character: Int] = [:]
115    /// Where block `I`, `A` and `c` copy what was typed when insert state ends: the other lines,
116    /// by number from 1, the column, and whether short lines are padded to it.
117    var blockInsert: (lines: [Int], column: Int, pad: Bool)?
118    /// The editor's marks for this key.
119    var contextMarks: [Character: Int] = [:]
120    /// The context's half page and visible text for this key.
121    var contextHalfPage = 15
122    var contextVisible: Range<Int>?
123    var contextOrg = false
124    /// Keys are going into a macro register.
125    public internal(set) var recording = false
126    var lastMacro: Character?
127    /// `$` in block visual state: every line to its end.
128    var blockToEnd = false
129    /// Replace state: each typed character's place, what it overwrote (nil past the line's
130    /// end) and its length; the text typed, and the count to repeat it.
131    var replaceStack: [(offset: Int, original: String?, length: Int)] = []
132    var replaceTyped = ""
133    var replaceCount = 1
134
135    public init() {}
136
137    // MARK: - Feeding keys
138
139    public mutating func feed(_ key: KeyChord, _ context: Context) -> [Action] {
140        switch mode {
141        case .insert:
142            return insertKey(key, context)
143        case .replace:
144            return replaceKey(key, context)
145        case .normal, .visual, .visualLine, .visualBlock:
146            var key = key
147            if pending.isEmpty, let repeatKeys = snipeRepeatKeys {
148                if key == repeatKeys.forward { key = KeyChord(";") } else if key == repeatKeys.backward { key = KeyChord(",") }
149            }
150            if pending.isEmpty { snipeRepeatKeys = nil }
151            pending.append(key)
152            let keys = pending
153            caretForApply = context.caret
154            contextMarks = context.marks
155            contextHalfPage = context.halfPage
156            contextVisible = context.visible
157            contextOrg = context.org
158            var buffer = Buffer(context)
159            switch parse(keys, &buffer, context) {
160            case .incomplete:
161                return []
162            case .invalid:
163                pending = []
164                return []
165            case .done(let actions):
166                pending = []
167                return actions
168            }
169        }
170    }
171
172    /// Text typed in insert state, recorded for `.`.
173    public mutating func inserted(_ text: String) {
174        insertedText += text
175    }
176
177    public mutating func deletedBackward() {
178        if !insertedText.isEmpty { insertedText.removeLast() }
179    }
180
181    private mutating func insertKey(_ key: KeyChord, _ context: Context) -> [Action] {
182        let buffer = Buffer(context)
183        if key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control) {
184            mode = .normal
185            if var keys = changeKeys {
186                keys.append(KeyChord("ESC"))
187                lastChange = (keys, insertedText)
188                changeKeys = nil
189            }
190            let caret = context.caret
191            let lineStart = buffer.lineStart(caret)
192            if let block = blockInsert {
193                blockInsert = nil
194                if !insertedText.isEmpty, !insertedText.contains("\n") { return replicateBlockInsert(block, buffer, caret: caret) }
195            }
196            return [.move(caret: caret > lineStart ? caret - 1 : caret)]
197        }
198        if key == KeyChord("w", .control) {
199            let start = buffer.wordBackward(context.caret, bigWord: false, stopAtLine: true)
200            guard start < context.caret else { return [] }
201            return [.edit([TextEdit(range: start..<context.caret, replacement: "")], caret: start)]
202        }
203        if key == KeyChord("u", .control) {
204            let start = buffer.firstNonBlank(buffer.lineStart(context.caret))
205            let from = context.caret > start ? start : buffer.lineStart(context.caret)
206            guard from < context.caret else { return [] }
207            return [.edit([TextEdit(range: from..<context.caret, replacement: "")], caret: from)]
208        }
209        return []
210    }
211
212    /// Whether a key in insert state belongs to the text system.
213    public func passesThrough(_ key: KeyChord) -> Bool {
214        guard mode == .insert else { return false }
215        return !(key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
216            || key == KeyChord("w", .control) || key == KeyChord("u", .control))
217    }
218
219    public mutating func enterInsert(at caret: Int, keys: [KeyChord]) {
220        mode = .insert
221        insertStart = caret
222        insertedText = ""
223        changeKeys = keys
224    }
225
226}