Sources/OrgCore/Keymap/Vim.swift

250 lines · 11212 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        /// C-e and C-y: scroll the window down (or, negative, up) by lines.
 60        case scrollLines(Int)
 61        /// `zl`, `zh`: scroll the window right (or, negative, left) by columns; `zL` and `zH`
 62        /// with `halfWidths`, by half the window's width.
 63        case scrollColumns(Int, halfWidths: Bool)
 64        /// `q:`, `q/`, `q?`: the command-line window, the earlier commands or searches to pick
 65        /// from and edit.
 66        case commandWindow(String)
 67    }
 68
 69    public struct Context: Sendable {
 70        public var text: String
 71        public var caret: Int
 72        public var clipboard: String?
 73        /// Lines in a half page, for C-d and C-u.
 74        public var halfPage: Int
 75        /// Marks where the editor keeps them now; `'` and `` ` `` are the last jump's start.
 76        public var marks: [Character: Int]
 77        /// The text the window shows, for H, M and L; nil when unknown.
 78        public var visible: Range<Int>?
 79        /// An Org buffer, where evil-org's keys apply.
 80        public var org: Bool
 81        /// The file's path, for the `%` register.
 82        public var fileName: String?
 83        /// The last ex command, for the `:` register.
 84        public var lastEx: String?
 85
 86        public init(text: String, caret: Int, clipboard: String? = nil, halfPage: Int = 15, marks: [Character: Int] = [:], visible: Range<Int>? = nil, org: Bool = false,
 87                    fileName: String? = nil, lastEx: String? = nil) {
 88            self.org = org
 89            self.fileName = fileName
 90            self.lastEx = lastEx
 91            self.text = text
 92            self.caret = caret
 93            self.clipboard = clipboard
 94            self.halfPage = halfPage
 95            self.marks = marks
 96            self.visible = visible
 97        }
 98    }
 99
100    public internal(set) var mode: Mode = .normal
101    /// Keys of the command being typed.
102    public internal(set) var pending: [KeyChord] = []
103    /// Named registers. Evil's are global: an editor with several engines shares them.
104    public var registers: [Character: (text: String, linewise: Bool)] = [:]
105    /// What the clipboard held when this engine last wrote it, and whether that was whole lines.
106    public var clipboardRecord: (text: String, linewise: Bool)?
107    var anchor = 0
108    var goalColumn: Int?
109    /// The last snipe: s, S, f, F, t or T. `consume` lands on the match (s, f, F) rather
110    /// than next to it (t, T); `keys` repeat it right after it, forward and back.
111    var lastSnipe: (forward: Bool, chars: String, count: Int, consume: Bool, keys: (forward: KeyChord, backward: KeyChord))?
112    /// Set after a snipe: its keys repeat it as the next key, as evil-snipe's transient map has it.
113    var snipeRepeatKeys: (forward: KeyChord, backward: KeyChord)?
114    var lastSearch: (pattern: String, forward: Bool)?
115    /// The keys and inserted text of the last change, for `.`.
116    var lastChange: (keys: [KeyChord], inserted: String?)?
117    var changeKeys: [KeyChord]?
118    var insertStart = 0
119    /// The caret when the command began, for commands that keep its column.
120    var caretForApply = 0
121    /// Typed in insert state since it began, kept by `inserted(_:)`.
122    var insertedText = ""
123    /// The last visual selection, for `gv`.
124    var lastVisual: (anchor: Int, caret: Int, mode: Mode)?
125    /// Marks the engine set this run, for a context without the editor's.
126    var marks: [Character: Int] = [:]
127    /// Where block `I`, `A` and `c` copy what was typed when insert state ends: the other lines,
128    /// by number from 1, the column, and whether short lines are padded to it.
129    var blockInsert: (lines: [Int], column: Int, pad: Bool)?
130    /// The editor's marks for this key.
131    var contextMarks: [Character: Int] = [:]
132    /// The context's half page and visible text for this key.
133    var contextHalfPage = 15
134    var contextVisible: Range<Int>?
135    var contextOrg = false
136    /// Keys are going into a macro register.
137    public internal(set) var recording = false
138    var lastMacro: Character?
139    /// `$` in block visual state: every line to its end.
140    var blockToEnd = false
141    /// Replace state: each typed character's place, what it overwrote (nil past the line's
142    /// end) and its length; the text typed, and the count to repeat it.
143    var replaceStack: [(offset: Int, original: String?, length: Int)] = []
144    var replaceTyped = ""
145    var replaceCount = 1
146    /// What the last insert state typed, for the `.` register.
147    var lastInsertion: String?
148    /// The buffer's edits, oldest first, for `g;` and `g,`.
149    var changeLog: [Change] = []
150    /// How far back `g;` has gone; 0 after any other command.
151    var changeDepth = 0
152    var steppingChanges = false
153
154    public init() {}
155
156    // MARK: - Feeding keys
157
158    public mutating func feed(_ key: KeyChord, _ context: Context) -> [Action] {
159        switch mode {
160        case .insert:
161            return insertKey(key, context)
162        case .replace:
163            return replaceKey(key, context)
164        case .normal, .visual, .visualLine, .visualBlock:
165            var key = key
166            if pending.isEmpty, let repeatKeys = snipeRepeatKeys {
167                if key == repeatKeys.forward { key = KeyChord(";") } else if key == repeatKeys.backward { key = KeyChord(",") }
168            }
169            if pending.isEmpty { snipeRepeatKeys = nil }
170            pending.append(key)
171            let keys = pending
172            caretForApply = context.caret
173            contextMarks = context.marks
174            contextHalfPage = context.halfPage
175            contextVisible = context.visible
176            contextOrg = context.org
177            var buffer = Buffer(context)
178            switch parse(keys, &buffer, context) {
179            case .incomplete:
180                return []
181            case .invalid:
182                pending = []
183                return []
184            case .done(let actions):
185                pending = []
186                if !steppingChanges { changeDepth = 0 }
187                steppingChanges = false
188                return actions
189            }
190        }
191    }
192
193    /// Text typed in insert state, recorded for `.`.
194    public mutating func inserted(_ text: String) {
195        insertedText += text
196    }
197
198    public mutating func deletedBackward() {
199        if !insertedText.isEmpty { insertedText.removeLast() }
200    }
201
202    private mutating func insertKey(_ key: KeyChord, _ context: Context) -> [Action] {
203        let buffer = Buffer(context)
204        if key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control) {
205            mode = .normal
206            if var keys = changeKeys {
207                keys.append(KeyChord("ESC"))
208                lastChange = (keys, insertedText)
209                changeKeys = nil
210            }
211            let caret = context.caret
212            let lineStart = buffer.lineStart(caret)
213            if !insertedText.isEmpty { lastInsertion = insertedText }
214            // The `^` mark, where `gi` resumes.
215            marks["^"] = caret
216            if let block = blockInsert {
217                blockInsert = nil
218                if !insertedText.isEmpty, !insertedText.contains("\n") { return [.setMark("^", caret)] + replicateBlockInsert(block, buffer, caret: caret) }
219            }
220            return [.setMark("^", caret), .move(caret: caret > lineStart ? caret - 1 : caret)]
221        }
222        if key == KeyChord("w", .control) {
223            let start = buffer.wordBackward(context.caret, bigWord: false, stopAtLine: true)
224            guard start < context.caret else { return [] }
225            return [.edit([TextEdit(range: start..<context.caret, replacement: "")], caret: start)]
226        }
227        if key == KeyChord("u", .control) {
228            let start = buffer.firstNonBlank(buffer.lineStart(context.caret))
229            let from = context.caret > start ? start : buffer.lineStart(context.caret)
230            guard from < context.caret else { return [] }
231            return [.edit([TextEdit(range: from..<context.caret, replacement: "")], caret: from)]
232        }
233        return []
234    }
235
236    /// Whether a key in insert state belongs to the text system.
237    public func passesThrough(_ key: KeyChord) -> Bool {
238        guard mode == .insert else { return false }
239        return !(key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
240            || key == KeyChord("w", .control) || key == KeyChord("u", .control))
241    }
242
243    public mutating func enterInsert(at caret: Int, keys: [KeyChord]) {
244        mode = .insert
245        insertStart = caret
246        insertedText = ""
247        changeKeys = keys
248    }
249
250}