1use crate::{Command, Direction, Key, KeyEvent};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum VimMode {
5 Normal,
6 Insert,
7 Visual,
8}
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum VimAction {
13 Commands(Vec<Command>),
14 Passthrough,
16 Pending,
18}
19
20#[derive(Clone, Debug)]
25pub struct Vim {
26 pub mode: VimMode,
27 count: Option<usize>,
28 operator: Option<char>,
29 g_pending: bool,
30 object: Option<char>,
32 awaiting: Option<char>,
34 line: Option<String>,
36}
37
38impl Default for Vim {
39 fn default() -> Self {
40 Self {
41 mode: VimMode::Normal,
42 count: None,
43 operator: None,
44 g_pending: false,
45 object: None,
46 awaiting: None,
47 line: None,
48 }
49 }
50}
51
52fn motion(key: char) -> Option<Direction> {
53 Some(match key {
54 'h' => Direction::Left,
55 'l' => Direction::Right,
56 'k' => Direction::Up,
57 'j' => Direction::Down,
58 'w' => Direction::NextWordStart,
59 'e' => Direction::WordRight,
60 'b' => Direction::WordLeft,
61 '$' => Direction::LineEnd,
62 '0' => Direction::LineColumnZero,
63 'G' => Direction::Bottom,
64 _ => return None,
65 })
66}
67
68impl Vim {
69 fn reset(&mut self) {
70 self.count = None;
71 self.operator = None;
72 self.g_pending = false;
73 self.object = None;
74 self.awaiting = None;
75 }
76
77 pub fn pending(&self) -> bool {
79 self.count.is_some()
80 || self.operator.is_some()
81 || self.g_pending
82 || self.object.is_some()
83 || self.awaiting.is_some()
84 || self.line.is_some()
85 }
86
87 pub fn command_line(&self) -> Option<&str> {
89 self.line.as_deref()
90 }
91
92 fn line_key(&mut self, event: KeyEvent) -> VimAction {
94 use Command::*;
95 let line = self.line.as_mut().expect("only called on a line");
96 match event.key {
97 Key::Esc => self.line = None,
98 Key::Backspace if line.is_empty() => self.line = None,
99 Key::Backspace => {
100 line.pop();
101 }
102 Key::Char(c) => line.push(c),
103 Key::Enter => {
104 let typed = self.line.take().unwrap_or_default();
105 let commands = match typed.trim() {
106 "w" => vec![Save],
107 "q" | "q!" => vec![CloseTab],
108 "wq" | "x" => vec![Save, CloseTab],
109 "qa" | "qa!" => vec![Quit],
110 number => match number.parse::<usize>() {
111 Ok(line) => {
112 let down = line.saturating_sub(1);
113 let mut moves = vec![Move(Direction::Top, false)];
114 moves.extend(vec![Move(Direction::Down, false); down]);
115 moves
116 }
117 Err(_) => Vec::new(),
118 },
119 };
120 return VimAction::Commands(commands);
121 }
122 _ => {}
123 }
124 VimAction::Pending
125 }
126
127 fn awaited(&mut self, pending: char, c: char) -> VimAction {
129 use Command::*;
130 if pending == 'r' {
131 self.reset();
132 return VimAction::Commands(vec![DeleteForward, Type(c), Move(Direction::Left, false)]);
133 }
134 let direction =
135 Direction::FindChar(c, pending.is_lowercase(), matches!(pending, 't' | 'T'));
136 let operator = self.operator;
137 let times = self.count.unwrap_or(1);
138 self.reset();
139 let Some(operator) = operator else {
140 return VimAction::Commands(vec![Move(direction, false); times]);
141 };
142 let mut commands = vec![Move(direction, true); times];
144 if pending.is_lowercase() {
145 commands.push(Move(Direction::Right, true));
146 }
147 self.finish(operator, commands)
148 }
149
150 fn finish(&mut self, operator: char, mut commands: Vec<Command>) -> VimAction {
152 use Command::*;
153 match operator {
154 'y' => commands.extend([Copy, Cancel]),
155 _ => commands.extend([Cut, Cancel]),
156 }
157 if operator == 'c' {
158 self.mode = VimMode::Insert;
159 }
160 VimAction::Commands(commands)
161 }
162
163 fn repeat(&mut self, commands: Vec<Command>) -> VimAction {
164 let times = self.count.unwrap_or(1);
165 self.reset();
166 VimAction::Commands(
167 commands
168 .iter()
169 .copied()
170 .cycle()
171 .take(commands.len() * times)
172 .collect(),
173 )
174 }
175
176 fn enter_insert(&mut self, before: Vec<Command>) -> VimAction {
177 self.reset();
178 self.mode = VimMode::Insert;
179 VimAction::Commands(before)
180 }
181
182 pub fn key(&mut self, event: KeyEvent) -> VimAction {
183 if self.line.is_some() {
184 return self.line_key(event);
185 }
186 match self.mode {
187 VimMode::Insert => {
188 if event.key == Key::Esc {
189 self.mode = VimMode::Normal;
190 return VimAction::Commands(vec![Command::Move(Direction::Left, false)]);
191 }
192 VimAction::Passthrough
193 }
194 VimMode::Normal | VimMode::Visual => self.command_key(event),
195 }
196 }
197
198 fn visual_key(&mut self, c: char) -> VimAction {
199 let operate = |vim: &mut Self, command| {
200 vim.mode = VimMode::Normal;
201 vim.reset();
202 VimAction::Commands(vec![Command::Move(Direction::Right, true), command])
204 };
205 match c {
206 'd' | 'x' => operate(self, Command::Cut),
207 'y' => operate(self, Command::Copy),
208 'v' => {
209 self.mode = VimMode::Normal;
210 self.reset();
211 VimAction::Commands(vec![Command::Cancel])
212 }
213 _ => match motion(c) {
214 Some(direction) => self.repeat(vec![Command::Move(direction, true)]),
215 None => VimAction::Pending,
216 },
217 }
218 }
219
220 fn command_key(&mut self, event: KeyEvent) -> VimAction {
221 use Command::*;
222 if event.key == Key::Esc {
223 self.reset();
224 self.mode = VimMode::Normal;
225 return VimAction::Commands(vec![Cancel]);
226 }
227 if event.mods.ctrl {
228 return match event.key {
229 Key::Char('r') => self.repeat(vec![Redo]),
230 _ => VimAction::Passthrough,
231 };
232 }
233 let Key::Char(c) = event.key else {
234 return match event.key {
236 Key::Enter | Key::Backspace | Key::Delete | Key::Tab => VimAction::Pending,
237 _ => VimAction::Passthrough,
238 };
239 };
240 if let Some(pending) = self.awaiting.take() {
241 return self.awaited(pending, c);
242 }
243 if let Some(object) = self.object.take() {
244 return self.text_object(object, c);
245 }
246 if c.is_ascii_digit() && (c != '0' || self.count.is_some()) {
247 let digit = c as usize - '0' as usize;
248 self.count = Some(self.count.unwrap_or(0) * 10 + digit);
249 return VimAction::Pending;
250 }
251 if self.mode == VimMode::Visual {
252 return self.visual_key(c);
253 }
254 if std::mem::take(&mut self.g_pending) {
255 self.reset();
256 return if c == 'g' {
257 VimAction::Commands(vec![Move(Direction::Top, false)])
258 } else {
259 VimAction::Pending
260 };
261 }
262 if matches!(c, 'f' | 't' | 'F' | 'T') {
263 self.awaiting = Some(c);
264 return VimAction::Pending;
265 }
266 if let Some(operator) = self.operator {
267 return self.operate(operator, c);
268 }
269 if let Some(direction) = motion(c) {
270 return self.repeat(vec![Move(direction, false)]);
271 }
272 match c {
273 'g' => {
274 self.g_pending = true;
275 VimAction::Pending
276 }
277 'd' | 'y' | 'c' => {
278 self.operator = Some(c);
279 VimAction::Pending
280 }
281 'i' => self.enter_insert(Vec::new()),
282 'a' => self.enter_insert(vec![Move(Direction::Right, false)]),
283 'I' => self.enter_insert(vec![
284 Move(Direction::LineColumnZero, false),
285 Move(Direction::LineStart, false),
286 ]),
287 'A' => self.enter_insert(vec![Move(Direction::LineEnd, false)]),
288 'o' => self.enter_insert(vec![Move(Direction::LineEnd, false), Newline]),
289 'O' => self.enter_insert(vec![
290 Move(Direction::LineColumnZero, false),
291 Newline,
292 Move(Direction::Up, false),
293 ]),
294 'x' => self.repeat(vec![DeleteForward]),
295 'u' => self.repeat(vec![Undo]),
296 'p' => self.repeat(vec![PasteLine]),
297 'D' => self.repeat(vec![DeleteToLineEnd]),
298 'C' => self.enter_insert(vec![DeleteToLineEnd]),
299 'J' => self.repeat(vec![
300 Move(Direction::LineEnd, false),
301 DeleteForward,
302 Type(' '),
303 ]),
304 'r' => {
305 self.awaiting = Some('r');
306 VimAction::Pending
307 }
308 ':' => {
309 self.reset();
310 self.line = Some(String::new());
311 VimAction::Pending
312 }
313 '/' => {
314 self.reset();
315 VimAction::Commands(vec![FindInFile])
316 }
317 'v' => {
318 self.reset();
319 self.mode = VimMode::Visual;
320 VimAction::Pending
321 }
322 'V' => {
323 self.reset();
324 self.mode = VimMode::Visual;
325 VimAction::Commands(vec![
326 Move(Direction::LineColumnZero, false),
327 Move(Direction::LineEnd, true),
328 ])
329 }
330 _ => {
331 self.reset();
332 VimAction::Pending
333 }
334 }
335 }
336
337 fn operate(&mut self, operator: char, c: char) -> VimAction {
340 use Command::*;
341 if matches!(c, 'i' | 'a') {
342 self.object = Some(c);
343 return VimAction::Pending;
344 }
345 let times = self.count.unwrap_or(1);
346 self.reset();
347 let direction = match (operator, motion(c)) {
349 ('c', Some(Direction::NextWordStart)) => Some(Direction::WordRight),
350 (_, direction) => direction,
351 };
352 let body: Vec<Command> = if c == operator {
353 vec![SelectLines(times)]
354 } else if let Some(direction) = direction {
355 vec![Move(direction, true); times]
356 } else {
357 return VimAction::Pending;
358 };
359 self.finish(operator, body)
360 }
361
362 fn text_object(&mut self, around: char, c: char) -> VimAction {
365 use Command::*;
366 let operator = self.operator;
367 self.reset();
368 let Some(operator) = operator.filter(|_| c == 'w') else {
369 return VimAction::Pending;
370 };
371 let mut commands = vec![
373 Move(Direction::Right, false),
374 Move(Direction::WordLeft, false),
375 Move(Direction::WordRight, true),
376 ];
377 if around == 'a' {
378 commands.push(Move(Direction::NextWordStart, true));
379 }
380 self.finish(operator, commands)
381 }
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 fn press(vim: &mut Vim, keys: &str) -> Vec<VimAction> {
389 keys.chars()
390 .map(|c| vim.key(KeyEvent::plain(Key::Char(c))))
391 .collect()
392 }
393
394 fn commands(vim: &mut Vim, keys: &str) -> Vec<Command> {
396 let mut out = Vec::new();
397 for c in keys.chars() {
398 let event = match c {
399 '\n' => KeyEvent::plain(Key::Enter),
400 '\x1b' => KeyEvent::plain(Key::Esc),
401 c => KeyEvent::plain(Key::Char(c)),
402 };
403 match vim.key(event) {
404 VimAction::Commands(more) => out.extend(more),
405 VimAction::Passthrough => out.push(Command::Type(c)),
406 VimAction::Pending => {}
407 }
408 }
409 out
410 }
411
412 #[test]
413 fn change_inner_word_replaces_just_the_word() {
414 let mut vim = Vim::default();
415 let made = commands(&mut vim, "ciwHI\x1b");
416 assert!(made.contains(&Command::Cut), "{made:?}");
417 let typed: String = made
418 .iter()
419 .filter_map(|c| match c {
420 Command::Type(c) => Some(*c),
421 _ => None,
422 })
423 .collect();
424 assert_eq!(typed, "HI", "only what's typed in Insert reaches the file");
425 assert_eq!(vim.mode, VimMode::Normal);
426 }
427
428 #[test]
429 fn unknown_keys_in_normal_mode_never_type() {
430 let mut vim = Vim::default();
431 let made = commands(&mut vim, "dif.QZ!\n");
432 assert!(
433 !made.iter().any(|c| matches!(c, Command::Type(_))),
434 "{made:?}"
435 );
436 assert_eq!(vim.mode, VimMode::Normal);
437 }
438
439 #[test]
440 fn colon_commands_save_close_and_go_to_a_line() {
441 let mut vim = Vim::default();
442 assert_eq!(commands(&mut vim, ":w\n"), vec![Command::Save]);
443 assert_eq!(
444 commands(&mut vim, ":wq\n"),
445 vec![Command::Save, Command::CloseTab]
446 );
447 let to_three = commands(&mut vim, ":3\n");
448 assert_eq!(to_three.len(), 3, "top, then down twice: {to_three:?}");
449 assert!(vim.command_line().is_none());
450 }
451
452 #[test]
453 fn find_motions_reach_the_character() {
454 let mut vim = Vim::default();
455 let made = commands(&mut vim, "fx");
456 assert_eq!(
457 made,
458 vec![Command::Move(Direction::FindChar('x', true, false), false)]
459 );
460 let made = commands(&mut vim, "dtx");
461 assert!(made.contains(&Command::Cut), "{made:?}");
462 }
463
464 #[test]
465 fn w_goes_to_the_next_word_and_e_to_the_end() {
466 assert_eq!(motion('w'), Some(Direction::NextWordStart));
467 assert_eq!(motion('e'), Some(Direction::WordRight));
468 }
469
470 #[test]
471 fn counts_repeat_motions() {
472 let mut vim = Vim::default();
473 let actions = press(&mut vim, "3j");
474 let want = vec![Command::Move(Direction::Down, false); 3];
475 assert_eq!(actions[1], VimAction::Commands(want));
476 }
477
478 #[test]
479 fn insert_passes_keys_through_until_escape() {
480 let mut vim = Vim::default();
481 press(&mut vim, "i");
482 assert_eq!(press(&mut vim, "q")[0], VimAction::Passthrough);
483 vim.key(KeyEvent::plain(Key::Esc));
484 assert_eq!(vim.mode, VimMode::Normal);
485 }
486
487 #[test]
488 fn zero_is_a_motion_until_a_count_starts() {
489 let mut vim = Vim::default();
490 let want = vec![Command::Move(Direction::LineColumnZero, false)];
491 assert_eq!(press(&mut vim, "0")[0], VimAction::Commands(want));
492 assert_eq!(press(&mut vim, "10")[1], VimAction::Pending);
493 }
494}