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