1mod update;
8
9#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
32pub enum VimMode {
33 #[default]
35 Normal,
36 Insert,
38 Visual,
40 VisualLine,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub(crate) enum VimMotion {
47 Left,
49 Down,
51 Up,
53 Right,
55 WordForward,
57 WordBackward,
59 WordEnd,
61 LineStart,
63 FirstNonBlank,
65 LineEnd,
67 DocumentStart,
69 DocumentEnd,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub(crate) enum VimOperator {
77 Delete,
79 Change,
81 Yank,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) enum VimInsertPosition {
88 BeforeCursor,
90 AfterCursor,
92 FirstNonBlank,
94 EndOfLine,
96 NewLineBelow,
98 NewLineAbove,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(crate) enum VimPastePosition {
105 AfterCursor,
107 BeforeCursor,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113pub(crate) enum VimAction {
114 Mode(VimMode),
116 Motion {
121 motion: VimMotion,
122 count: usize,
123 explicit_count: bool,
124 },
125 Insert {
128 position: VimInsertPosition,
129 count: usize,
130 },
131 Operator {
134 operator: VimOperator,
135 motion: VimMotion,
136 count: usize,
137 explicit_count: bool,
138 },
139 LineOperator { operator: VimOperator, count: usize },
141 VisualOperator(VimOperator),
143 DeleteCharacters { count: usize },
145 Paste {
147 position: VimPastePosition,
148 count: usize,
149 },
150 Undo { count: usize },
152 Redo { count: usize },
154 RepeatSearch { reverse: bool },
157 CommandLineChanged,
159 SubmitSearch(String),
161 SubmitGotoLine(usize),
164 WriteFile { exit_vim: bool },
167 ExitVimMode,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172enum VimCommandLineKind {
173 Search,
174 Command,
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
178struct VimCommandLine {
179 kind: VimCommandLineKind,
180 input: String,
181}
182
183#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
185pub(crate) enum VimRegisterKind {
186 #[default]
187 Characterwise,
188 Linewise,
189}
190
191#[derive(Debug, Default, Clone, PartialEq, Eq)]
193pub(crate) struct VimRegister {
194 pub(crate) text: String,
195 pub(crate) kind: VimRegisterKind,
196}
197
198#[derive(Debug, Default)]
200pub(crate) struct VimState {
201 mode: VimMode,
202 count: Option<usize>,
203 g_prefix: bool,
204 pending_operator: Option<VimOperator>,
205 pending_operator_count: usize,
206 visual_anchor: Option<(usize, usize)>,
207 visual_active: Option<(usize, usize)>,
208 command_line: Option<VimCommandLine>,
209 last_search: Option<String>,
210 pub(crate) register: VimRegister,
211}
212
213impl VimState {
214 pub(crate) fn mode(&self) -> VimMode {
215 self.mode
216 }
217
218 pub(crate) fn reset(&mut self) {
219 *self = Self::default();
220 }
221
222 pub(crate) fn enter_clean_normal_mode(&mut self) {
223 self.mode = VimMode::Normal;
224 self.clear_visual();
225 self.command_line = None;
226 self.clear_pending();
227 }
228
229 pub(crate) fn command_line_active(&self) -> bool {
230 self.command_line.is_some()
231 }
232
233 pub(crate) fn last_search(&self) -> Option<&str> {
234 self.last_search.as_deref()
235 }
236
237 pub(crate) fn command_line_text(&self) -> Option<String> {
238 self.command_line.as_ref().map(|command_line| {
239 let prefix = match command_line.kind {
240 VimCommandLineKind::Search => '/',
241 VimCommandLineKind::Command => ':',
242 };
243 format!("{prefix}{}", command_line.input)
244 })
245 }
246
247 pub(crate) fn pending_keys(&self) -> String {
248 let mut pending = String::new();
249 if let Some(operator) = self.pending_operator {
250 if self.pending_operator_count > 1 {
251 pending.push_str(&self.pending_operator_count.to_string());
252 }
253 pending.push(match operator {
254 VimOperator::Delete => 'd',
255 VimOperator::Change => 'c',
256 VimOperator::Yank => 'y',
257 });
258 if let Some(count) = self.count {
259 pending.push_str(&count.to_string());
260 }
261 } else if let Some(count) = self.count {
262 pending.push_str(&count.to_string());
263 }
264 if self.g_prefix {
265 pending.push('g');
266 }
267 pending
268 }
269
270 pub(crate) fn status_line_text(&self) -> (String, String) {
271 if let Some(command_line) = self.command_line_text() {
272 return (command_line, String::new());
273 }
274
275 let mode = match self.mode {
276 VimMode::Normal => "NORMAL",
277 VimMode::Insert => "INSERT",
278 VimMode::Visual => "VISUAL",
279 VimMode::VisualLine => "VISUAL LINE",
280 };
281
282 (format!("-- {mode} --"), self.pending_keys())
283 }
284
285 pub(crate) fn begin_visual(&mut self, position: (usize, usize)) {
286 self.visual_anchor = Some(position);
287 self.visual_active = Some(position);
288 }
289
290 pub(crate) fn visual_positions(&self) -> Option<((usize, usize), (usize, usize))> {
291 Some((self.visual_anchor?, self.visual_active?))
292 }
293
294 pub(crate) fn set_visual_active(&mut self, position: (usize, usize)) {
295 self.visual_active = Some(position);
296 }
297
298 pub(crate) fn clear_visual(&mut self) {
299 self.visual_anchor = None;
300 self.visual_active = None;
301 }
302
303 pub(crate) fn set_mode_from_mouse(&mut self, mode: VimMode) {
304 self.mode = mode;
305 self.clear_pending();
306 }
307
308 pub(crate) fn enter_insert_mode(&mut self) {
309 self.mode = VimMode::Insert;
310 self.clear_visual();
311 self.command_line = None;
312 self.clear_pending();
313 }
314
315 pub(crate) fn parse_key(&mut self, key: char) -> Option<VimAction> {
316 if self.command_line.is_some() {
317 return self.parse_command_line_key(key);
318 }
319
320 if self.mode == VimMode::Insert {
321 return if key == '\u{1b}' {
322 Some(self.set_mode(VimMode::Normal))
323 } else {
324 None
325 };
326 }
327
328 if key == '\u{1b}' {
329 return Some(self.set_mode(VimMode::Normal));
330 }
331
332 if key.is_ascii_digit() && (key != '0' || self.count.is_some()) {
333 self.push_count_digit(key);
334 return None;
335 }
336
337 if self.g_prefix {
338 if key == 'g' {
339 self.g_prefix = false;
340 return Some(self.finish_motion(VimMotion::DocumentStart));
341 }
342 self.clear_pending();
343 return None;
344 }
345
346 if key == 'g' {
347 self.g_prefix = true;
348 return None;
349 }
350
351 if let Some(operator) = operator_for_key(key) {
352 return self.parse_operator(operator);
353 }
354
355 if let Some(motion) = motion_for_key(key) {
356 return Some(self.finish_motion(motion));
357 }
358
359 let action = match key {
360 'i' => Some(self.insert(VimInsertPosition::BeforeCursor)),
361 'a' => Some(self.insert(VimInsertPosition::AfterCursor)),
362 'I' => Some(self.insert(VimInsertPosition::FirstNonBlank)),
363 'A' => Some(self.insert(VimInsertPosition::EndOfLine)),
364 'o' => Some(self.insert(VimInsertPosition::NewLineBelow)),
365 'O' => Some(self.insert(VimInsertPosition::NewLineAbove)),
366 'v' => Some(self.set_mode(VimMode::Visual)),
367 'V' => Some(self.set_mode(VimMode::VisualLine)),
368 'x' => Some(VimAction::DeleteCharacters {
369 count: self.take_count(),
370 }),
371 'p' => Some(VimAction::Paste {
372 position: VimPastePosition::AfterCursor,
373 count: self.take_count(),
374 }),
375 'P' => Some(VimAction::Paste {
376 position: VimPastePosition::BeforeCursor,
377 count: self.take_count(),
378 }),
379 'u' => Some(VimAction::Undo {
380 count: self.take_count(),
381 }),
382 '\u{12}' => Some(VimAction::Redo {
383 count: self.take_count(),
384 }),
385 'n' => Some(VimAction::RepeatSearch { reverse: false }),
386 'N' => Some(VimAction::RepeatSearch { reverse: true }),
387 '/' => Some(self.open_command_line(VimCommandLineKind::Search)),
388 ':' => Some(self.open_command_line(VimCommandLineKind::Command)),
389 _ => None,
390 };
391
392 if action.is_none() {
393 self.clear_pending();
394 }
395 action
396 }
397
398 fn open_command_line(&mut self, kind: VimCommandLineKind) -> VimAction {
399 self.clear_pending();
400 self.command_line = Some(VimCommandLine {
401 kind,
402 input: String::new(),
403 });
404 VimAction::CommandLineChanged
405 }
406
407 fn parse_command_line_key(&mut self, key: char) -> Option<VimAction> {
408 match key {
409 '\u{1b}' => {
410 self.command_line = None;
411 Some(VimAction::CommandLineChanged)
412 },
413 '\u{8}' => {
414 if let Some(command_line) = self.command_line.as_mut()
415 && command_line.input.pop().is_none()
416 {
417 self.command_line = None;
418 }
419 Some(VimAction::CommandLineChanged)
420 },
421 '\n' | '\r' => {
422 let command_line = self.command_line.take()?;
423 if command_line.input.is_empty() {
424 return Some(VimAction::CommandLineChanged);
425 }
426 match command_line.kind {
427 VimCommandLineKind::Search => {
428 self.last_search = Some(command_line.input.clone());
429 Some(VimAction::SubmitSearch(command_line.input))
430 },
431 VimCommandLineKind::Command => match command_line.input.as_str() {
432 "q" => Some(VimAction::ExitVimMode),
433 "w" => Some(VimAction::WriteFile { exit_vim: false }),
434 "wq" => Some(VimAction::WriteFile { exit_vim: true }),
435 _ => command_line
436 .input
437 .parse::<usize>()
438 .ok()
439 .filter(|line| *line > 0)
440 .map(VimAction::SubmitGotoLine)
441 .or(Some(VimAction::CommandLineChanged)),
442 },
443 }
444 },
445 key if !key.is_control() => {
446 if let Some(command_line) = self.command_line.as_mut() {
447 command_line.input.push(key);
448 }
449 Some(VimAction::CommandLineChanged)
450 },
451 _ => None,
452 }
453 }
454
455 fn set_mode(&mut self, mode: VimMode) -> VimAction {
456 self.mode = mode;
457 self.clear_pending();
458 VimAction::Mode(mode)
459 }
460
461 fn insert(&mut self, position: VimInsertPosition) -> VimAction {
462 let count = self.take_count();
463 self.mode = VimMode::Insert;
464 self.clear_pending();
465 VimAction::Insert { position, count }
466 }
467
468 fn parse_operator(&mut self, operator: VimOperator) -> Option<VimAction> {
469 if self.mode != VimMode::Normal {
470 self.clear_pending();
471 return Some(VimAction::VisualOperator(operator));
472 }
473
474 if let Some(pending) = self.pending_operator {
475 if pending == operator {
476 let count = self.pending_operator_count.saturating_mul(self.take_count());
477 self.clear_pending();
478 return Some(VimAction::LineOperator { operator, count });
479 }
480 self.clear_pending();
481 return None;
482 }
483
484 self.pending_operator_count = self.take_count();
485 self.pending_operator = Some(operator);
486 None
487 }
488
489 fn finish_motion(&mut self, motion: VimMotion) -> VimAction {
490 let motion_count_explicit = self.count.is_some();
491 let motion_count = self.take_count();
492 if let Some(operator) = self.pending_operator {
493 let count = self.pending_operator_count.saturating_mul(motion_count);
494 let explicit_count = motion_count_explicit || self.pending_operator_count > 1;
498 self.clear_pending();
499 VimAction::Operator {
500 operator,
501 motion,
502 count,
503 explicit_count,
504 }
505 } else {
506 self.g_prefix = false;
507 VimAction::Motion {
508 motion,
509 count: motion_count,
510 explicit_count: motion_count_explicit,
511 }
512 }
513 }
514
515 fn push_count_digit(&mut self, key: char) {
516 let digit = key.to_digit(10).unwrap_or_default() as usize;
517 self.count = Some(self.count.unwrap_or_default().saturating_mul(10).saturating_add(digit));
518 }
519
520 fn take_count(&mut self) -> usize {
521 self.count.take().unwrap_or(1).max(1)
522 }
523
524 fn clear_pending(&mut self) {
525 self.count = None;
526 self.g_prefix = false;
527 self.pending_operator = None;
528 self.pending_operator_count = 1;
529 }
530}
531
532fn motion_for_key(key: char) -> Option<VimMotion> {
533 match key {
534 'h' => Some(VimMotion::Left),
535 'j' => Some(VimMotion::Down),
536 'k' => Some(VimMotion::Up),
537 'l' => Some(VimMotion::Right),
538 'w' => Some(VimMotion::WordForward),
539 'b' => Some(VimMotion::WordBackward),
540 'e' => Some(VimMotion::WordEnd),
541 '0' => Some(VimMotion::LineStart),
542 '^' => Some(VimMotion::FirstNonBlank),
543 '$' => Some(VimMotion::LineEnd),
544 'G' => Some(VimMotion::DocumentEnd),
545 _ => None,
546 }
547}
548
549fn operator_for_key(key: char) -> Option<VimOperator> {
550 match key {
551 'd' => Some(VimOperator::Delete),
552 'c' => Some(VimOperator::Change),
553 'y' => Some(VimOperator::Yank),
554 _ => None,
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::{VimAction, VimMotion, VimOperator, VimRegister, VimRegisterKind, VimState};
561
562 #[test]
563 fn vim_parser_accumulates_count_and_operator() {
564 let mut state = VimState::default();
565
566 assert_eq!(state.parse_key('2'), None);
567 assert_eq!(state.parse_key('d'), None);
568 assert_eq!(state.parse_key('3'), None);
569 assert_eq!(
570 state.parse_key('w'),
571 Some(VimAction::Operator {
572 operator: VimOperator::Delete,
573 motion: VimMotion::WordForward,
574 count: 6,
575 explicit_count: true,
576 })
577 );
578 }
579
580 #[test]
581 fn vim_parser_zero_is_motion_without_leading_count() {
582 let mut state = VimState::default();
583
584 assert_eq!(
585 state.parse_key('0'),
586 Some(VimAction::Motion {
587 motion: VimMotion::LineStart,
588 count: 1,
589 explicit_count: false,
590 })
591 );
592
593 assert_eq!(state.parse_key('1'), None);
594 assert_eq!(state.parse_key('0'), None);
595 assert_eq!(
596 state.parse_key('l'),
597 Some(VimAction::Motion {
598 motion: VimMotion::Right,
599 count: 10,
600 explicit_count: true,
601 })
602 );
603 }
604
605 #[test]
606 fn vim_parser_distinguishes_explicit_count_for_document_end() {
607 let mut state = VimState::default();
608
609 assert_eq!(
610 state.parse_key('G'),
611 Some(VimAction::Motion {
612 motion: VimMotion::DocumentEnd,
613 count: 1,
614 explicit_count: false,
615 })
616 );
617
618 assert_eq!(state.parse_key('1'), None);
619 assert_eq!(
620 state.parse_key('G'),
621 Some(VimAction::Motion {
622 motion: VimMotion::DocumentEnd,
623 count: 1,
624 explicit_count: true,
625 })
626 );
627 }
628
629 #[test]
630 fn vim_state_resets_typed_unnamed_register() {
631 let mut state = VimState {
632 register: VimRegister {
633 text: "line\n".to_owned(),
634 kind: VimRegisterKind::Linewise,
635 },
636 ..VimState::default()
637 };
638
639 assert_eq!(state.register.text, "line\n");
640 assert_eq!(state.register.kind, VimRegisterKind::Linewise);
641
642 state.reset();
643
644 assert!(state.register.text.is_empty());
645 assert_eq!(state.register.kind, VimRegisterKind::Characterwise);
646 }
647
648 #[test]
649 fn vim_command_line_parser_accepts_edit_submit_and_cancel() {
650 let mut state = VimState::default();
651
652 assert_eq!(state.parse_key('/'), Some(VimAction::CommandLineChanged));
653 assert_eq!(state.command_line_text().as_deref(), Some("/"));
654
655 for key in "foo".chars() {
656 assert_eq!(state.parse_key(key), Some(VimAction::CommandLineChanged));
657 }
658 assert_eq!(state.command_line_text().as_deref(), Some("/foo"));
659
660 assert_eq!(
661 state.parse_key('\u{8}'),
662 Some(VimAction::CommandLineChanged)
663 );
664 assert_eq!(state.command_line_text().as_deref(), Some("/fo"));
665 assert_eq!(
666 state.parse_key('\n'),
667 Some(VimAction::SubmitSearch("fo".to_owned()))
668 );
669 assert_eq!(state.command_line_text(), None);
670
671 assert_eq!(state.parse_key(':'), Some(VimAction::CommandLineChanged));
672 for key in "12".chars() {
673 let _ = state.parse_key(key);
674 }
675 assert_eq!(state.parse_key('\n'), Some(VimAction::SubmitGotoLine(12)));
676
677 let _ = state.parse_key(':');
678 let _ = state.parse_key('q');
679 assert_eq!(state.parse_key('\n'), Some(VimAction::ExitVimMode));
680
681 let _ = state.parse_key(':');
682 let _ = state.parse_key('w');
683 assert_eq!(
684 state.parse_key('\n'),
685 Some(VimAction::WriteFile { exit_vim: false })
686 );
687
688 let _ = state.parse_key(':');
689 let _ = state.parse_key('w');
690 let _ = state.parse_key('q');
691 assert_eq!(
692 state.parse_key('\n'),
693 Some(VimAction::WriteFile { exit_vim: true })
694 );
695
696 let _ = state.parse_key('/');
697 let _ = state.parse_key('x');
698 assert_eq!(
699 state.parse_key('\u{1b}'),
700 Some(VimAction::CommandLineChanged)
701 );
702 assert_eq!(state.command_line_text(), None);
703 }
704
705 #[test]
706 fn vim_pending_keys_formats_counts_prefixes_and_operators() {
707 let mut state = VimState::default();
708
709 assert_eq!(state.parse_key('5'), None);
710 assert_eq!(state.pending_keys(), "5");
711 assert_eq!(state.parse_key('d'), None);
712 assert_eq!(state.pending_keys(), "5d");
713 assert_eq!(state.parse_key('2'), None);
714 assert_eq!(state.pending_keys(), "5d2");
715
716 state.enter_clean_normal_mode();
717 assert_eq!(state.parse_key('3'), None);
718 assert_eq!(state.parse_key('g'), None);
719 assert_eq!(state.pending_keys(), "3g");
720 }
721
722 #[test]
723 fn vim_status_line_formats_mode_command_and_pending_input() {
724 let mut state = VimState::default();
725 assert_eq!(
726 state.status_line_text(),
727 ("-- NORMAL --".to_owned(), String::new())
728 );
729
730 let _ = state.parse_key('i');
731 assert_eq!(
732 state.status_line_text(),
733 ("-- INSERT --".to_owned(), String::new())
734 );
735 let _ = state.parse_key('\u{1b}');
736
737 let _ = state.parse_key('5');
738 let _ = state.parse_key('d');
739 assert_eq!(
740 state.status_line_text(),
741 ("-- NORMAL --".to_owned(), "5d".to_owned())
742 );
743
744 state.enter_clean_normal_mode();
745 let _ = state.parse_key('/');
746 let _ = state.parse_key('f');
747 let _ = state.parse_key('o');
748 let _ = state.parse_key('o');
749 assert_eq!(state.status_line_text(), ("/foo".to_owned(), String::new()));
750
751 let _ = state.parse_key('\u{1b}');
752 let _ = state.parse_key('v');
753 assert_eq!(
754 state.status_line_text(),
755 ("-- VISUAL --".to_owned(), String::new())
756 );
757
758 let _ = state.parse_key('V');
759 assert_eq!(
760 state.status_line_text(),
761 ("-- VISUAL LINE --".to_owned(), String::new())
762 );
763 }
764}