reedline 0.50.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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
mod helix_keybindings;

use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
pub use helix_keybindings::{
    default_helix_insert_keybindings, default_helix_normal_keybindings,
    default_helix_select_keybindings,
};

use super::{is_plain_char, is_text_char, parse_non_key_event};

use crate::{
    Direction, EditCommand, EditMode, FindStop, Granularity, Keybindings, MotionTarget,
    PromptEditMode, PromptHelixMode, ReedlineEvent, WordEdge, WordKind,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HelixMode {
    Normal,
    Insert,
    Select,
}
/// A prefix key waiting for its argument.
///
/// `Find` and `Replace` take an arbitrary char as data, so no finite key
/// sequence can spell them; `Goto` takes one key from a fixed set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pending {
    /// `f`/`F`/`t`/`T` are waiting for the character to find.
    Find {
        direction: Direction,
        stop: FindStop,
    },
    /// `r` is waiting for the replacement character.
    Replace,
    /// `g` is waiting for the goto target (`h`/`l`/`g`/`e`).
    Goto,
}

/// Every parse_event will result in one of three outcomes:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
    /// Absorb the `ReedlineRawEvent` -> change state -> continue parsing
    Absorb(Pending),
    /// Execute an `Action` matching the completed sequence
    Execute(Action),
    /// Reject a miss-typed sequence
    Reject,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verb {
    SelectingMotion(MotionTarget),
    CollapsingMotion(MotionTarget),
    Collapse(Direction),
    Deselect,
    OnSelection(Op),
    Submit,
    ChangeMode,
    Undo,
    Redo,
    Paste(Direction),
    /// Open a blank line below (`Forward`, `o`) or above (`Backward`, `O`).
    OpenLine(Direction),
    /// `%`. Whole-buffer, so both edges move and no [`MotionTarget`] applies.
    SelectAll,
    /// `x`. Selection-shaped rather than motion-shaped: it moves both edges,
    /// which no [`MotionTarget`] can express.
    SelectLine,
    /// `j`/`k`. The only verb that does not lower to a [`MotionTarget`]: which
    /// of line movement and history traversal applies is decided by the engine
    /// against the *whole* buffer, above where a motion resolves.
    LineOrHistory(Direction),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    Cut,
    Change,
    Yank,
    Replace(char),
    /// `~`. Keeps the selection, like `Yank`, so a further op reuses the span.
    Switchcase,
    /// `` ` ``. Keeps the selection, as `Switchcase` does.
    Lowercase,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Action {
    count: usize,
    verb: Verb,
    next_mode: Option<HelixMode>,
}

impl Action {
    /// Emit `cmd` once per count.
    ///
    /// Valid only when repeating the event composes, i.e. the op re-reads
    /// the cursor each time. Motions and undo qualify; paste won't, since
    /// it writes a cursor derived from what it just inserted.
    fn repeated(self, cmd: EditCommand) -> ReedlineEvent {
        ReedlineEvent::Edit(vec![cmd; self.count])
    }
}

/// Shorthand for the `Outcome::Execute(Action { .. })` arms of the key tables.
fn exec(count: usize, verb: Verb, next_mode: Option<HelixMode>) -> Outcome {
    Outcome::Execute(Action {
        count,
        verb,
        next_mode,
    })
}

/// The word-family target of `w`/`b`/`e` and their WORD (`W`/`B`/`E`) twins.
fn word(kind: WordKind, edge: WordEdge, direction: Direction) -> MotionTarget {
    MotionTarget::Word {
        kind,
        edge,
        direction,
    }
}

/// This parses incoming input `Event`s like a Helix/Kakoune-style editor: motions are
/// selection first, lowered onto the editor's [`MotionTarget`](crate::MotionTarget) verb vocabulary.
#[derive(Debug, Clone)]
pub struct Helix {
    /// Keybinding lookup table for insert mode
    insert_keybindings: Keybindings,
    /// Keybinding lookup table for normal mode
    normal_keybindings: Keybindings,
    /// Keybinding lookup table for select mode
    select_keybindings: Keybindings,
    mode: HelixMode,
    /// Count prefix being accumulated (`3w`).
    count: Option<usize>,
    /// Prefix key waiting for its argument (`f`/`r`/`g`).
    pending: Option<Pending>,
}

impl EditMode for Helix {
    fn parse_event(&mut self, event: crate::ReedlineRawEvent) -> crate::ReedlineEvent {
        match event.into() {
            Event::Key(key) => match self.mode {
                HelixMode::Insert => self.dispatch_insert(key),
                _ => self.dispatch(key),
            },
            event => parse_non_key_event(event),
        }
    }
    fn edit_mode(&self) -> crate::PromptEditMode {
        match self.mode {
            HelixMode::Insert => PromptEditMode::Helix(PromptHelixMode::Insert),
            HelixMode::Normal => PromptEditMode::Helix(PromptHelixMode::Normal),
            HelixMode::Select => PromptEditMode::Helix(PromptHelixMode::Select),
        }
    }
}

impl Helix {
    /// Replace the insert-mode keybinding table, keeping the normal-mode
    /// default.
    ///
    /// Layer onto the defaults rather than starting from
    /// [`Keybindings::empty`]: the table is consulted before the state machine
    /// runs, so an empty one silently drops every bound key.
    ///
    ///     # use reedline::{default_helix_insert_keybindings, Helix};
    ///     let mut bindings = default_helix_insert_keybindings();
    ///     // bindings.add_binding(..);
    ///     let helix = Helix::default().with_insert_keybindings(bindings);
    #[must_use]
    pub fn with_insert_keybindings(mut self, keybindings: Keybindings) -> Self {
        self.insert_keybindings = keybindings;
        self
    }

    /// Replace the normal-mode keybinding table, keeping the insert- and
    /// select-mode defaults. Consulted before the state machine, so a binding
    /// here shadows the built-in key of the same name.
    #[must_use]
    pub fn with_normal_keybindings(mut self, keybindings: Keybindings) -> Self {
        self.normal_keybindings = keybindings;
        self
    }

    /// Replace the select-mode keybinding table, keeping the other defaults.
    /// Layer onto [`default_helix_select_keybindings`] rather than the normal
    /// table, or the extending navigation twins (arrows, `Home`/`End`, ...)
    /// fall back to their mode-blind normal-mode behavior.
    #[must_use]
    pub fn with_select_keybindings(mut self, keybindings: Keybindings) -> Self {
        self.select_keybindings = keybindings;
        self
    }

    fn dispatch(&mut self, key: KeyEvent) -> ReedlineEvent {
        // Insert should never use this code-path.
        debug_assert!(self.mode != HelixMode::Insert);
        let outcome = match (self.pending.take(), key.code) {
            // Handle a pending key event
            (Some(pending), _) => complete_pending(pending, self.count.unwrap_or(1), key),
            // Handle a count modifier
            (None, KeyCode::Char(c @ '0'..='9'))
                if key.modifiers == KeyModifiers::NONE && (c != '0' || self.count.is_some()) =>
            {
                // Cap the count: every consumer repeats O(count) work on one
                // keystroke, so an absurd prefix must not freeze the REPL.
                self.count = Some(
                    self.count
                        .unwrap_or(0)
                        .saturating_mul(10)
                        .saturating_add(c.to_digit(10).unwrap_or(0) as usize)
                        .min(u16::MAX as usize),
                );
                return ReedlineEvent::None;
            }
            // Do a table lookup, else use the helix machine,
            // we don't handle insert mode in dispatch.
            // Esc must always reach the machine, otherwise modes get stranded.
            (None, code) => {
                if self.count.is_none() && code != KeyCode::Esc {
                    let table = match self.mode {
                        HelixMode::Select => &self.select_keybindings,
                        _ => &self.normal_keybindings,
                    };
                    if let Some(event) = table.find_binding(key.modifiers, code) {
                        return event;
                    }
                }
                interpret(self.mode, self.count, key)
            }
        };

        match outcome {
            Outcome::Absorb(pending) => {
                self.pending = Some(pending);
                ReedlineEvent::None
            }
            Outcome::Execute(action) => {
                self.count = None;
                let event = lower(action, self.mode);
                if let Some(next_mode) = action.next_mode {
                    self.mode = next_mode;
                }
                event
            }
            Outcome::Reject => {
                self.count = None;
                ReedlineEvent::None
            }
        }
    }
    fn dispatch_insert(&mut self, key: KeyEvent) -> ReedlineEvent {
        // handle esc first since it has to always reach the machine
        if matches!(key.code, KeyCode::Esc) {
            self.mode = HelixMode::Normal;
            return ReedlineEvent::Multiple(vec![ReedlineEvent::Esc, ReedlineEvent::Repaint]);
        }
        if let Some(event) = self
            .insert_keybindings
            .find_binding(key.modifiers, key.code)
        {
            return event;
        }
        match key.code {
            KeyCode::Enter if key.modifiers == KeyModifiers::NONE => ReedlineEvent::Enter,
            KeyCode::Char(ch) if is_text_char(key.modifiers) => {
                ReedlineEvent::Edit(vec![EditCommand::InsertChar(ch)])
            }
            _ => ReedlineEvent::None,
        }
    }
}
impl Default for Helix {
    fn default() -> Self {
        Self {
            insert_keybindings: default_helix_insert_keybindings(),
            normal_keybindings: default_helix_normal_keybindings(),
            select_keybindings: default_helix_select_keybindings(),
            mode: HelixMode::Insert,
            count: None,
            pending: None,
        }
    }
}

/// Complete a pending sequence
fn complete_pending(pending: Pending, count: usize, key: KeyEvent) -> Outcome {
    let ch = match key.code {
        KeyCode::Char(ch) if is_text_char(key.modifiers) => ch,
        _ => return Outcome::Reject,
    };

    match pending {
        Pending::Find { direction, stop } => exec(
            count,
            Verb::SelectingMotion(MotionTarget::Find {
                ch,
                direction,
                stop,
            }),
            None,
        ),
        Pending::Replace => exec(count, Verb::OnSelection(Op::Replace(ch)), None),
        Pending::Goto => {
            let target = match ch {
                'h' => MotionTarget::LineEdge(Direction::Backward),
                'l' => MotionTarget::LineEdge(Direction::Forward),
                'g' => MotionTarget::BufferEdge(Direction::Backward),
                'e' => MotionTarget::BufferEdge(Direction::Forward),
                's' => MotionTarget::LineStartNonBlank,
                _ => return Outcome::Reject,
            };
            exec(count, Verb::CollapsingMotion(target), None)
        }
    }
}

/// Interpret a state
///
/// `count` stays `Option` so a typed `1` is distinguishable from no count;
/// only the goto prefix cares.
fn interpret(mode: HelixMode, count: Option<usize>, key: KeyEvent) -> Outcome {
    // Reject any non-typeable char. Alt-modified keys reach the keybinding table
    // in `dispatch` instead, which is where `Alt-d` and ``Alt-` `` are bound.
    if let KeyCode::Char(_) = key.code {
        if !is_plain_char(key.modifiers) {
            return Outcome::Reject;
        }
    }
    // Helix reads `3gg` as "go to line 3", which has no `MotionTarget` yet, so
    // a counted `g` falls through to the reject arm rather than acting as `gg`.
    if key.code == KeyCode::Char('g') && count.is_none() {
        return Outcome::Absorb(Pending::Goto);
    }
    let count = count.unwrap_or(1);
    match key.code {
        KeyCode::Char(ch) => match ch {
            'f' => Outcome::Absorb(Pending::Find {
                direction: Direction::Forward,
                stop: FindStop::On,
            }),
            'F' => Outcome::Absorb(Pending::Find {
                direction: Direction::Backward,
                stop: FindStop::On,
            }),
            't' => Outcome::Absorb(Pending::Find {
                direction: Direction::Forward,
                stop: FindStop::Before,
            }),
            'T' => Outcome::Absorb(Pending::Find {
                direction: Direction::Backward,
                stop: FindStop::Before,
            }),
            'r' => Outcome::Absorb(Pending::Replace),
            'w' => exec(
                count,
                Verb::SelectingMotion(word(WordKind::Word, WordEdge::Start, Direction::Forward)),
                None,
            ),
            'b' => exec(
                count,
                Verb::SelectingMotion(word(WordKind::Word, WordEdge::Start, Direction::Backward)),
                None,
            ),
            'e' => exec(
                count,
                Verb::SelectingMotion(word(WordKind::Word, WordEdge::End, Direction::Forward)),
                None,
            ),
            'W' => exec(
                count,
                Verb::SelectingMotion(word(
                    WordKind::LongWord,
                    WordEdge::Start,
                    Direction::Forward,
                )),
                None,
            ),
            'B' => exec(
                count,
                Verb::SelectingMotion(word(
                    WordKind::LongWord,
                    WordEdge::Start,
                    Direction::Backward,
                )),
                None,
            ),
            'E' => exec(
                count,
                Verb::SelectingMotion(word(WordKind::LongWord, WordEdge::End, Direction::Forward)),
                None,
            ),
            'l' => exec(
                count,
                Verb::CollapsingMotion(MotionTarget::Grapheme(Direction::Forward)),
                None,
            ),
            'h' => exec(
                count,
                Verb::CollapsingMotion(MotionTarget::Grapheme(Direction::Backward)),
                None,
            ),
            'j' => exec(count, Verb::LineOrHistory(Direction::Forward), None),
            'k' => exec(count, Verb::LineOrHistory(Direction::Backward), None),
            'x' => exec(count, Verb::SelectLine, None),
            '%' => exec(count, Verb::SelectAll, None),
            '~' => exec(count, Verb::OnSelection(Op::Switchcase), None),
            '`' => exec(count, Verb::OnSelection(Op::Lowercase), None),
            // Insert at the line's first non-blank, append past its last
            // grapheme. Both collapse first: insert mode rests between
            // graphemes, so the block cursor must not survive the switch.
            'I' => exec(
                count,
                Verb::CollapsingMotion(MotionTarget::LineStartNonBlank),
                Some(HelixMode::Insert),
            ),
            'A' => exec(
                count,
                Verb::CollapsingMotion(MotionTarget::LineEdge(Direction::Forward)),
                Some(HelixMode::Insert),
            ),
            'v' => match mode {
                HelixMode::Normal => exec(count, Verb::ChangeMode, Some(HelixMode::Select)),
                HelixMode::Select => exec(count, Verb::ChangeMode, Some(HelixMode::Normal)),
                _ => Outcome::Reject,
            },
            'i' => exec(
                count,
                Verb::Collapse(Direction::Backward),
                Some(HelixMode::Insert),
            ),
            'a' => exec(
                count,
                Verb::Collapse(Direction::Forward),
                Some(HelixMode::Insert),
            ),
            'd' => exec(count, Verb::OnSelection(Op::Cut), Some(HelixMode::Normal)),
            'c' => exec(
                count,
                Verb::OnSelection(Op::Change),
                Some(HelixMode::Insert),
            ),
            'y' => exec(count, Verb::OnSelection(Op::Yank), Some(HelixMode::Normal)),
            'o' => exec(
                count,
                Verb::OpenLine(Direction::Forward),
                Some(HelixMode::Insert),
            ),
            'O' => exec(
                count,
                Verb::OpenLine(Direction::Backward),
                Some(HelixMode::Insert),
            ),
            'u' => exec(count, Verb::Undo, None),
            'U' => exec(count, Verb::Redo, None),
            'p' => exec(
                count,
                Verb::Paste(Direction::Forward),
                Some(HelixMode::Normal),
            ),
            'P' => exec(
                count,
                Verb::Paste(Direction::Backward),
                Some(HelixMode::Normal),
            ),
            _ => Outcome::Reject,
        },
        KeyCode::Enter => exec(count, Verb::Submit, Some(HelixMode::Insert)),
        // Esc deviates from helix, which keeps the selection in normal mode:
        // the single engine-level `Esc` event both dismisses menus and clears
        // the selection, and with `;` not yet bound it is also the only way to
        // drop a selection.
        KeyCode::Esc => match mode {
            HelixMode::Normal => exec(count, Verb::Deselect, None),
            HelixMode::Select => exec(count, Verb::ChangeMode, Some(HelixMode::Normal)),
            HelixMode::Insert => Outcome::Reject,
        },
        _ => Outcome::Reject,
    }
}

/// Lowers an `Action` onto `ReedlineEvent`
fn lower(action: Action, mode: HelixMode) -> ReedlineEvent {
    let event = match action.verb {
        // The two motion verbs differ only in what normal mode does with the
        // span; select mode extends either way.
        Verb::SelectingMotion(target) | Verb::CollapsingMotion(target) => match mode {
            HelixMode::Normal => action.repeated(match action.verb {
                Verb::SelectingMotion(_) => EditCommand::Select(target),
                _ => EditCommand::Move(target),
            }),
            HelixMode::Select => action.repeated(EditCommand::Extend(target)),
            HelixMode::Insert => {
                // unreachable at runtime: dispatch guards against insert mode
                ReedlineEvent::None
            }
        },
        Verb::OnSelection(op) => match op {
            // Helix has no linewise register: `d` and `c` cut exactly the
            // selection, whatever it spans. They differ only in `next_mode`,
            // which `interpret` already set.
            Op::Cut | Op::Change => ReedlineEvent::Edit(vec![EditCommand::CutSelection {
                granularity: Granularity::CharWise,
            }]),
            Op::Yank => ReedlineEvent::Edit(vec![EditCommand::CopySelection]),
            Op::Replace(ch) => ReedlineEvent::Edit(vec![EditCommand::ReplaceChar(ch)]),
            Op::Switchcase => ReedlineEvent::Edit(vec![EditCommand::SwitchcaseSelection]),
            Op::Lowercase => ReedlineEvent::Edit(vec![EditCommand::LowercaseSelection]),
        },
        Verb::Collapse(dir) => ReedlineEvent::Edit(vec![EditCommand::CollapseSelection(dir)]),
        // Only the first open seeks; the rest go *above* the blank line it just
        // made. A repeated `InsertNewlineBelow` would find no `\n` past that
        // line and append at the buffer end, and a plain `InsertNewline` would
        // delete the resting selection, which under `BlockOverNewline` always
        // covers a grapheme.
        Verb::OpenLine(direction) => {
            let first = match direction {
                Direction::Forward => EditCommand::InsertNewlineBelow,
                Direction::Backward => EditCommand::InsertNewlineAbove,
            };
            let mut cmds = vec![first];
            cmds.resize(action.count, EditCommand::InsertNewlineAbove);
            ReedlineEvent::Edit(cmds)
        }
        Verb::Undo => action.repeated(EditCommand::Undo),
        Verb::Redo => action.repeated(EditCommand::Redo),
        Verb::Paste(direction) => ReedlineEvent::Edit(vec![EditCommand::PasteAtSelectionEdge {
            direction,
            count: action.count,
        }]),
        // Each press grows the selection one line, thus a count is just the
        // command repeated: it re-reads the selection every time.
        Verb::SelectAll => ReedlineEvent::Edit(vec![EditCommand::SelectAll]),
        Verb::SelectLine => action.repeated(EditCommand::SelectLine),
        Verb::Deselect => ReedlineEvent::Multiple(vec![ReedlineEvent::Esc, ReedlineEvent::Repaint]),
        Verb::ChangeMode => ReedlineEvent::None,
        // `Up`/`Down` already carry the whole rule: move by line while another
        // line is there, walk history at the buffer edge, and prefix-search it
        // when the caret sits at the buffer end. A menu takes the keys first, or
        // `j` would move the caret out from under an open one.
        //
        // Select mode extends by line instead and never reaches history, which
        // would replace the buffer the selection is anchored in. `Multiple`
        // carries the count, since `repeated` only multiplies `EditCommand`s.
        Verb::LineOrHistory(direction) => {
            let event = match mode {
                // `MoveLine*`, not `Extend(MotionTarget::Line)`: the target lands
                // on the line *start*, while `line_down_target` keeps the column,
                // so only this reaches the grapheme normal mode would land on.
                HelixMode::Select => ReedlineEvent::Edit(vec![match direction {
                    Direction::Forward => EditCommand::MoveLineDown { select: true },
                    Direction::Backward => EditCommand::MoveLineUp { select: true },
                }]),
                _ => ReedlineEvent::UntilFound(match direction {
                    Direction::Forward => vec![ReedlineEvent::MenuDown, ReedlineEvent::Down],
                    Direction::Backward => vec![ReedlineEvent::MenuUp, ReedlineEvent::Up],
                }),
            };
            ReedlineEvent::Multiple(vec![event; action.count])
        }
        // Collapse forward first, as `a` does. The resting selection outlives the
        // `next_mode` flip to insert, so `InsertNewline` on incomplete input
        // opens with `delete_selection` and eats the covered grapheme, and
        // `submit_buffer`'s final repaint leaves the selection highlight in the
        // scrollback. Forward specifically: the break belongs *past* the covered
        // grapheme, where `Deselect` would land before it and vi's `MoveRight`
        // one beyond, since a helix head already sits on the far edge.
        Verb::Submit => {
            return ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::CollapseSelection(Direction::Forward)]),
                ReedlineEvent::Enter,
            ]);
        }
    };

    if action.next_mode.is_some() {
        ReedlineEvent::Multiple(vec![event, ReedlineEvent::Repaint])
    } else {
        event
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::ReedlineRawEvent;
    use pretty_assertions::assert_eq;
    use rstest::rstest;

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

    fn chr(c: char) -> ReedlineRawEvent {
        let modifiers = if c.is_ascii_uppercase() {
            KeyModifiers::SHIFT
        } else {
            KeyModifiers::NONE
        };
        key(KeyCode::Char(c), modifiers)
    }

    fn kev(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, modifiers)
    }

    fn normal() -> Helix {
        Helix {
            mode: HelixMode::Normal,
            ..Default::default()
        }
    }

    fn w() -> MotionTarget {
        word(WordKind::Word, WordEdge::Start, Direction::Forward)
    }

    // ---- insert path ----

    #[test]
    fn defaults_to_insert_and_inserts_chars() {
        let mut helix = Helix::default();
        assert_eq!(
            helix.edit_mode(),
            PromptEditMode::Helix(PromptHelixMode::Insert)
        );
        assert_eq!(
            helix.parse_event(chr('a')),
            ReedlineEvent::Edit(vec![EditCommand::InsertChar('a')])
        );
    }

    #[test]
    fn insert_accepts_altgr_chars() {
        let mut helix = Helix::default();
        assert_eq!(
            helix.parse_event(key(
                KeyCode::Char('µ'),
                KeyModifiers::CONTROL | KeyModifiers::ALT
            )),
            ReedlineEvent::Edit(vec![EditCommand::InsertChar('µ')])
        );
    }

    #[test]
    fn insert_esc_enters_normal() {
        let mut helix = Helix::default();
        assert_eq!(
            helix.parse_event(key(KeyCode::Esc, KeyModifiers::NONE)),
            ReedlineEvent::Multiple(vec![ReedlineEvent::Esc, ReedlineEvent::Repaint])
        );
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[test]
    fn insert_enter_submits_only_without_modifiers() {
        let mut helix = Helix::default();
        assert_eq!(
            helix.parse_event(key(KeyCode::Enter, KeyModifiers::NONE)),
            ReedlineEvent::Enter
        );
        // unbound Enter chords must not submit
        assert_eq!(
            helix.parse_event(key(KeyCode::Enter, KeyModifiers::CONTROL)),
            ReedlineEvent::None
        );
    }

    // ---- motions ----

    #[rstest]
    #[case('w', WordKind::Word, WordEdge::Start, Direction::Forward)]
    #[case('W', WordKind::LongWord, WordEdge::Start, Direction::Forward)]
    #[case('e', WordKind::Word, WordEdge::End, Direction::Forward)]
    #[case('E', WordKind::LongWord, WordEdge::End, Direction::Forward)]
    #[case('b', WordKind::Word, WordEdge::Start, Direction::Backward)]
    #[case('B', WordKind::LongWord, WordEdge::Start, Direction::Backward)]
    fn word_motions_select_in_normal_mode(
        #[case] c: char,
        #[case] kind: WordKind,
        #[case] edge: WordEdge,
        #[case] direction: Direction,
    ) {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![EditCommand::Select(word(kind, edge, direction))])
        );
    }

    #[test]
    fn word_motion_extends_in_select_mode() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Extend(w())])
        );
    }

    #[test]
    fn h_and_l_collapse_in_normal_extend_in_select() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr('l')),
            ReedlineEvent::Edit(vec![EditCommand::Move(MotionTarget::Grapheme(
                Direction::Forward
            ))])
        );
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(chr('h')),
            ReedlineEvent::Edit(vec![EditCommand::Extend(MotionTarget::Grapheme(
                Direction::Backward
            ))])
        );
    }

    // ---- counts ----

    #[test]
    fn count_repeats_motion() {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('3')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w()); 3])
        );
        assert_eq!(helix.count, None);
    }

    #[test]
    fn x_selects_a_line_once_per_count() {
        // Repeating composes here: each application re-reads the selection and
        // grows it by one line.
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr('x')),
            ReedlineEvent::Edit(vec![EditCommand::SelectLine])
        );
        assert_eq!(helix.parse_event(chr('3')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr('x')),
            ReedlineEvent::Edit(vec![EditCommand::SelectLine; 3])
        );
    }

    #[test]
    fn count_accumulates_digits() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('1'));
        let _ = helix.parse_event(chr('2'));
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w()); 12])
        );
    }

    #[test]
    fn leading_zero_is_not_a_count() {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('0')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w())])
        );
    }

    #[test]
    fn live_count_suppresses_table_bindings() {
        // rule from #693: live sequence state wins over the lookup table
        let mut helix = normal();
        let _ = helix.parse_event(chr('3'));
        assert_eq!(
            helix.parse_event(key(KeyCode::Char('c'), KeyModifiers::CONTROL)),
            ReedlineEvent::None
        );
        // the rejected chord killed the count
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w())])
        );
    }

    #[test]
    fn ctrl_c_uses_common_control_binding() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(key(KeyCode::Char('c'), KeyModifiers::CONTROL)),
            ReedlineEvent::CtrlC
        );
    }

    // ---- the select-mode keybinding table ----

    #[test]
    fn select_mode_consults_its_own_table() {
        // Arrows mirror their modal siblings: `l` extends by grapheme, `k`
        // moves by line without reaching menus or history.
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(key(KeyCode::Right, KeyModifiers::NONE)),
            ReedlineEvent::Edit(vec![EditCommand::Extend(MotionTarget::Grapheme(
                Direction::Forward
            ))])
        );
        assert_eq!(
            helix.parse_event(key(KeyCode::Up, KeyModifiers::NONE)),
            ReedlineEvent::Edit(vec![EditCommand::MoveLineUp { select: true }])
        );
    }

    #[test]
    fn normal_mode_arrows_keep_menu_navigation() {
        // The select table must not leak into normal mode, where an open menu
        // takes the arrows first.
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(key(KeyCode::Left, KeyModifiers::NONE)),
            ReedlineEvent::UntilFound(vec![ReedlineEvent::MenuLeft, ReedlineEvent::Left])
        );
    }

    #[test]
    fn select_mode_backspace_extends() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(key(KeyCode::Backspace, KeyModifiers::NONE)),
            ReedlineEvent::Edit(vec![EditCommand::Extend(MotionTarget::Grapheme(
                Direction::Backward
            ))])
        );
    }

    #[test]
    fn select_mode_home_and_end_extend_to_the_line_edges() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(key(KeyCode::Home, KeyModifiers::NONE)),
            ReedlineEvent::Edit(vec![EditCommand::Extend(MotionTarget::LineEdge(
                Direction::Backward
            ))])
        );
        assert_eq!(
            helix.parse_event(key(KeyCode::End, KeyModifiers::NONE)),
            ReedlineEvent::Edit(vec![EditCommand::Extend(MotionTarget::LineEdge(
                Direction::Forward
            ))])
        );
    }

    #[test]
    fn custom_select_table_shadows_the_default() {
        let mut bindings = default_helix_select_keybindings();
        bindings.add_binding(
            KeyModifiers::NONE,
            KeyCode::Right,
            ReedlineEvent::ClearScreen,
        );
        let mut helix = Helix {
            mode: HelixMode::Normal,
            ..Default::default()
        }
        .with_select_keybindings(bindings);
        // normal mode still uses the untouched normal table
        assert_eq!(
            helix.parse_event(key(KeyCode::Right, KeyModifiers::NONE)),
            ReedlineEvent::UntilFound(vec![
                ReedlineEvent::HistoryHintComplete,
                ReedlineEvent::MenuRight,
                ReedlineEvent::Right,
            ])
        );
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(key(KeyCode::Right, KeyModifiers::NONE)),
            ReedlineEvent::ClearScreen
        );
    }

    // ---- pending sequences ----

    #[test]
    fn find_waits_for_char_then_selects() {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('f')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr('x')),
            ReedlineEvent::Edit(vec![EditCommand::Select(MotionTarget::Find {
                ch: 'x',
                direction: Direction::Forward,
                stop: FindStop::On,
            })])
        );
    }

    #[test]
    fn till_backward_uses_stop_before() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('T'));
        assert_eq!(
            helix.parse_event(chr('a')),
            ReedlineEvent::Edit(vec![EditCommand::Select(MotionTarget::Find {
                ch: 'a',
                direction: Direction::Backward,
                stop: FindStop::Before,
            })])
        );
    }

    #[test]
    fn count_survives_into_pending() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('2'));
        let _ = helix.parse_event(chr('f'));
        let target = MotionTarget::Find {
            ch: 'x',
            direction: Direction::Forward,
            stop: FindStop::On,
        };
        assert_eq!(
            helix.parse_event(chr('x')),
            ReedlineEvent::Edit(vec![EditCommand::Select(target); 2])
        );
    }

    #[test]
    fn find_accepts_altgr_argument() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('f'));
        assert_eq!(
            helix.parse_event(key(
                KeyCode::Char('@'),
                KeyModifiers::CONTROL | KeyModifiers::ALT
            )),
            ReedlineEvent::Edit(vec![EditCommand::Select(MotionTarget::Find {
                ch: '@',
                direction: Direction::Forward,
                stop: FindStop::On,
            })])
        );
    }

    #[test]
    fn altgr_char_is_not_a_command() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(key(
                KeyCode::Char('w'),
                KeyModifiers::CONTROL | KeyModifiers::ALT
            )),
            ReedlineEvent::None
        );
        assert_eq!(helix.pending, None);
    }

    #[test]
    fn replace_waits_for_char() {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('r')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr('z')),
            ReedlineEvent::Edit(vec![EditCommand::ReplaceChar('z')])
        );
    }

    // ---- goto ----

    #[rstest]
    #[case('h', MotionTarget::LineEdge(Direction::Backward))]
    #[case('l', MotionTarget::LineEdge(Direction::Forward))]
    #[case('g', MotionTarget::BufferEdge(Direction::Backward))]
    #[case('e', MotionTarget::BufferEdge(Direction::Forward))]
    fn goto_moves_in_normal_and_extends_in_select(#[case] c: char, #[case] target: MotionTarget) {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('g')), ReedlineEvent::None);
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![EditCommand::Move(target)])
        );

        let _ = helix.parse_event(chr('v'));
        let _ = helix.parse_event(chr('g'));
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![EditCommand::Extend(target)])
        );
    }

    #[test]
    fn g_absorbs_without_emitting() {
        let mut helix = normal();
        assert_eq!(helix.parse_event(chr('g')), ReedlineEvent::None);
        assert_eq!(helix.pending, Some(Pending::Goto));
    }

    #[rstest]
    #[case('h', MotionTarget::LineEdge(Direction::Backward))]
    #[case('l', MotionTarget::LineEdge(Direction::Forward))]
    #[case('e', MotionTarget::BufferEdge(Direction::Forward))]
    fn goto_shadows_the_bare_binding_for_the_same_key(
        #[case] c: char,
        #[case] target: MotionTarget,
    ) {
        // `dispatch` checks `pending` before the table and before `interpret`.
        let mut helix = normal();
        let bare = helix.parse_event(chr(c));
        assert_ne!(bare, ReedlineEvent::Edit(vec![EditCommand::Move(target)]));

        let _ = helix.parse_event(chr('g'));
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![EditCommand::Move(target)])
        );
    }

    #[test]
    fn goto_keeps_select_mode() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        let _ = helix.parse_event(chr('g'));
        let _ = helix.parse_event(chr('h'));
        assert_eq!(helix.mode, HelixMode::Select);
    }

    #[test]
    fn unbound_goto_target_rejects_and_clears() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('g'));
        assert_eq!(helix.parse_event(chr('z')), ReedlineEvent::None);
        assert_eq!(helix.pending, None);
        // the machine is usable again, not stuck holding the prefix
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w())])
        );
    }

    #[test]
    fn esc_cancels_pending_goto() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('g'));
        let _ = helix.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));
        assert_eq!(helix.pending, None);
        // `h` is a grapheme step again, not a goto target
        assert_eq!(
            helix.parse_event(chr('h')),
            ReedlineEvent::Edit(vec![EditCommand::Move(MotionTarget::Grapheme(
                Direction::Backward
            ))])
        );
    }

    #[test]
    fn a_live_count_rejects_the_goto_prefix() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('3'));
        assert_eq!(helix.parse_event(chr('g')), ReedlineEvent::None);
        assert_eq!(helix.pending, None);
        assert_eq!(helix.count, None);
        assert_eq!(helix.parse_event(chr('g')), ReedlineEvent::None);
        assert_eq!(helix.pending, Some(Pending::Goto));
    }

    #[test]
    fn a_typed_one_is_still_a_count() {
        // `unwrap_or(1)` here would make `1gg` silently become `gg`.
        let mut helix = normal();
        let _ = helix.parse_event(chr('1'));
        assert_eq!(helix.count, Some(1));
        assert_eq!(helix.parse_event(chr('g')), ReedlineEvent::None);
        assert_eq!(helix.pending, None);
    }

    #[test]
    fn esc_cancels_pending_sequence() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('2'));
        let _ = helix.parse_event(chr('f'));
        let _ = helix.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));
        assert_eq!(helix.count, None);
        assert_eq!(helix.pending, None);
        // the next key is interpreted fresh, not as a find argument
        assert_eq!(
            helix.parse_event(chr('w')),
            ReedlineEvent::Edit(vec![EditCommand::Select(w())])
        );
    }

    // ---- operators and mode transitions ----

    #[rstest]
    #[case('d', Op::Cut, Some(HelixMode::Normal))]
    #[case('c', Op::Change, Some(HelixMode::Insert))]
    #[case('y', Op::Yank, Some(HelixMode::Normal))]
    fn operator_next_mode_is_mode_independent(
        #[case] c: char,
        #[case] op: Op,
        #[case] next_mode: Option<HelixMode>,
    ) {
        // operators leave select mode; `next_mode` must not depend on where
        // they started (this is where the copy-paste bugs lived)
        for mode in [HelixMode::Normal, HelixMode::Select] {
            assert_eq!(
                interpret(mode, None, kev(KeyCode::Char(c), KeyModifiers::NONE)),
                Outcome::Execute(Action {
                    count: 1,
                    verb: Verb::OnSelection(op),
                    next_mode,
                })
            );
        }
    }

    #[rstest]
    #[case('i', Direction::Backward)]
    #[case('a', Direction::Forward)]
    fn insert_entries_collapse_to_an_edge(#[case] c: char, #[case] direction: Direction) {
        for mode in [HelixMode::Normal, HelixMode::Select] {
            assert_eq!(
                interpret(mode, None, kev(KeyCode::Char(c), KeyModifiers::NONE)),
                Outcome::Execute(Action {
                    count: 1,
                    verb: Verb::Collapse(direction),
                    next_mode: Some(HelixMode::Insert),
                })
            );
        }
    }

    #[test]
    fn v_toggles_between_normal_and_select() {
        assert_eq!(
            interpret(
                HelixMode::Normal,
                None,
                kev(KeyCode::Char('v'), KeyModifiers::NONE)
            ),
            Outcome::Execute(Action {
                count: 1,
                verb: Verb::ChangeMode,
                next_mode: Some(HelixMode::Select),
            })
        );
        assert_eq!(
            interpret(
                HelixMode::Select,
                None,
                kev(KeyCode::Char('v'), KeyModifiers::NONE)
            ),
            Outcome::Execute(Action {
                count: 1,
                verb: Verb::ChangeMode,
                next_mode: Some(HelixMode::Normal),
            })
        );
    }

    #[test]
    fn esc_deselects_in_normal_and_leaves_select() {
        assert_eq!(
            interpret(
                HelixMode::Normal,
                None,
                kev(KeyCode::Esc, KeyModifiers::NONE)
            ),
            Outcome::Execute(Action {
                count: 1,
                verb: Verb::Deselect,
                next_mode: None,
            })
        );
        assert_eq!(
            interpret(
                HelixMode::Select,
                None,
                kev(KeyCode::Esc, KeyModifiers::NONE)
            ),
            Outcome::Execute(Action {
                count: 1,
                verb: Verb::ChangeMode,
                next_mode: Some(HelixMode::Normal),
            })
        );
    }

    #[test]
    fn operators_leave_select_mode() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(chr('d')),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::CutSelection {
                    granularity: Granularity::CharWise,
                }]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[test]
    fn c_cuts_and_enters_insert() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr('c')),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::CutSelection {
                    granularity: Granularity::CharWise,
                }]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.mode, HelixMode::Insert);
    }

    #[test]
    fn y_copies_and_stays_normal() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr('y')),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::CopySelection]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[test]
    fn esc_in_normal_deselects() {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(key(KeyCode::Esc, KeyModifiers::NONE)),
            ReedlineEvent::Multiple(vec![ReedlineEvent::Esc, ReedlineEvent::Repaint])
        );
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[test]
    fn esc_returns_from_select_despite_table_binding() {
        // Esc is exempt from the table lookup; the generic Esc binding must
        // not strand select mode
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        let _ = helix.parse_event(key(KeyCode::Esc, KeyModifiers::NONE));
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[test]
    fn enter_collapses_then_submits_and_enters_insert() {
        // Enter must still escape the repaint rule: `next_mode` would otherwise
        // append a `Repaint` that the submitting `Enter` never reaches, since
        // the engine returns on the first `Exits`. Asserted on the event rather
        // than driven, since escaping that wrapping is not observable from the
        // editor's state.
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(key(KeyCode::Enter, KeyModifiers::NONE)),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::CollapseSelection(Direction::Forward)]),
                ReedlineEvent::Enter,
            ])
        );
        assert_eq!(helix.mode, HelixMode::Insert);
    }

    // ---- undo / redo ----

    #[rstest]
    #[case('u', EditCommand::Undo)]
    #[case('U', EditCommand::Redo)]
    fn undo_redo_lower_to_bare_edits(#[case] c: char, #[case] expected: EditCommand) {
        // `next_mode` is None, so these must escape the repaint wrap in `lower`:
        // no mode indicator changed, and an `Edit` repaints on its own. `U`
        // arrives with SHIFT, which `is_plain_char` accepts.
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![expected])
        );
    }

    #[test]
    fn count_repeats_undo() {
        // This is the reason undo lives in the machine rather than the binding
        // table: `dispatch` only consults the table while no count is live, so a
        // table-bound `u` would give a working `u` and a silently dead `3u`.
        let mut helix = normal();
        let _ = helix.parse_event(chr('3'));
        assert_eq!(
            helix.parse_event(chr('u')),
            ReedlineEvent::Edit(vec![EditCommand::Undo; 3])
        );
        assert_eq!(helix.count, None);
    }

    #[rstest]
    #[case('u', EditCommand::Undo)]
    #[case('U', EditCommand::Redo)]
    fn undo_redo_keep_select_mode(#[case] c: char, #[case] expected: EditCommand) {
        // Select mode is sticky: only operators and Esc leave it, and undo is
        // neither. Asserted on the machine rather than on `interpret`'s
        // `next_mode`, since "the mode survives" is the actual claim.
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Edit(vec![expected])
        );
        assert_eq!(helix.mode, HelixMode::Select);
    }

    // ---- paste ----

    #[rstest]
    #[case('p', Direction::Forward)]
    #[case('P', Direction::Backward)]
    fn paste_carries_the_edge_direction(#[case] c: char, #[case] direction: Direction) {
        // `next_mode` is `Some`, so the repaint rule wraps the edit — same shape
        // the operators produce.
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::PasteAtSelectionEdge {
                    direction,
                    count: 1
                }]),
                ReedlineEvent::Repaint,
            ])
        );
    }

    #[test]
    fn paste_carries_the_count_in_the_command() {
        // Paste must not go through `Action::repeated`: repeating the event
        // re-anchors at each paste, so the selection would end up covering only
        // the last copy. One command carrying 3, not three commands.
        let mut helix = normal();
        let _ = helix.parse_event(chr('3'));
        assert_eq!(
            helix.parse_event(chr('p')),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![EditCommand::PasteAtSelectionEdge {
                    direction: Direction::Forward,
                    count: 3,
                }]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.count, None);
    }

    #[rstest]
    #[case('p')]
    #[case('P')]
    fn paste_leaves_select_mode(#[case] c: char) {
        let mut helix = normal();
        let _ = helix.parse_event(chr('v'));
        let _ = helix.parse_event(chr(c));
        assert_eq!(helix.mode, HelixMode::Normal);
    }

    #[rstest]
    #[case('p', KeyModifiers::NONE, Direction::Forward)]
    #[case('P', KeyModifiers::SHIFT, Direction::Backward)]
    fn paste_next_mode_is_mode_independent(
        #[case] c: char,
        #[case] modifiers: KeyModifiers,
        #[case] direction: Direction,
    ) {
        // Like the operators, paste's `next_mode` must not depend on where it
        // started: it returns to normal from select and is inert in normal.
        for mode in [HelixMode::Normal, HelixMode::Select] {
            assert_eq!(
                interpret(mode, None, kev(KeyCode::Char(c), modifiers)),
                Outcome::Execute(Action {
                    count: 1,
                    verb: Verb::Paste(direction),
                    next_mode: Some(HelixMode::Normal),
                })
            );
        }
    }

    #[test]
    fn paste_event_produces_insert_string() {
        let mut helix = Helix::default();
        let paste = ReedlineRawEvent::try_from(Event::Paste("hello".to_string())).unwrap();
        assert_eq!(
            helix.parse_event(paste),
            ReedlineEvent::Edit(vec![EditCommand::InsertString("hello".to_string())])
        );
    }

    // ---- open line ----

    #[rstest]
    #[case('o', EditCommand::InsertNewlineBelow)]
    #[case('O', EditCommand::InsertNewlineAbove)]
    fn open_line_enters_insert(#[case] c: char, #[case] expected: EditCommand) {
        let mut helix = normal();
        assert_eq!(
            helix.parse_event(chr(c)),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![expected]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.mode, HelixMode::Insert);
    }

    #[rstest]
    #[case('o', KeyModifiers::NONE, Direction::Forward)]
    #[case('O', KeyModifiers::SHIFT, Direction::Backward)]
    fn open_line_next_mode_is_mode_independent(
        #[case] c: char,
        #[case] modifiers: KeyModifiers,
        #[case] direction: Direction,
    ) {
        for mode in [HelixMode::Normal, HelixMode::Select] {
            assert_eq!(
                interpret(mode, None, kev(KeyCode::Char(c), modifiers)),
                Outcome::Execute(Action {
                    count: 1,
                    verb: Verb::OpenLine(direction),
                    next_mode: Some(HelixMode::Insert),
                })
            );
        }
    }

    #[test]
    fn count_seeks_once_then_opens_above() {
        let mut helix = normal();
        let _ = helix.parse_event(chr('3'));
        assert_eq!(
            helix.parse_event(chr('o')),
            ReedlineEvent::Multiple(vec![
                ReedlineEvent::Edit(vec![
                    EditCommand::InsertNewlineBelow,
                    EditCommand::InsertNewlineAbove,
                    EditCommand::InsertNewlineAbove,
                ]),
                ReedlineEvent::Repaint,
            ])
        );
        assert_eq!(helix.count, None);
    }
}