Sources/OrgCore/Keymap/Vim.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgCore/Keymap/Vim.swift history · blame · raw

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