reedline 0.49.0

A readline-like crate for CLI text input
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
mod command;
mod motion;
mod parser;
mod vi_keybindings;

use std::str::FromStr;

use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
pub use vi_keybindings::{default_vi_insert_keybindings, default_vi_normal_keybindings};

use super::EditMode;
use crate::{
    edit_mode::{keybindings::Keybindings, vi::parser::parse},
    enums::{EditCommand, EventStatus, ReedlineEvent, ReedlineRawEvent},
    Direction, MotionTarget, PromptEditMode, PromptViMode,
};

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum ViMode {
    Normal,
    Insert,
    Visual,
}

impl FromStr for ViMode {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "normal" => Ok(ViMode::Normal),
            "insert" => Ok(ViMode::Insert),
            "visual" => Ok(ViMode::Visual),
            _ => Err(()),
        }
    }
}

/// This parses incoming input `Event`s like a Vi-Style editor
pub struct Vi {
    cache: Vec<char>,
    insert_keybindings: Keybindings,
    normal_keybindings: Keybindings,
    mode: ViMode,
    previous: Option<ReedlineEvent>,
    // last f, F, t, T motion for ; and ,
    last_char_search: Option<MotionTarget>,
}

impl Default for Vi {
    fn default() -> Self {
        Vi {
            insert_keybindings: default_vi_insert_keybindings(),
            normal_keybindings: default_vi_normal_keybindings(),
            cache: Vec::new(),
            mode: ViMode::Insert,
            previous: None,
            last_char_search: None,
        }
    }
}

impl Vi {
    /// Creates Vi editor using defined keybindings
    pub fn new(insert_keybindings: Keybindings, normal_keybindings: Keybindings) -> Self {
        Self {
            insert_keybindings,
            normal_keybindings,
            ..Default::default()
        }
    }
}

impl EditMode for Vi {
    fn parse_event(&mut self, event: ReedlineRawEvent) -> ReedlineEvent {
        match event.into() {
            Event::Key(KeyEvent {
                code, modifiers, ..
            }) => match (self.mode, modifiers, code) {
                (ViMode::Normal, KeyModifiers::NONE, KeyCode::Char('v')) => {
                    self.cache.clear();
                    self.mode = ViMode::Visual;
                    // Entering Visual switches the rest policy to `Block`; the
                    // pre-paint commit then widens the cursor into its min-width-1
                    // selection. Just repaint — do *not* clear the selection here
                    // (e.g. by emitting `Esc`), which would defeat starting one.
                    ReedlineEvent::Repaint
                }
                (ViMode::Normal | ViMode::Visual, modifier, KeyCode::Char(c)) => {
                    let c = c.to_ascii_lowercase();

                    let binding = self
                        .normal_keybindings
                        .find_binding(modifiers, KeyCode::Char(c));
                    let is_typeable =
                        modifier == KeyModifiers::NONE || modifier == KeyModifiers::SHIFT;

                    // A pending multi-key motion (e.g. `f<char>`) must be completed
                    // before a custom keybinding can claim the next key; otherwise a
                    // binding on that second key would hijack the sequence.
                    if !self.cache.is_empty() || (binding.is_none() && is_typeable) {
                        self.cache.push(if modifier == KeyModifiers::SHIFT {
                            c.to_ascii_uppercase()
                        } else {
                            c
                        });

                        let res = parse(self.mode, &mut self.cache.iter().peekable());

                        if !res.is_valid() {
                            self.cache.clear();
                            ReedlineEvent::None
                        } else if res.is_complete(self.mode) {
                            let event = res.to_reedline_event(self);
                            if let Some(mode) = res.changes_mode(self.mode) {
                                self.mode = mode;
                            }
                            self.cache.clear();
                            event
                        } else {
                            ReedlineEvent::None
                        }
                    } else if let Some(event) = binding {
                        event
                    } else {
                        ReedlineEvent::None
                    }
                }
                (ViMode::Insert, modifier, KeyCode::Char(c)) => {
                    // Note. The modifier can also be a combination of modifiers, for
                    // example:
                    //     KeyModifiers::CONTROL | KeyModifiers::ALT
                    //     KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT
                    //
                    // Mixed modifiers are used by non american keyboards that have extra
                    // keys like 'alt gr'. Keep this in mind if in the future there are
                    // cases where an event is not being captured
                    let c = match modifier {
                        KeyModifiers::NONE => c,
                        _ => c.to_ascii_lowercase(),
                    };

                    self.insert_keybindings
                        .find_binding(modifier, KeyCode::Char(c))
                        .unwrap_or_else(|| {
                            if modifier == KeyModifiers::NONE
                                || modifier == KeyModifiers::SHIFT
                                || modifier == KeyModifiers::CONTROL | KeyModifiers::ALT
                                || modifier
                                    == KeyModifiers::CONTROL
                                        | KeyModifiers::ALT
                                        | KeyModifiers::SHIFT
                            {
                                ReedlineEvent::Edit(vec![EditCommand::InsertChar(
                                    if modifier == KeyModifiers::SHIFT {
                                        c.to_ascii_uppercase()
                                    } else {
                                        c
                                    },
                                )])
                            } else {
                                ReedlineEvent::None
                            }
                        })
                }
                (_, KeyModifiers::NONE, KeyCode::Esc) => {
                    self.cache.clear();
                    let leaving_insert = self.mode == ViMode::Insert;
                    self.mode = ViMode::Normal;
                    let mut events = vec![ReedlineEvent::Esc];
                    if leaving_insert {
                        events.push(ReedlineEvent::Edit(vec![EditCommand::Move(
                            MotionTarget::Grapheme(Direction::Backward),
                        )]));
                    }
                    events.push(ReedlineEvent::Repaint);
                    ReedlineEvent::Multiple(events)
                }
                (ViMode::Normal | ViMode::Visual, _, _) => self
                    .normal_keybindings
                    .find_binding(modifiers, code)
                    .unwrap_or_else(|| {
                        // Default Enter behavior when no custom binding
                        if modifiers == KeyModifiers::NONE && code == KeyCode::Enter {
                            self.mode = ViMode::Insert;
                            // The normal/visual block caret rests *on* a grapheme;
                            // submitting (or inserting a newline on incomplete input)
                            // acts past it. Release the caret forward like `a`/append
                            // — under the now-`Between` policy — so the trailing edit
                            // (abbreviation expansion or the newline) lands at the line
                            // end, not one grapheme short, which otherwise split the
                            // last word and dropped submit-time abbreviation expansion.
                            ReedlineEvent::Multiple(vec![
                                ReedlineEvent::Edit(vec![EditCommand::MoveRight { select: false }]),
                                ReedlineEvent::Enter,
                            ])
                        } else {
                            ReedlineEvent::None
                        }
                    }),
                (ViMode::Insert, _, _) => self
                    .insert_keybindings
                    .find_binding(modifiers, code)
                    .unwrap_or_else(|| {
                        // Default Enter behavior when no custom binding
                        if modifiers == KeyModifiers::NONE && code == KeyCode::Enter {
                            ReedlineEvent::Enter
                        } else {
                            ReedlineEvent::None
                        }
                    }),
            },

            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(button),
                column,
                row,
                modifiers: KeyModifiers::NONE,
            }) => ReedlineEvent::Mouse {
                column,
                row,
                button: button.into(),
            },
            Event::Mouse(_) => ReedlineEvent::None,
            Event::Resize(width, height) => ReedlineEvent::Resize(width, height),
            Event::FocusGained => ReedlineEvent::None,
            Event::FocusLost => ReedlineEvent::None,
            Event::Paste(body) => ReedlineEvent::Edit(vec![EditCommand::InsertString(
                body.replace("\r\n", "\n").replace('\r', "\n"),
            )]),
        }
    }

    fn edit_mode(&self) -> PromptEditMode {
        match self.mode {
            ViMode::Normal => PromptEditMode::Vi(PromptViMode::Normal),
            // Visual maps to its own policy (min-width-1 `Block`) so the commit
            // boundary widens the cursor into a selection on entry.
            ViMode::Visual => PromptEditMode::Vi(PromptViMode::Visual),
            ViMode::Insert => PromptEditMode::Vi(PromptViMode::Insert),
        }
    }

    fn handle_mode_specific_event(&mut self, event: ReedlineEvent) -> EventStatus {
        match event {
            ReedlineEvent::ViChangeMode(mode_str) => match ViMode::from_str(&mode_str) {
                Ok(mode) => {
                    self.mode = mode;
                    EventStatus::Handled
                }
                Err(_) => EventStatus::Inapplicable,
            },
            _ => EventStatus::Inapplicable,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{Direction, Granularity, MotionTarget, WordEdge, WordKind};
    use pretty_assertions::assert_eq;

    fn key(code: KeyCode, modifiers: KeyModifiers) -> ReedlineRawEvent {
        ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(code, modifiers))).unwrap()
    }

    #[test]
    fn esc_leads_to_normal_mode_test() {
        // `Vi::default()` starts in insert, so this also covers the
        // leaving-insert cursor step-back.
        let mut vi = Vi::default();
        let esc =
            ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)))
                .unwrap();
        let result = vi.parse_event(esc);

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Esc,
                ReedlineEvent::Edit(vec![EditCommand::Move(MotionTarget::Grapheme(
                    Direction::Backward
                ))]),
                ReedlineEvent::Repaint,
            ])
        );
        assert!(matches!(vi.mode, ViMode::Normal));
    }

    #[test]
    fn esc_from_normal_does_not_step_cursor() {
        // Esc in normal mode only cancels a pending sequence; it must not
        // walk the cursor left like leaving insert does.
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Esc, ReedlineEvent::Repaint])
        );
        assert!(matches!(vi.mode, ViMode::Normal));
    }

    #[test]
    fn keybinding_without_modifier_test() {
        let mut keybindings = default_vi_normal_keybindings();
        keybindings.add_binding(
            KeyModifiers::NONE,
            KeyCode::Char('e'),
            ReedlineEvent::ClearScreen,
        );

        let mut vi = Vi {
            insert_keybindings: default_vi_insert_keybindings(),
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        let esc = ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(
            KeyCode::Char('e'),
            KeyModifiers::NONE,
        )))
        .unwrap();
        let result = vi.parse_event(esc);

        assert_eq!(result, ReedlineEvent::ClearScreen);
    }

    #[test]
    fn keybinding_with_shift_modifier_test() {
        let mut keybindings = default_vi_normal_keybindings();
        keybindings.add_binding(
            KeyModifiers::SHIFT,
            KeyCode::Char('$'),
            ReedlineEvent::CtrlD,
        );

        let mut vi = Vi {
            insert_keybindings: default_vi_insert_keybindings(),
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        let esc = ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(
            KeyCode::Char('$'),
            KeyModifiers::SHIFT,
        )))
        .unwrap();
        let result = vi.parse_event(esc);

        assert_eq!(result, ReedlineEvent::CtrlD);
    }

    #[test]
    fn pending_motion_beats_custom_keybinding() {
        // A custom binding on `B` must not hijack the second key of an
        // in-progress `f<char>` motion: `fB` should find `B`, not fire the
        // binding. Regression test for nushell/reedline#693.
        let mut keybindings = default_vi_normal_keybindings();
        keybindings.add_binding(
            KeyModifiers::SHIFT,
            KeyCode::Char('b'),
            ReedlineEvent::ClearScreen,
        );

        let mut vi = Vi {
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        // `f` opens a pending find-motion...
        let pending = vi.parse_event(key(KeyCode::Char('f'), KeyModifiers::NONE));
        assert_eq!(pending, ReedlineEvent::None);

        // ...so `B` completes `fB` instead of triggering the custom binding.
        let res = vi.parse_event(key(KeyCode::Char('b'), KeyModifiers::SHIFT));

        assert_eq!(
            res,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Edit(vec![EditCommand::Move(
                MotionTarget::Find {
                    ch: 'B',
                    direction: Direction::Forward,
                    stop: crate::FindStop::On,
                }
            )])])
        );
    }

    #[test]
    fn binding_fires_right_after_aborted_find() {
        // A custom binding on `B` must not hijack the second key of an
        // in-progress `f<char>` motion: `fB` should find `B`, not fire the
        // binding. Regression test for nushell/reedline#693.
        let mut keybindings = default_vi_normal_keybindings();
        keybindings.add_binding(
            KeyModifiers::SHIFT,
            KeyCode::Char('z'),
            ReedlineEvent::ClearScreen,
        );

        let mut vi = Vi {
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        // `f` opens a pending find-motion
        let pending = vi.parse_event(key(KeyCode::Char('f'), KeyModifiers::NONE));
        assert_eq!(pending, ReedlineEvent::None);

        // `ESC` aborts the pending find-motion
        vi.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));

        let res = vi.parse_event(key(KeyCode::Char('z'), KeyModifiers::SHIFT));

        assert_eq!(res, ReedlineEvent::ClearScreen);
    }

    #[test]
    fn keybinding_with_super_modifier_test() {
        let mut keybindings = default_vi_normal_keybindings();
        keybindings.add_binding(
            KeyModifiers::SUPER,
            KeyCode::Char('$'),
            ReedlineEvent::CtrlD,
        );

        let mut vi = Vi {
            insert_keybindings: default_vi_insert_keybindings(),
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        let esc = ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(
            KeyCode::Char('$'),
            KeyModifiers::SUPER,
        )))
        .unwrap();
        let result = vi.parse_event(esc);

        assert_eq!(result, ReedlineEvent::CtrlD);
    }

    #[test]
    fn non_register_modifier_test() {
        let keybindings = default_vi_normal_keybindings();
        let mut vi = Vi {
            insert_keybindings: default_vi_insert_keybindings(),
            normal_keybindings: keybindings,
            mode: ViMode::Normal,
            ..Default::default()
        };

        let esc = ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(
            KeyCode::Char('q'),
            KeyModifiers::NONE,
        )))
        .unwrap();
        let result = vi.parse_event(esc);

        assert_eq!(result, ReedlineEvent::None);
    }

    #[test]
    fn v_in_normal_enters_visual() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('v'), KeyModifiers::NONE));

        assert!(matches!(vi.mode, ViMode::Visual));
        // `v` only enters Visual + repaints; it must NOT emit `Esc` (which would
        // clear the selection). The `Block` rest policy materializes the block.
        assert_eq!(result, ReedlineEvent::Repaint);
    }

    #[test]
    fn esc_from_visual_returns_to_normal() {
        let mut vi = Vi {
            mode: ViMode::Visual,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));
        assert!(matches!(vi.mode, ViMode::Normal));
    }

    #[test]
    fn esc_clears_cache() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        assert!(
            !vi.cache.is_empty(),
            "cache should hold the partial sequence"
        );

        let _ = vi.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));
        assert!(vi.cache.is_empty(), "Esc should clear the cache");
    }

    #[test]
    fn unbound_char_in_normal_feeds_parser() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };

        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let result = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Edit(vec![EditCommand::Cut {
                target: MotionTarget::Word {
                    kind: WordKind::Word,
                    edge: WordEdge::Start,
                    direction: Direction::Forward,
                },
                granularity: Granularity::CharWise
            }])]),
        );
        assert!(
            vi.cache.is_empty(),
            "cache should be cleared after a complete sequence"
        );
    }

    #[test]
    fn incomplete_sequence_returns_none_and_holds_cache() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));

        assert_eq!(result, ReedlineEvent::None);
        assert_eq!(vi.cache, vec!['d']);
    }

    #[test]
    fn shift_char_pushed_uppercase_into_cache() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::SHIFT));

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Edit(vec![EditCommand::Move(
                MotionTarget::Word {
                    kind: WordKind::LongWord,
                    edge: WordEdge::Start,
                    direction: Direction::Forward,
                }
            )])]),
        );
    }

    #[test]
    fn d_in_visual_emits_cut_selection_and_returns_to_normal() {
        let mut vi = Vi {
            mode: ViMode::Visual,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Edit(vec![EditCommand::CutSelection])]),
        );
        assert!(matches!(vi.mode, ViMode::Normal));
    }

    #[test]
    fn non_char_key_in_normal_uses_keybindings() {
        let mut kb = default_vi_normal_keybindings();
        kb.add_binding(KeyModifiers::NONE, KeyCode::Up, ReedlineEvent::Up);

        let mut vi = Vi {
            normal_keybindings: kb,
            mode: ViMode::Normal,
            ..Default::default()
        };

        let result = vi.parse_event(key(KeyCode::Up, KeyModifiers::NONE));
        assert_eq!(result, ReedlineEvent::Up);
    }

    #[test]
    fn enter_in_normal_with_no_binding_submits_and_enters_insert() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Enter, KeyModifiers::NONE));

        // Releases the block caret forward (like `a`) before submitting, so a
        // trailing abbreviation / newline acts past the resting grapheme.
        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::MoveRight { select: false }]),
                ReedlineEvent::Enter,
            ])
        );
        assert!(matches!(vi.mode, ViMode::Insert));
    }

    #[test]
    fn unbound_char_in_insert_inserts_char() {
        let mut vi = Vi {
            mode: ViMode::Insert,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('x'), KeyModifiers::NONE));

        assert_eq!(
            result,
            ReedlineEvent::Edit(vec![EditCommand::InsertChar('x')]),
        );
    }

    #[test]
    fn shift_char_in_insert_inserts_uppercase() {
        let mut vi = Vi {
            mode: ViMode::Insert,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('a'), KeyModifiers::SHIFT));

        assert_eq!(
            result,
            ReedlineEvent::Edit(vec![EditCommand::InsertChar('A')]),
        );
    }

    #[test]
    fn ctrl_char_in_insert_with_no_binding_returns_none() {
        let mut vi = Vi {
            mode: ViMode::Insert,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('z'), KeyModifiers::CONTROL));

        assert_eq!(result, ReedlineEvent::None);
    }

    #[test]
    fn i_in_normal_transitions_to_insert() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('i'), KeyModifiers::NONE));
        assert!(matches!(vi.mode, ViMode::Insert));
    }

    #[test]
    fn previous_set_after_complete_command() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let _ = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));
        assert!(
            vi.previous.is_some(),
            "previous should track the last complete command"
        );
    }

    #[test]
    fn paste_event_produces_insert_string() {
        let mut vi = Vi::default();
        let paste = ReedlineRawEvent::try_from(Event::Paste("hello".to_string())).unwrap();
        let result = vi.parse_event(paste);

        assert_eq!(
            result,
            ReedlineEvent::Edit(vec![EditCommand::InsertString("hello".to_string())]),
        );
    }

    #[test]
    fn resize_event_passes_through() {
        let mut vi = Vi::default();
        let resize = ReedlineRawEvent::try_from(Event::Resize(80, 24)).unwrap();
        let result = vi.parse_event(resize);
        assert_eq!(result, ReedlineEvent::Resize(80, 24));
    }

    #[test]
    fn focus_gained_returns_none() {
        let mut vi = Vi::default();
        let ev = ReedlineRawEvent::try_from(Event::FocusGained).unwrap();
        assert_eq!(vi.parse_event(ev), ReedlineEvent::None);
    }

    #[test]
    fn mouse_down_event_produces_mouse_event() {
        let mut vi = Vi::default();
        let ev = ReedlineRawEvent::try_from(Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: 5,
            row: 10,
            modifiers: KeyModifiers::NONE,
        }))
        .unwrap();

        assert_eq!(
            vi.parse_event(ev),
            ReedlineEvent::Mouse {
                column: 5,
                row: 10,
                button: crate::enums::MouseButton::Left,
            },
        );
    }

    #[test]
    fn multiplier_repeats_operator_motion() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('2'), KeyModifiers::NONE));
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let result = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));

        let cut_word = ReedlineEvent::Edit(vec![EditCommand::Cut {
            target: MotionTarget::Word {
                kind: WordKind::Word,
                edge: WordEdge::Start,
                direction: Direction::Forward,
            },
            granularity: Granularity::CharWise,
        }]);
        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![cut_word.clone(), cut_word]),
        );
        assert!(vi.cache.is_empty());
    }

    #[test]
    fn multiplier_alone_repeats_motion() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('3'), KeyModifiers::NONE));
        let result = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));

        let mv = ReedlineEvent::Edit(vec![EditCommand::Move(MotionTarget::Word {
            kind: WordKind::Word,
            edge: WordEdge::Start,
            direction: Direction::Forward,
        })]);
        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![mv.clone(), mv.clone(), mv]),
        );
        assert!(vi.cache.is_empty());
    }

    #[test]
    fn partial_multiplier_holds_cache() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let result = vi.parse_event(key(KeyCode::Char('2'), KeyModifiers::NONE));

        assert_eq!(result, ReedlineEvent::None);
        assert_eq!(vi.cache, vec!['2']);
    }

    #[test]
    fn invalid_motion_after_operator_clears_cache() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        assert_eq!(vi.cache, vec!['d']);

        let result = vi.parse_event(key(KeyCode::Char('z'), KeyModifiers::NONE));

        assert_eq!(result, ReedlineEvent::None);
        assert!(
            vi.cache.is_empty(),
            "an invalid motion should drop the cached operator",
        );
    }

    #[test]
    fn linewise_dd_emits_linewise_cut() {
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let result = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));

        assert_eq!(
            result,
            ReedlineEvent::Multiple(vec![ReedlineEvent::Edit(vec![EditCommand::Cut {
                target: MotionTarget::LineEdge(Direction::Forward),
                granularity: Granularity::LineWise,
            }])]),
        );
        assert!(vi.cache.is_empty());
    }

    #[test]
    fn repeated_dot_doesnt_accumulates_nesting_in_previous() {
        // `.` replays the last change; it must not record itself
        fn depth(ev: &ReedlineEvent) -> usize {
            match ev {
                ReedlineEvent::Multiple(v) if v.len() == 1 => 1 + depth(&v[0]),
                _ => 0,
            }
        }
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let _ = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));
        assert_eq!(depth(vi.previous.as_ref().unwrap()), 1);

        let _ = vi.parse_event(key(KeyCode::Char('.'), KeyModifiers::NONE));
        assert_eq!(depth(vi.previous.as_ref().unwrap()), 1);

        let _ = vi.parse_event(key(KeyCode::Char('.'), KeyModifiers::NONE));
        assert_eq!(depth(vi.previous.as_ref().unwrap()), 1);

        let _ = vi.parse_event(key(KeyCode::Char('.'), KeyModifiers::NONE));
        assert_eq!(depth(vi.previous.as_ref().unwrap()), 1);
    }

    #[test]
    fn dot_replays_previous_wrapped_in_outer_multiple() {
        // `.` produces Multiple([previous]) and writes it back to
        // `previous`. See `repeated_dot_accumulates_nesting_in_previous`
        // for the consequences — this assertion just pins the shape.
        let mut vi = Vi {
            mode: ViMode::Normal,
            ..Default::default()
        };
        let _ = vi.parse_event(key(KeyCode::Char('d'), KeyModifiers::NONE));
        let dw = vi.parse_event(key(KeyCode::Char('w'), KeyModifiers::NONE));
        assert!(vi.previous.is_some());

        let dot = vi.parse_event(key(KeyCode::Char('.'), KeyModifiers::NONE));
        assert_eq!(dot, ReedlineEvent::Multiple(vec![dw]));
    }
}