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