hjkl 0.33.5

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
use super::*;

// ── Phase 2c-vi: SelectRegister reducer integration tests ─────────────────

/// `"add` — delete line into register a; verify register a contains the line.
#[test]
fn quote_a_then_dd_deletes_into_register_a() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world\nline two");
    // Move cursor to first line (already there after seed).
    assert_eq!(app.active_editor().cursor().0, 0);

    // `"a` sets pending register to 'a' via reducer, then `dd` deletes the line.
    drive_key(&mut app, key(KeyCode::Char('"')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    drive_key(&mut app, key(KeyCode::Char('d')));
    drive_key(&mut app, key(KeyCode::Char('d')));

    // Register 'a' must contain the deleted line text.
    let regs = app.active_editor().registers();
    let slot = regs.read('a');
    assert!(slot.is_some(), "register 'a' should be set after \"add");
    let text = &slot.unwrap().text;
    assert!(
        text.contains("hello world"),
        "register 'a' should contain 'hello world', got {text:?}"
    );
    drop(regs);
    // Buffer should only have the second line.
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines, vec!["line two"], "\"add must delete first line");
}

/// `"ayy` → move → `"ap` round-trips through register a.
#[test]
fn quote_a_then_yy_then_quote_a_then_p_pastes_named_register() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "first line\nsecond line");

    // `"ayy` — yank first line into register a.
    drive_key(&mut app, key(KeyCode::Char('"')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    drive_key(&mut app, key(KeyCode::Char('y')));
    drive_key(&mut app, key(KeyCode::Char('y')));

    // Verify register a has the yanked text.
    let regs = app.active_editor().registers();
    let slot = regs.read('a');
    assert!(slot.is_some(), "register 'a' must be set after \"ayy");
    let text = slot.unwrap().text.clone();
    drop(regs);
    assert!(
        text.contains("first line"),
        "register 'a' should contain 'first line', got {text:?}"
    );

    // Move down one line.
    drive_key(&mut app, key(KeyCode::Char('j')));
    assert_eq!(
        app.active_editor().cursor().0,
        1,
        "cursor must be on line 1"
    );

    // `"ap` — paste from register a.
    drive_key(&mut app, key(KeyCode::Char('"')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    drive_key(&mut app, key(KeyCode::Char('p')));

    // Buffer should now have "first line" duplicated after line two.
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert!(lines.len() >= 3, "paste must add a line, got {lines:?}");
    assert!(
        lines.iter().any(|l| l.contains("first line")),
        "pasted content must contain 'first line', got {lines:?}"
    );
}

/// `"_dd` — delete into black-hole; unnamed register must not change.
#[test]
fn quote_underscore_then_dd_blackhole_no_unnamed_change() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "keep me\ndelete me\nkeep too");

    // Yank first line into unnamed to establish a baseline.
    drive_key(&mut app, key(KeyCode::Char('y')));
    drive_key(&mut app, key(KeyCode::Char('y')));
    let baseline = app
        .active_editor()
        .registers()
        .read('"')
        .map(|s| s.text.clone())
        .unwrap_or_default();

    // Move to second line.
    drive_key(&mut app, key(KeyCode::Char('j')));

    // `"_dd` — delete into black-hole register.
    drive_key(&mut app, key(KeyCode::Char('"')));
    drive_key(&mut app, key(KeyCode::Char('_')));
    drive_key(&mut app, key(KeyCode::Char('d')));
    drive_key(&mut app, key(KeyCode::Char('d')));

    // Unnamed register must still match the baseline yank.
    let after = app
        .active_editor()
        .registers()
        .read('"')
        .map(|s| s.text.clone())
        .unwrap_or_default();
    assert_eq!(
        baseline, after,
        "\"_dd must not overwrite the unnamed register"
    );
    // Line was deleted from the buffer.
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert!(
        !lines.iter().any(|l| l.contains("delete me")),
        "\"_dd must still delete the line from the buffer, got {lines:?}"
    );
}

/// Esc after `"` must clear the pending reducer state without setting any register.
#[test]
fn quote_then_esc_cancels() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello");

    // `"` enters SelectRegister pending state.
    drive_key(&mut app, key(KeyCode::Char('"')));
    assert!(
        app.pending_state.is_some(),
        "\" must set app pending_state to SelectRegister"
    );

    // Esc cancels.
    drive_key(&mut app, key(KeyCode::Esc));
    assert!(
        app.pending_state.is_none(),
        "Esc must clear pending_state after \""
    );
}

/// `"!` — invalid register char; pending_register must not be set and the
/// next operation uses the unnamed register.
#[test]
fn quote_invalid_char_no_register_set() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world\nsecond");

    // Yank baseline into unnamed.
    drive_key(&mut app, key(KeyCode::Char('y')));
    drive_key(&mut app, key(KeyCode::Char('y')));
    let baseline_unnamed = app
        .active_editor()
        .registers()
        .read('"')
        .map(|s| s.text.clone())
        .unwrap_or_default();

    // `"!dd` — '!' is not a valid register selector; engine ignores it.
    // After cancel the reducer clears without setting pending_register.
    drive_key(&mut app, key(KeyCode::Char('"')));
    drive_key(&mut app, key(KeyCode::Char('!')));
    // Reducer cancels on invalid key — pending_state cleared.
    assert!(
        app.pending_state.is_none(),
        "invalid register char must cancel pending_state"
    );

    // No register named '!' exists.
    let regs = app.active_editor().registers();
    let slot = regs.read('!');
    assert!(slot.is_none(), "register '!' must not exist");
    drop(regs);

    // Unnamed register unchanged.
    let after = app
        .active_editor()
        .registers()
        .read('"')
        .map(|s| s.text.clone())
        .unwrap_or_default();
    assert_eq!(
        baseline_unnamed, after,
        "unnamed register must be unchanged after \"!"
    );
}

// ── Phase 5a: mark chord pending states integration tests ─────────────────

/// `ma` then move, then `'a` — linewise mark jump round-trip.
#[test]
fn m_a_then_apostrophe_a_jumps_back_to_line() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "first line\n  second line\nthird line");
    // Jump to row 2, col 3 and set mark 'a'.
    app.active_editor_mut().jump_cursor(2, 3);
    drive_key(&mut app, key(KeyCode::Char('m')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    assert!(
        app.pending_state.is_none(),
        "pending_state must clear after ma"
    );
    // Move away to row 0.
    app.active_editor_mut().jump_cursor(0, 0);
    // `'a` — linewise jump back to row 2, first non-blank.
    drive_key(&mut app, key(KeyCode::Char('\'')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    assert!(
        app.pending_state.is_none(),
        "pending_state must clear after 'a"
    );
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "'a must jump back to mark row"
    );
    assert_window_synced_to_engine(&app);
}

/// `ma` then move, then `` `a `` — charwise mark jump round-trip.
#[test]
fn m_a_then_backtick_a_jumps_back_to_pos() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "first line\nsecond line\nthird line");
    // Jump to exact pos (1, 4) and set mark 'a'.
    app.active_editor_mut().jump_cursor(1, 4);
    drive_key(&mut app, key(KeyCode::Char('m')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    // Move away.
    app.active_editor_mut().jump_cursor(0, 0);
    // `` `a `` — charwise jump back.
    drive_key(&mut app, key(KeyCode::Char('`')));
    drive_key(&mut app, key(KeyCode::Char('a')));
    assert!(
        app.pending_state.is_none(),
        "pending_state must clear after `a"
    );
    assert_eq!(
        app.active_editor().cursor(),
        (1, 4),
        "`a must jump to exact mark position"
    );
    assert_window_synced_to_engine(&app);
}

/// `m` then `<Esc>` — Esc must cancel the SetMark chord without moving cursor.
#[test]
fn m_then_esc_cancels() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    app.active_editor_mut().jump_cursor(0, 3);
    drive_key(&mut app, key(KeyCode::Char('m')));
    assert!(
        app.pending_state.is_some(),
        "m must enter SetMark pending state"
    );
    drive_key(&mut app, key(KeyCode::Esc));
    assert!(
        app.pending_state.is_none(),
        "Esc must cancel SetMark pending state"
    );
    assert_eq!(
        app.active_editor().cursor(),
        (0, 3),
        "cursor must not move after m<Esc>"
    );
}

/// `'` then `<Esc>` — Esc must cancel the GotoMarkLine chord.
#[test]
fn apostrophe_then_esc_cancels() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    app.active_editor_mut().jump_cursor(0, 2);
    drive_key(&mut app, key(KeyCode::Char('\'')));
    assert!(
        app.pending_state.is_some(),
        "' must enter GotoMarkLine pending state"
    );
    drive_key(&mut app, key(KeyCode::Esc));
    assert!(
        app.pending_state.is_none(),
        "Esc must cancel GotoMarkLine pending state"
    );
    assert_eq!(
        app.active_editor().cursor(),
        (0, 2),
        "cursor must not move after '<Esc>"
    );
}

/// `` ` `` in Visual mode jumps charwise and keeps visual mode active.
#[test]
fn backtick_in_visual_jumps_pos() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "first line\nsecond line\nthird line");
    // Set mark 'b' at (2, 2) in Normal mode.
    app.active_editor_mut().jump_cursor(2, 2);
    drive_key(&mut app, key(KeyCode::Char('m')));
    drive_key(&mut app, key(KeyCode::Char('b')));
    // Enter Visual mode at (0, 0).
    app.active_editor_mut().jump_cursor(0, 0);
    drive_key(&mut app, key(KeyCode::Char('v')));
    assert_eq!(app.active_editor().vim_mode(), hjkl_engine::VimMode::Visual);
    // `` `b `` in Visual mode — must jump to (2, 2) via BeginPendingGotoMarkChar.
    // In Visual mode, route_chord_key dispatches non-Normal trie, which has
    // the `` ` `` binding from build_app_keymap.
    app.route_chord_key(ck('`'));
    app.route_chord_key(ck('b'));
    assert!(
        app.pending_state.is_none(),
        "pending_state must clear after `b in Visual mode"
    );
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "`b in Visual mode must jump to mark row"
    );
}

// ── Phase 5b: macro record / play integration tests ──────────────────────────

/// Helper: send keys through `route_chord_key` for macro integration tests.
/// Uses route_chord_key (not drive_key) so the recorder hook fires.
#[test]
fn q_then_esc_cancels_no_recording_started() {
    // `q<Esc>` — Esc after `q` cancels (no recording started).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");

    drive_key(&mut app, ck('q'));
    // After `q`, pending state = RecordMacroTarget.
    assert_eq!(
        app.pending_state,
        Some(hjkl_vim::PendingState::RecordMacroTarget),
        "q must set RecordMacroTarget pending state"
    );
    drive_key(&mut app, key(KeyCode::Esc));
    // Esc cancels — no recording.
    assert!(
        app.pending_state.is_none(),
        "Esc after q must clear pending_state"
    );
    assert!(
        !app.active_editor().is_recording_macro(),
        "Esc cancel must not start recording"
    );
}

#[test]
fn bare_q_during_record_stops() {
    // `qa` starts recording, bare `q` stops it.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");

    // Start recording register 'a'.
    drive_key(&mut app, ck('q'));
    drive_key(&mut app, ck('a'));
    assert!(
        app.active_editor().is_recording_macro(),
        "q a must start recording"
    );
    assert_eq!(app.active_editor().recording_register(), Some('a'));

    // Bare `q` must stop the recording (QChord branches to stop_macro_record).
    drive_key(&mut app, ck('q'));
    assert!(
        !app.active_editor().is_recording_macro(),
        "bare q must stop recording"
    );
    assert!(
        app.pending_state.is_none(),
        "pending_state must be clear after stop"
    );
}

#[test]
fn record_macro_a_j_motion_replay_plays() {
    // Record `qa j q` (move down one line), then `@a` replays it.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Record: qa j q.
    macro_key_seq(
        &mut app,
        &[
            ck('q'),
            ck('a'), // start recording into 'a'
            ck('j'), // record: move down
            ck('q'), // stop recording
        ],
    );
    assert!(
        !app.active_editor().is_recording_macro(),
        "recording must stop after second q"
    );
    // Should be on row 1 from the j motion during recording.
    assert_eq!(app.active_editor().cursor().0, 1);

    // Play: @a — should move down one more row.
    macro_key_seq(&mut app, &[ck('@'), ck('a')]);
    assert!(
        !app.active_editor().is_replaying_macro(),
        "replaying_macro must be false after replay finishes"
    );
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "@a must replay j motion (move to row 2)"
    );
}

#[test]
fn record_macro_a_insert_text_esc_motion_replays_full() {
    // Repro for: qa A test <Esc> 0 j q  → @a should re-execute the entire
    // sequence on the next line. Reported bug: replay only enters insert
    // mode at EOL and stops (text + esc + motion not replayed).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(
        &mut app,
        &[
            ck('q'),
            ck('a'), // start recording into 'a'
            ck('A'), // append at end of line → Insert mode
            ck('t'),
            ck('e'),
            ck('s'),
            ck('t'),
            key(KeyCode::Esc), // back to Normal
            ck('0'),           // start of line
            ck('j'),           // down one
            ck('q'),           // stop recording
        ],
    );
    assert!(!app.active_editor().is_recording_macro());
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "line0test",
        "recording itself must append 'test' to line0"
    );
    assert_eq!(
        app.active_editor().cursor(),
        (1, 0),
        "after recording, cursor must be at row 1, col 0"
    );

    macro_key_seq(&mut app, &[ck('@'), ck('a')]);
    assert!(!app.active_editor().is_replaying_macro());
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 1),
        "line1test",
        "@a must re-execute A+test on line1"
    );
    assert_eq!(
        app.active_editor().cursor(),
        (2, 0),
        "@a must end with cursor at row 2, col 0 (0 then j)"
    );
}

#[test]
fn record_macro_a_comma_text_esc_j0_replays() {
    // User scenario: qaA, this is a test<Esc>j0q  → @a
    // Expected: append ", this is a test" to current line then move down/start.
    // Actual bug report: replay went into insert at EOL then literally typed "j0".
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(
        &mut app,
        &[
            ck('q'),
            ck('a'),
            ck('A'),
            ck(','),
            ck(' '),
            ck('t'),
            ck('h'),
            ck('i'),
            ck('s'),
            ck(' '),
            ck('i'),
            ck('s'),
            ck(' '),
            ck('a'),
            ck(' '),
            ck('t'),
            ck('e'),
            ck('s'),
            ck('t'),
            key(KeyCode::Esc),
            ck('j'),
            ck('0'),
            ck('q'),
        ],
    );
    assert!(!app.active_editor().is_recording_macro());
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "line0, this is a test",
        "recording itself must append the text"
    );

    macro_key_seq(&mut app, &[ck('@'), ck('a')]);
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 1),
        "line1, this is a test",
        "@a must re-append the text on line1"
    );
}

#[test]
fn gcc_toggles_comment_on_current_line_via_app_layer() {
    // User report: `gcc` doesn't toggle line comment in the live binary.
    // Drive through the same path the event loop uses (handle_keypress →
    // route_chord_key → engine via FallThrough).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "let x = 1;\nlet y = 2;");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "// let x = 1;",
        "gcc must toggle a comment marker onto line 0"
    );
}

#[test]
fn gcc_on_doc_comment_uncomments_via_app_layer() {
    // User report: `gcc` is a no-op on `///` rustdoc lines in the live
    // binary. The toggle is supposed to detect "already commented"
    // (starts_with("//") covers "///") and uncomment by stripping one
    // "//" + one optional space — turning `/// foo` → `/ foo`.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "/// doc line\nfn foo() {}");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    let line0 = hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0);
    assert_ne!(
        line0, "/// doc line",
        "gcc must mutate the doc-comment line; got {line0:?} (no-op == bug)"
    );
}

#[test]
fn gc_in_visual_line_toggles_selection_via_app_layer() {
    // Visual `gc` must fire toggle_comment_range on the active selection
    // immediately — no second key required. Before the routing fix, gc in
    // visual went through engine.after_g which set Pending::Op{Comment}
    // and stalled waiting for a motion that visual mode never delivers.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "let x = 1;\nlet y = 2;\nlet z = 3;");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // V → visual-line, j → extend down, gc → toggle.
    macro_key_seq(&mut app, &[ck('V'), ck('j'), ck('g'), ck('c')]);
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines[0], "// let x = 1;",
        "visual gc must comment line 0; got {lines:?}"
    );
    assert_eq!(
        lines[1], "// let y = 2;",
        "visual gc must comment line 1; got {lines:?}"
    );
    assert_eq!(
        lines[2], "let z = 3;",
        "visual gc must NOT touch line 2 (outside selection); got {lines:?}"
    );
}

#[test]
fn gc_in_visual_charwise_toggles_selection_via_app_layer() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "let x = 1;\nlet y = 2;");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('v'), ck('j'), ck('g'), ck('c')]);
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines[0], "// let x = 1;");
    assert_eq!(lines[1], "// let y = 2;");
}

#[test]
fn gcc_then_gcc_round_trips_after_routing_fix() {
    // Direct regression for the user-reported intermittent gcc no-op.
    // After the routing fix, gc/gcc go through the App-level AfterOp
    // reducer instead of engine Pending::Op, so the 1000ms engine chord-
    // timeout can no longer drop the third `c` and reroute it into the
    // bare-`c` Change operator path.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "let x = 1;\nlet y = 2;");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "// let x = 1;"
    );
    // Critical: no engine pending leak between invocations.
    assert!(!app.active_editor().is_chord_pending());
    assert!(app.pending_state.is_none());

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "let x = 1;",
        "second gcc must uncomment after the routing fix"
    );
    assert!(!app.active_editor().is_chord_pending());
}

#[test]
fn gcc_with_count_3_toggles_3_lines_via_app_layer() {
    // `3gcc` — comment 3 lines starting at cursor.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "a\nb\nc\nd\ne");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('3'), ck('g'), ck('c'), ck('c')]);
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines[0], "// a");
    assert_eq!(lines[1], "// b");
    assert_eq!(lines[2], "// c");
    assert_eq!(lines[3], "d", "line 3 must stay outside the count range");
    assert_eq!(lines[4], "e");
}

#[test]
fn gc_with_motion_j_toggles_2_lines_via_app_layer() {
    // `gcj` — comment current line plus one line down (motion j).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "a\nb\nc");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('j')]);
    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(lines[0], "// a");
    assert_eq!(lines[1], "// b");
    assert_eq!(lines[2], "c");
}

#[test]
fn gcc_on_indented_doc_comment_via_app_layer() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "    /// indented doc\nfn foo() {}");
    app.active_editor_mut().set_filetype("rust");
    app.active_editor_mut().jump_cursor(0, 4);
    app.sync_viewport_from_editor();

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    let line0 = hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0);
    assert_ne!(
        line0, "    /// indented doc",
        "gcc on indented doc-comment must mutate; got {line0:?}"
    );
}

#[test]
fn opening_rust_file_auto_sets_filetype_so_gcc_works() {
    // User report: opening a .rs file from the CLI and pressing `gcc`
    // does nothing. Root cause: build_slot never called set_filetype, so
    // toggle_comment_range took the no-known-syntax early return. This
    // test drives the production file-open path end-to-end.
    let dir = std::env::temp_dir().join(format!("hjkl-gcc-filetype-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file_path = dir.join("a.rs");
    std::fs::write(&file_path, "let x = 1;\nlet y = 2;\n").unwrap();

    let mut app = App::new(Some(file_path.clone()), false, None, None).unwrap();
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    assert_eq!(
        app.active_editor().settings().filetype,
        "rust",
        "opening a .rs file must seed the editor's filetype to \"rust\""
    );

    macro_key_seq(&mut app, &[ck('g'), ck('c'), ck('c')]);
    assert_eq!(
        hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0),
        "// let x = 1;",
        "gcc on a freshly-opened .rs file must toggle a comment marker"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn at_at_repeats_last_macro() {
    // Record `qa j q`, play `@a`, then `@@` re-plays same macro.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Record qa j q.
    macro_key_seq(&mut app, &[ck('q'), ck('a'), ck('j'), ck('q')]);
    assert_eq!(app.active_editor().cursor().0, 1);

    // @a — plays, moves to row 2, sets last_macro = 'a'.
    macro_key_seq(&mut app, &[ck('@'), ck('a')]);
    assert_eq!(app.active_editor().cursor().0, 2);

    // @@ — repeats last macro ('a'), moves to row 3.
    macro_key_seq(&mut app, &[ck('@'), ck('@')]);
    assert_eq!(
        app.active_editor().cursor().0,
        3,
        "@@ must replay the last macro"
    );
}

#[test]
fn play_macro_with_count_3() {
    // Verify that Editor::play_macro with count=3 produces 3× the inputs,
    // which is the mechanism underlying `3@a`. We call play_macro directly
    // here because count-prefix buffering lives in the event_loop, above
    // route_chord_key, and cannot be easily injected in unit-test context.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4\nline5\nline6");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Record a simple macro into register 'a' via the public API.
    app.active_editor_mut().start_macro_record('a');
    app.active_editor_mut().record_input(hjkl_engine::Input {
        key: hjkl_engine::Key::Char('j'),
        ..Default::default()
    });
    app.active_editor_mut().stop_macro_record();

    // play_macro('a', 3) must return 3 inputs.
    let inputs = app.active_editor_mut().play_macro('a', 3);
    app.active_editor_mut().end_macro_replay();
    assert_eq!(
        inputs.len(),
        3,
        "play_macro with count=3 must return 3 inputs"
    );

    // Re-feed them through route_chord_key.
    for input in inputs {
        let ct_key = engine_input_to_key_event(input);
        if ct_key.code != KeyCode::Null {
            let consumed = app.route_chord_key(ct_key);
            if !consumed {
                hjkl_vim_tui::handle_key(app.active_editor_mut(), ct_key);
            }
            app.sync_viewport_from_editor();
        }
    }
    assert_eq!(
        app.active_editor().cursor().0,
        3,
        "3× j motions must move cursor to row 3"
    );
}

#[test]
fn record_capital_appends_to_lowercase() {
    // `qa j q` records one j. `qA k q` appends one k (opposite direction).
    // `@a` should replay both (j then k — net zero movement).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3");
    app.active_editor_mut().jump_cursor(1, 0);
    app.sync_viewport_from_editor();

    // Record qa j q.
    macro_key_seq(&mut app, &[ck('q'), ck('a'), ck('j'), ck('q')]);
    assert_eq!(app.active_editor().cursor().0, 2);

    // Record qA k q (append: moves back up from row 2 to row 1).
    macro_key_seq(&mut app, &[ck('q'), ck('A'), ck('k'), ck('q')]);
    // Cursor moved k (up) from row 2 → row 1.
    assert_eq!(app.active_editor().cursor().0, 1);

    // Now @a should replay the combined macro (j then k) — net zero move.
    // Start at row 1 after qA k q. j moves to 2, k moves back to 1.
    let start_row = app.active_editor().cursor().0; // should be 1
    macro_key_seq(&mut app, &[ck('@'), ck('a')]);
    assert_eq!(
        app.active_editor().cursor().0,
        start_row,
        "@a with capital append must replay j+k (net zero from row {start_row})"
    );
}

// ── Phase 5d: `@:` last-ex repeat ───────────────────────────────────────────

#[test]
fn at_colon_replays_last_ex() {
    // dispatch_ex("3") moves cursor to line 3 (1-based → row 2).
    // replay_last_ex() called directly must re-run `:3` and land there again.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Run :3 — cursor goes to row 2 (0-based).
    app.dispatch_ex("3");
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        ":3 must move cursor to row 2"
    );

    // Move cursor away.
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();
    assert_eq!(app.active_editor().cursor().0, 0);

    // Direct replay must bring cursor back to row 2.
    app.replay_last_ex();
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "replay_last_ex must re-run :3 and land on row 2"
    );
}

#[test]
fn at_colon_via_play_macro_arm_replays() {
    // Drive the full `@:` chord through route_chord_key so the PlayMacro arm
    // with reg==':' is exercised.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Establish last_ex_command via :3.
    app.dispatch_ex("3");
    assert_eq!(app.active_editor().cursor().0, 2);

    // Move away.
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Set up BeginPendingPlayMacro state then drive ':'.
    app.dispatch_action(
        crate::keymap_actions::AppAction::BeginPendingPlayMacro { count: 1 },
        1,
    );
    assert_eq!(
        app.pending_state,
        Some(hjkl_vim::PendingState::PlayMacroTarget { count: 1 }),
        "BeginPendingPlayMacro must set PlayMacroTarget pending state"
    );

    // Drive ':' — should commit PlayMacro { reg: ':', count: 1 } → replay_last_ex.
    let consumed = app.route_chord_key(ck(':'));
    assert!(consumed, "@: must be consumed by route_chord_key");
    assert!(
        app.pending_state.is_none(),
        "pending_state must be cleared after @: commit"
    );
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "@: chord must replay :3 and land on row 2"
    );
}

#[test]
fn at_colon_with_count_3_replays_three_times() {
    // `3@:` must run the last ex command 3 times. Use `:s` substitute to
    // verify actual repetition count — each run changes one occurrence.
    // Simpler: use line-goto commands to verify idempotent + state at end.
    // We use a toggle-able command: `:set cursorline!` toggled 3 times
    // leaves it in the opposite state from start (net odd = one toggle).
    // But cursorline may not be observable. Instead use row-goto idempotency:
    // 3@: of `:1` is same as `:1` once — cursor ends on row 0 regardless.
    // To prove N > 1 actually loops, verify last_ex_command is still "1"
    // (unchanged) and cursor is on row 0.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4");
    app.active_editor_mut().jump_cursor(2, 0);
    app.sync_viewport_from_editor();

    // Establish last_ex_command as "1" (goto line 1).
    app.dispatch_ex("1");
    assert_eq!(app.active_editor().cursor().0, 0, ":1 must go to row 0");

    // Move away so we can verify the replays actually run.
    app.active_editor_mut().jump_cursor(4, 0);
    app.sync_viewport_from_editor();

    // Set up BeginPendingPlayMacro with count=3, then drive ':'.
    app.dispatch_action(
        crate::keymap_actions::AppAction::BeginPendingPlayMacro { count: 3 },
        1,
    );
    let consumed = app.route_chord_key(ck(':'));
    assert!(consumed, "3@: must be consumed");
    // After 3 replays of :1, cursor must be at row 0 (last replay wins).
    assert_eq!(
        app.active_editor().cursor().0,
        0,
        "3@: of :1 must end with cursor at row 0"
    );
    // last_ex_command must still be "1" (replay doesn't corrupt storage).
    assert_eq!(
        app.last_ex_command.as_deref(),
        Some("1"),
        "last_ex_command must remain '1' after 3@:"
    );
}

#[test]
fn at_colon_no_prior_ex_is_noop() {
    // Fresh app with no prior :cmd — replay_last_ex must be a silent no-op.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    assert!(
        app.last_ex_command.is_none(),
        "fresh app must have no last_ex_command"
    );

    // Direct call — must not crash.
    app.replay_last_ex();

    // Nothing changed.
    assert_eq!(
        app.active_editor().cursor().0,
        0,
        "cursor must be unchanged"
    );
    assert!(
        app.bus.last_body().is_none(),
        "no status message for no-op replay"
    );
    assert!(
        !app.exit_requested,
        "exit_requested must stay false on no-op"
    );
}

#[test]
fn at_colon_within_macro_does_not_recurse() {
    // Verifies that `replay_last_ex` does NOT re-enter `route_chord_key` or
    // the macro recorder — `dispatch_ex` is a direct state mutation that
    // bypasses the input-dispatch layer entirely.
    //
    // The test works as follows:
    //   1. Establish last_ex_command = "1" via dispatch_ex.
    //   2. While recording a macro, call replay_last_ex() directly (simulating
    //      what the PlayMacro { reg: ':' } arm does). Verify it mutates cursor
    //      state without starting a second recording or causing recursion.
    //   3. Verify that last_ex_command is still "1" after the replay (no
    //      corruption from the inner dispatch_ex call).
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "line0\nline1\nline2\nline3\nline4");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // Establish last_ex_command as "1".
    app.dispatch_ex("1");
    assert_eq!(app.active_editor().cursor().0, 0, ":1 must go to row 0");
    assert_eq!(app.last_ex_command.as_deref(), Some("1"));

    // Move to row 2.
    app.active_editor_mut().jump_cursor(2, 0);
    app.sync_viewport_from_editor();

    // Start recording register 'a'.
    macro_key_seq(&mut app, &[ck('q'), ck('a')]);
    assert!(
        app.active_editor().is_recording_macro(),
        "must be recording"
    );

    // Directly invoke replay_last_ex (as if @: was processed by the PlayMacro
    // arm). This simulates the non-recursive path: dispatch_ex → ex::run, no
    // route_chord_key re-entry.
    app.replay_last_ex();

    // Cursor must be at row 0 — :1 was replayed.
    assert_eq!(
        app.active_editor().cursor().0,
        0,
        "replay_last_ex during recording must move cursor to row 0"
    );

    // Recording must still be active — replay_last_ex did NOT stop it.
    assert!(
        app.active_editor().is_recording_macro(),
        "replay_last_ex must not stop macro recording"
    );

    // last_ex_command must still be "1" — no corruption from inner dispatch.
    assert_eq!(
        app.last_ex_command.as_deref(),
        Some("1"),
        "last_ex_command must remain '1' after replay_last_ex"
    );

    // Stop recording.
    macro_key_seq(&mut app, &[ck('q')]);
    assert!(!app.active_editor().is_recording_macro());
}

// ── Phase 5e: count + register audit tests ───────────────────────────────────
//
// These tests verify the dispatch path for count-prefixed register-targeted
// ops and the single-use semantics of pending_register.

/// Seed a buffer with N numbered lines ("line1\nline2\n...").
#[test]
fn count_before_op_5dd_deletes_5_lines() {
    // `5dd` — count before doubled op deletes 5 lines.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 10);

    // Simulate what event_loop does: accumulate '5' in pending_count, then
    // route `d` through the keymap which reads pending_count.
    app.pending_count.try_accumulate('5');
    rck(&mut app, &['d', 'd']);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.first().map(String::as_str),
        Some("line6"),
        "5dd must delete lines 1-5; first line must now be 'line6', got {lines:?}"
    );
    assert_eq!(
        app.active_editor().vim_mode(),
        hjkl_engine::VimMode::Normal,
        "must be in Normal after 5dd"
    );
}

#[test]
fn register_then_count_a5dd_targets_register_a() {
    // `"a5dd` — register prefix, then count, then doubled op.
    // Sequence: `"` → SelectRegister, `a` → SetPendingRegister('a'),
    //           `5` → pending_count=5, `dd` → delete 5 lines into reg 'a'.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 10);

    // `"a` via route_chord_key (the canonical path for SelectRegister).
    rck(&mut app, &['"', 'a']);
    assert_eq!(
        app.active_editor().pending_register(),
        Some('a'),
        "pending_register must be 'a' after \"a"
    );

    // `5` — accumulate count.
    app.pending_count.try_accumulate('5');

    // `dd` — op.
    rck(&mut app, &['d', 'd']);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.first().map(String::as_str),
        Some("line6"),
        "\"a5dd must delete 5 lines; first line must now be 'line6', got {lines:?}"
    );

    // Register 'a' must hold deleted content.
    let reg_a = &app.active_editor().registers().named[0];
    assert!(
        reg_a.text.contains("line1"),
        "register 'a' must contain deleted text; got {:?}",
        reg_a.text
    );

    // pending_register must be cleared after one-shot use.
    assert_eq!(
        app.active_editor().pending_register(),
        None,
        "pending_register must be cleared after op"
    );
}

#[test]
fn count_then_register_5_quote_a_dd_targets_register_a() {
    // `5"add` — count typed BEFORE `"`, then register, then doubled op.
    // Bug target: `BeginPendingSelectRegister` previously reset pending_count,
    // causing the 5 to be silently discarded. With the fix, it must survive.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 10);

    // `5` — accumulate in pending_count (as event_loop does).
    app.pending_count.try_accumulate('5');

    // `"a` — register selection. pending_count must NOT be reset.
    rck(&mut app, &['"', 'a']);
    assert_eq!(
        app.active_editor().pending_register(),
        Some('a'),
        "pending_register must be 'a' after \"a"
    );
    assert_eq!(
        app.pending_count.peek(),
        5,
        "pending_count must survive through register selection (5\"add regression)"
    );

    // `dd` — op must consume count=5 and register='a'.
    rck(&mut app, &['d', 'd']);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.first().map(String::as_str),
        Some("line6"),
        "5\"add must delete 5 lines; first line must now be 'line6', got {lines:?}"
    );

    // Register 'a' must hold the deleted content.
    let reg_a = &app.active_editor().registers().named[0];
    assert!(
        reg_a.text.contains("line1"),
        "register 'a' must contain deleted text; got {:?}",
        reg_a.text
    );
}

#[test]
fn outer_count_inner_count_2_quote_a_5dd_total_10() {
    // `2"a5dd` — outer count 2, register 'a', inner count 5.
    // In vim these multiply: total = 2 * 5 = 10 lines deleted.
    // With our implementation: pending_count=2 survives `"`, then `5` is
    // accumulated into pending_count making it 25 (not 10). That's a known
    // quirk of the linear accumulation model; this test documents actual
    // behaviour so regressions are caught. The primary bug (5 discarded by
    // the reset) is fixed; the multiply semantic is aspirational.
    //
    // NOTE: This test deliberately documents current behaviour. If the
    // multiplication semantic is ever implemented, update the assertion.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 30);

    // Outer count 2.
    app.pending_count.try_accumulate('2');

    // `"a` — register. pending_count must remain 2.
    rck(&mut app, &['"', 'a']);
    assert_eq!(
        app.pending_count.peek(),
        2,
        "pending_count must be 2 after \"a"
    );

    // Inner count 5 — appends to pending_count (becomes 25 in current model).
    app.pending_count.try_accumulate('5');
    assert_eq!(
        app.pending_count.peek(),
        25,
        "pending_count digits accumulate to 25"
    );

    // `dd` — delete count1=25 lines into register 'a'.
    rck(&mut app, &['d', 'd']);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    // 25 lines deleted from a 30-line buffer → line26 is now first.
    assert_eq!(
        lines.first().map(String::as_str),
        Some("line26"),
        "2\"a5dd with digit-accumulation semantics must delete 25 lines; got {lines:?}"
    );
    let reg_a = &app.active_editor().registers().named[0];
    assert!(
        !reg_a.text.is_empty(),
        "register 'a' must be non-empty after op"
    );
}

#[test]
fn register_prefix_then_x_targets_register() {
    // `"ax` — delete current char into register 'a'.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // `"a` via route_chord_key.
    rck(&mut app, &['"', 'a']);
    assert_eq!(
        app.active_editor().pending_register(),
        Some('a'),
        "pending_register must be 'a' after \"a"
    );

    // `x` — engine-handled delete-char. Feed via engine (x is not in app keymap).
    hjkl_vim_tui::handle_key(app.active_editor_mut(), ck('x'));
    app.sync_viewport_from_editor();

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.first().map(String::as_str),
        Some("ello world"),
        "\"ax must delete 'h'; got {lines:?}"
    );

    // Register 'a' must hold 'h'.
    let reg_a = &app.active_editor().registers().named[0];
    assert_eq!(
        reg_a.text, "h",
        "register 'a' must contain 'h' after \"ax; got {:?}",
        reg_a.text
    );
}

#[test]
fn register_prefix_single_use_then_next_op_unnamed() {
    // `"add` then `dd` — the second dd must go to unnamed register `"`,
    // not reuse register 'a'. Verifies pending_register is one-shot.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 5);

    // `"add` — delete line1 into reg 'a'.
    rck(&mut app, &['"', 'a', 'd', 'd']);

    let reg_a_text = app.active_editor().registers().named[0].text.clone();
    assert!(
        reg_a_text.contains("line1"),
        "first dd must land in reg 'a'; got {:?}",
        reg_a_text
    );

    // pending_register must be None now.
    assert_eq!(
        app.active_editor().pending_register(),
        None,
        "pending_register must be cleared after first op"
    );

    // Snapshot unnamed register state before second dd.
    let unnamed_before = app.active_editor().registers().unnamed.text.clone();

    // `dd` — delete line2 (now line1) to unnamed register.
    rck(&mut app, &['d', 'd']);

    let unnamed_after = app.active_editor().registers().unnamed.text.clone();
    assert_ne!(
        unnamed_after, unnamed_before,
        "second dd must update unnamed register"
    );

    // Register 'a' must be unchanged — still has line1.
    let reg_a_text2 = app.active_editor().registers().named[0].text.clone();
    assert_eq!(
        reg_a_text, reg_a_text2,
        "register 'a' must not be overwritten by second dd; got {:?}",
        reg_a_text2
    );
}

#[test]
fn count_then_play_macro_3at_a_plays_three_times() {
    // `3@a` — play macro 'a' three times.
    // Record: `qa j q` (move down once). Then `3@a` moves cursor down 3 rows.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_numbered_lines(&mut app, 10);

    // Record macro 'a': move down one line.
    macro_key_seq(&mut app, &[ck('q'), ck('a')]);
    assert!(
        app.active_editor().is_recording_macro(),
        "must be recording"
    );
    macro_key_seq(&mut app, &[ck('j')]);
    macro_key_seq(&mut app, &[ck('q')]);
    assert!(
        !app.active_editor().is_recording_macro(),
        "recording stopped"
    );

    let row_after_record = app.active_editor().cursor().0;
    assert_eq!(row_after_record, 1, "recording 'j' moves cursor to row 1");

    // Accumulate count 3 in pending_count, then `@a`.
    app.pending_count.try_accumulate('3');
    // `@` → BeginPendingPlayMacro, takes pending_count.
    rck(&mut app, &['@', 'a']);

    let row_after_play = app.active_editor().cursor().0;
    assert_eq!(
        row_after_play, 4,
        "3@a must play macro 3 times → cursor moves from row 1 to row 4; got {row_after_play}"
    );
}

#[test]
fn count_then_dot_5_dot_repeats_five_times() {
    // `5.` — dot-repeat runs last change 5 times.
    // Setup: `x` deletes first char of "hello world", then `5.` deletes 5 more.
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "hello world");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // `x` — delete 'h', establishes last_change.
    hjkl_vim_tui::handle_key(app.active_editor_mut(), ck('x'));
    app.sync_viewport_from_editor();

    let lines_after_x = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines_after_x.first().map(String::as_str),
        Some("ello world"),
        "x must delete 'h'; got {lines_after_x:?}"
    );

    // Accumulate count 5 into pending_count, then `.`.
    app.pending_count.try_accumulate('5');
    // DotRepeat is bound in the app keymap; route through route_chord_key.
    let consumed = app.route_chord_key(ck('.'));
    assert!(consumed, ". must be consumed by keymap");
    app.sync_viewport_from_editor();

    let lines_after_dot = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    // Started with "ello world" (10 chars). Delete 5 chars one at a time:
    // 'e','l','l','o',' ' → "world". Each dot-repeat fires x (delete-one-char)
    // once (count folded into single repeat of the last-change op).
    assert_eq!(
        lines_after_dot.first().map(String::as_str),
        Some("world"),
        "5. must repeat x 5 more times; got {lines_after_dot:?}"
    );
}

/// Regression: `{count}p` (5p, 10p, 100p) must paste the register
/// `count` times. Drives through `macro_key_seq` so it exercises the
/// full event-loop digit-buffering path (handle_keypress →
/// pending_count.try_accumulate → keymap dispatch).
#[test]
fn count_p_pastes_register_count_times() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "x");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // yy5p — linewise yank, then 5p.
    macro_key_seq(&mut app, &[ck('y'), ck('y'), ck('5'), ck('p')]);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.len(),
        6,
        "5p on a 1-line linewise yank must produce 6 lines (1 + 5); got {lines:?}"
    );
    assert!(
        lines.iter().all(|l| l == "x"),
        "every line should be 'x'; got {lines:?}"
    );
}

/// Regression: counts with embedded zeros (10p, 100p) must accumulate
/// correctly through the event-loop digit-buffering path.
#[test]
fn count_with_zero_digits_pastes_correctly() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "x");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // yy10p — linewise yank, then 10p.
    macro_key_seq(&mut app, &[ck('y'), ck('y'), ck('1'), ck('0'), ck('p')]);

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.len(),
        11,
        "10p must produce 11 lines (1 + 10); got {lines:?}"
    );
}

/// Regression: charwise paste with count must also repeat. Charwise
/// pastes take a different branch inside `do_paste` than linewise.
#[test]
fn count_p_charwise_yank_pastes_count_times() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "abc");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    // yl5p — charwise yank one char, then 5p.
    macro_key_seq(&mut app, &[ck('y'), ck('l'), ck('5'), ck('p')]);

    let first_line = hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), 0);
    // Started with "abc", yanked 'a', `5p` pastes 'a' 5 times after cursor (col 0):
    // "a" + "aaaaa" + "bc" = "aaaaaabc".
    assert_eq!(
        first_line, "aaaaaabc",
        "5p of charwise 'a' must produce 'aaaaaabc'; got {first_line:?}"
    );
}

/// Regression: three-digit counts (100p) must accumulate correctly.
#[test]
fn count_100p_pastes_100_times() {
    let mut app = App::new(None, false, None, None).unwrap();
    seed_buffer(&mut app, "x");
    app.active_editor_mut().jump_cursor(0, 0);
    app.sync_viewport_from_editor();

    macro_key_seq(
        &mut app,
        &[ck('y'), ck('y'), ck('1'), ck('0'), ck('0'), ck('p')],
    );

    let lines = app
        .active_editor()
        .buffer()
        .rope()
        .lines()
        .map(|s| {
            let s = s.to_string();
            s.strip_suffix('\n').map(str::to_string).unwrap_or(s)
        })
        .collect::<Vec<_>>();
    assert_eq!(
        lines.len(),
        101,
        "100p must produce 101 lines (1 + 100); got {} lines",
        lines.len()
    );
}

/// Vim registers are global: `yy` in one buffer must paste with `p` after
/// switching to another buffer. Regression — registers used to live per-Editor.
#[test]
fn registers_are_global_across_buffers() {
    let path_a = std::env::temp_dir().join("hjkl_reg_global_a.txt");
    let path_b = std::env::temp_dir().join("hjkl_reg_global_b.txt");
    std::fs::write(&path_a, "alpha\n").unwrap();
    std::fs::write(&path_b, "beta\n").unwrap();

    let mut app = App::new(Some(path_a.clone()), false, None, None).unwrap();
    app.dispatch_ex(&format!("e {}", path_b.display()));
    // Re-open A (reuses its slot) so it's active, then yank its line.
    app.dispatch_ex(&format!("e {}", path_a.display()));
    macro_key_seq(&mut app, &[ck('y'), ck('y')]);

    // Switch to B and paste — should paste A's yanked "alpha".
    app.dispatch_ex(&format!("e {}", path_b.display()));
    macro_key_seq(&mut app, &[ck('p')]);

    let content = (*app.active_editor().buffer().content_joined()).clone();
    assert!(
        content.contains("alpha"),
        "yank in buffer A must paste in buffer B (global registers); got {content:?}"
    );

    let _ = std::fs::remove_file(&path_a);
    let _ = std::fs::remove_file(&path_b);
}