fresh-editor 0.2.11

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
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
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
use crate::common::harness::EditorTestHarness;

/// Test that Ctrl+D with backward selection (Shift+Left) creates properly synced cursors
/// Issue #210: When selecting with Shift+Left and then creating a multiple cursor with Ctrl+D,
/// the cursors use unsynced offsets - one cursor is at start of selection, one at end.
/// This causes typing to produce incorrect results.
#[test]
fn test_add_cursor_next_match_with_backward_selection() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type some text with repeated words
    harness.type_text("foo bar foo").unwrap();
    harness.assert_buffer_content("foo bar foo");

    // Position cursor after first "foo" (at position 3)
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();

    // Verify cursor position
    let primary = harness.editor().active_cursors().primary();
    assert_eq!(
        primary.position, 3,
        "Cursor should be at position 3 after first 'foo'"
    );

    // Select backward with Shift+Left 3 times to select "foo"
    // This creates a backward selection: cursor at 0, anchor at 3
    harness
        .send_key(KeyCode::Left, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::SHIFT)
        .unwrap();

    // Verify backward selection: position=0 (cursor at start), anchor=3 (selection end)
    let primary = harness.editor().active_cursors().primary();
    assert_eq!(
        primary.position, 0,
        "After Shift+Left, cursor should be at start of selection"
    );
    assert_eq!(
        primary.anchor,
        Some(3),
        "After Shift+Left, anchor should be at end of selection"
    );

    // Add cursor at next "foo" match
    harness.editor_mut().add_cursor_at_next_match();
    harness.render().unwrap();

    // Should now have 2 cursors
    assert_eq!(harness.editor().active_cursors().iter().count(), 2);

    // CRITICAL: Both cursors should have the same relative position within their selections
    // The original cursor is at position 0 (start of selection 0..3)
    // The new cursor should also be at the start of its selection (8..11)
    // i.e., new cursor position should be 8, not 11
    for (id, cursor) in harness.editor().active_cursors().iter() {
        let selection = cursor
            .selection_range()
            .expect("Cursor should have selection");
        let is_at_start = cursor.position == selection.start;
        let is_at_end = cursor.position == selection.end;

        // Since original selection was backward (cursor at start), new cursor should also be at start
        assert!(
            is_at_start,
            "Cursor {:?} should be at start of selection. Position: {}, Selection: {:?}",
            id, cursor.position, selection
        );
        assert!(
            !is_at_end || selection.start == selection.end,
            "Cursor {:?} should NOT be at end of selection (unless collapsed). Position: {}, Selection: {:?}",
            id, cursor.position, selection
        );
    }

    // Type "X" to replace both selections - this should result in "X bar X"
    harness.type_text("X").unwrap();
    harness.render().unwrap();

    // Both "foo"s should be replaced with "X"
    harness.assert_buffer_content("X bar X");
}

/// Test that Ctrl+D with forward selection (Shift+Right) creates properly synced cursors
/// and typing replaces both selections correctly
#[test]
fn test_add_cursor_next_match_with_forward_selection() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type some text with repeated words
    harness.type_text("foo bar foo").unwrap();
    harness.assert_buffer_content("foo bar foo");

    // Select the first "foo" with forward selection (Shift+Right from position 0)
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();

    // Verify forward selection: position=3 (cursor at end), anchor=0 (selection start)
    let primary = harness.editor().active_cursors().primary();
    assert_eq!(
        primary.position, 3,
        "After Shift+Right, cursor should be at end of selection"
    );
    assert_eq!(
        primary.anchor,
        Some(0),
        "After Shift+Right, anchor should be at start of selection"
    );

    // Add cursor at next "foo" match
    harness.editor_mut().add_cursor_at_next_match();
    harness.render().unwrap();

    // Should now have 2 cursors
    assert_eq!(harness.editor().active_cursors().iter().count(), 2);

    // Type "X" to replace both selections - this should result in "X bar X"
    harness.type_text("X").unwrap();
    harness.render().unwrap();

    // Both "foo"s should be replaced with "X"
    harness.assert_buffer_content("X bar X");
}

/// Test adding cursor at next match with Ctrl+D (no typing, just cursor creation)
#[test]
fn test_add_cursor_next_match() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type some text with repeated words
    harness.type_text("foo bar foo baz foo").unwrap();
    harness.assert_buffer_content("foo bar foo baz foo");

    // Select the first "foo" (positions 0-3)
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();

    // Verify selection
    let primary = harness.editor().active_cursors().primary();
    assert_eq!(primary.position, 3);
    assert_eq!(primary.anchor, Some(0));

    // Press Ctrl+D to add cursor at next "foo"
    harness.editor_mut().add_cursor_at_next_match();
    harness.render().unwrap();

    // Should now have 2 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 2);

    // Press Ctrl+D again to add cursor at third "foo"
    harness.editor_mut().add_cursor_at_next_match();
    harness.render().unwrap();

    // Should now have 3 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 3);
}

/// Test adding cursor above with Ctrl+Alt+Up
#[test]
fn test_add_cursor_above() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Position cursor on Line 3
    harness.assert_buffer_content("Line 1\nLine 2\nLine 3");

    // Add cursor above (to Line 2)
    harness.editor_mut().add_cursor_above();
    harness.render().unwrap();

    // Should now have 2 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 2);

    // Add cursor above again (to Line 1)
    harness.editor_mut().add_cursor_above();
    harness.render().unwrap();

    // Should now have 3 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 3);
}

/// Test adding cursor below with Ctrl+Alt+Down
#[test]
fn test_add_cursor_below() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Position cursor on Line 1
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add cursor below (to Line 2)
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should now have 2 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 2);

    // Add cursor below again (to Line 3)
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should now have 3 cursors
    let cursors = &harness.editor().active_cursors();
    assert_eq!(cursors.iter().count(), 3);
}

/// Test multi-cursor typing
#[test]
fn test_multi_cursor_typing() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines with more content
    harness.type_text("aaa\nbbb\nccc\nddd").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add cursors - each time we add a cursor below, the new cursor becomes primary
    // So we can continue adding cursors below
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1 and 2
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1, 2, and 3

    // Should have 3 cursors
    let cursor_count = harness.editor().active_cursors().iter().count();
    assert_eq!(cursor_count, 3, "Should have 3 cursors");

    // Type "xyz" with all three cursors
    harness.type_text("xyz").unwrap();

    // Verify the complete buffer content
    harness.assert_buffer_content("xyzaaa\nxyzbbb\nxyzccc\nddd");
}

/// Test removing secondary cursors with Esc
#[test]
fn test_remove_secondary_cursors() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Add cursors above
    harness.editor_mut().add_cursor_above();
    harness.editor_mut().add_cursor_above();

    // Should have 3 cursors
    assert_eq!(harness.editor().active_cursors().iter().count(), 3);

    // Remove secondary cursors
    harness.editor_mut().active_cursors_mut().remove_secondary();
    harness.render().unwrap();

    // Should have only 1 cursor now
    assert_eq!(harness.editor().active_cursors().iter().count(), 1);
}

/// Test multi-cursor undo atomicity
/// When using multiple cursors, undo should undo all cursor actions in one step
#[test]
fn test_multi_cursor_undo_atomic() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines with more content (matching the working test)
    harness.type_text("aaa\nbbb\nccc\nddd").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add cursors - each time we add a cursor below, the new cursor becomes primary
    // So we can continue adding cursors below
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1 and 2
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1, 2, and 3

    // Should have 3 cursors
    let cursor_count = harness.editor().active_cursors().iter().count();
    assert_eq!(cursor_count, 3, "Should have 3 cursors");

    // Type "xyz" with all three cursors - this should create a batch event
    harness.type_text("xyz").unwrap();

    // Verify the complete buffer content after typing
    harness.assert_buffer_content("xyzaaa\nxyzbbb\nxyzccc\nddd");

    // Undo 3 times (one for each character typed) - each undo removes one char from all cursors
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
    }

    // All "xyz" should be gone after undoing all 3 character insertions
    harness.assert_buffer_content("aaa\nbbb\nccc\nddd");

    // Redo 3 times - this should restore all characters
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Char('y'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
    }

    // All "xyz" should be back after redoing all 3
    harness.assert_buffer_content("xyzaaa\nxyzbbb\nxyzccc\nddd");
}

/// Test multi-cursor delete undo atomicity
#[test]
fn test_multi_cursor_delete_undo_atomic() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines
    harness.type_text("aaa\nbbb\nccc").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add two more cursors
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();

    // Should have 3 cursors
    assert_eq!(harness.editor().active_cursors().iter().count(), 3);

    // Delete forward at all three cursors - should delete 'a', 'b', 'c'
    harness
        .send_key(KeyCode::Delete, KeyModifiers::NONE)
        .unwrap();

    // Verify first character deleted from each line
    harness.assert_buffer_content("aa\nbb\ncc");

    // Undo once - should restore all three characters
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // All characters should be restored
    harness.assert_buffer_content("aaa\nbbb\nccc");
}

/// Test that adding cursors can be undone
#[test]
fn test_add_cursor_undo() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Should start with 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);

    // Add a cursor below
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should now have 2 cursors
    assert_eq!(harness.editor().active_cursors().count(), 2);

    // Add another cursor below
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should now have 3 cursors
    assert_eq!(harness.editor().active_cursors().count(), 3);

    // Undo - should remove the last cursor added
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 2 cursors
    assert_eq!(harness.editor().active_cursors().count(), 2);

    // Undo again - should remove the second cursor
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);

    // Redo - should add cursor back
    harness
        .send_key(KeyCode::Char('y'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 2 cursors
    assert_eq!(harness.editor().active_cursors().count(), 2);
}

/// Test that removing cursors can be undone
/// Note: Ignored - cursor removal undo behavior may not restore cursors
/// depending on how undo history handles cursor state
#[test]
#[ignore]
fn test_remove_cursor_undo() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add two cursors
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();

    // Should have 3 cursors
    assert_eq!(harness.editor().active_cursors().count(), 3);

    // Remove secondary cursors (using Escape)
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should be back to 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);

    // Undo - should restore the secondary cursors
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 3 cursors
    assert_eq!(harness.editor().active_cursors().count(), 3);

    // Redo - should remove them again
    harness
        .send_key(KeyCode::Char('y'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);
}

/// Test undo beyond cursor add removes the cursor and undoes the edit
#[test]
fn test_undo_beyond_cursor_add() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines
    harness.type_text("aaa\nbbb\nccc").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Should start with 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);

    // Add a cursor below
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should now have 2 cursors
    assert_eq!(harness.editor().active_cursors().count(), 2);

    // Type "xyz" with both cursors
    harness.type_text("xyz").unwrap();

    // Verify the complete buffer content after typing
    harness.assert_buffer_content("xyzaaa\nxyzbbb\nccc");

    // Undo 3 times (one for each character typed) - each undo removes one char from all cursors
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
    }

    // "xyz" should be gone, but we should still have 2 cursors
    harness.assert_buffer_content("aaa\nbbb\nccc");
    assert_eq!(harness.editor().active_cursors().count(), 2);

    // Undo again - should remove the second cursor
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should be back to 1 cursor
    assert_eq!(harness.editor().active_cursors().count(), 1);

    // Redo - should add the cursor back
    harness
        .send_key(KeyCode::Char('y'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should have 2 cursors again
    assert_eq!(harness.editor().active_cursors().count(), 2);

    // Redo 3 times - should redo all 3 character insertions
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Char('y'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
    }

    // "xyz" should be back
    harness.assert_buffer_content("xyzaaa\nxyzbbb\nccc");
}

/// Test that status bar shows cursor count when multiple cursors exist
#[test]
fn test_multi_cursor_status_bar_indicator() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create three lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Render to capture initial state
    harness.render().unwrap();

    // Status bar should NOT show cursor count when single cursor
    let screen = harness.screen_to_string();
    assert!(
        !screen.contains(" cursors"),
        "Should not show cursor count with single cursor"
    );

    // Add a cursor below
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Status bar should show "2 cursors"
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("2 cursors"),
        "Status bar should show '2 cursors'. Screen:\n{screen}"
    );

    // Add another cursor
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Status bar should show "3 cursors"
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("3 cursors"),
        "Status bar should show '3 cursors'. Screen:\n{screen}"
    );

    // Remove secondary cursors
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Status bar should NOT show cursor count again
    let screen = harness.screen_to_string();
    assert!(
        !screen.contains(" cursors"),
        "Should not show cursor count after removing cursors"
    );
}

/// Test that all cursors are visible in the viewport
#[test]
fn test_all_cursors_visible_in_viewport() {
    use crossterm::event::{KeyCode, KeyModifiers};
    use ratatui::style::Modifier;
    let mut harness = EditorTestHarness::new_no_wrap(80, 24).unwrap();

    // Create three lines
    harness.type_text("Line 1\nLine 2\nLine 3").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add two more cursors
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should have 3 cursors
    assert_eq!(harness.cursor_count(), 3);

    // Now verify that all 3 cursors are visible with some kind of styling
    // (In the viewport, we should see styled characters at cursor positions)
    // Line 1, Line 2, Line 3 all start at column 0, so we should check
    // that there's cursor styling at the 'L' of each line

    // Get the y-coordinates of the three lines (after tab bar)
    // Tab bar is 1 line, content starts at y=1
    // But we also need to account for line numbers (gutter)
    // Line numbers take up some space (e.g., "1 ", "2 ", "3 ")
    // Let's check multiple x positions to find the cursor

    let line_y_positions = vec![1, 2, 3]; // y positions of the three lines

    let mut cursor_indicators_found = 0;

    for y in line_y_positions {
        // Check multiple x positions (accounting for line numbers/gutter)
        // Try x=0 through x=10 to find reversed characters
        for x in 0..10 {
            if let Some(style) = harness.get_cell_style(x, y) {
                // Cursor should have REVERSED modifier
                if style.add_modifier.contains(Modifier::REVERSED) {
                    cursor_indicators_found += 1;
                    break; // Found cursor on this line, move to next line
                }
            }
        }
    }

    assert!(
        cursor_indicators_found >= 2,
        "Expected at least 2 visible cursors (secondary cursors), found {cursor_indicators_found}"
    );
}

/// Test comprehensive multi-cursor editing with multiple 'abc' lines
/// This test uses the exact same pattern as test_multi_cursor_typing but with 'abc' content
#[test]
fn test_multi_cursor_comprehensive_abc_editing() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines with 'abc' - matching test_multi_cursor_typing pattern
    // Note: Using varied content to avoid any potential cursor normalization issues
    harness.type_text("abc1\nabc2\nabc3\nabc4").unwrap();

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add cursors - each time we add a cursor below, the new cursor becomes primary
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1 and 2
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1, 2, and 3
    harness.editor_mut().add_cursor_below(); // Now we have cursors on line 1, 2, 3, and 4

    // Should have 4 cursors
    let cursor_count = harness.editor().active_cursors().iter().count();
    assert_eq!(cursor_count, 4, "Should have 4 cursors");

    // Test 1: Type "xyz" with all four cursors
    harness.type_text("xyz").unwrap();

    // Verify the complete buffer content after typing
    harness.assert_buffer_content("xyzabc1\nxyzabc2\nxyzabc3\nxyzabc4");

    // Test 2: Undo 3 times (one per character) should remove all "xyz"
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
    }

    // Verify content is restored after undo
    harness.assert_buffer_content("abc1\nabc2\nabc3\nabc4");

    // Verify we still have 4 cursors after undo
    assert_eq!(harness.editor().active_cursors().iter().count(), 4);
}

/// Test single cursor visibility - comprehensive test moving through every position
#[test]
fn test_single_cursor_visible() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new_no_wrap(80, 24).unwrap();

    // Create multiple lines with various content
    harness
        .type_text("Hello World\nSecond Line Here\nThird Line\nFourth")
        .unwrap();

    let expected_content = "Hello World\nSecond Line Here\nThird Line\nFourth";
    harness.assert_buffer_content(expected_content);

    // Move to start of document
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Expected positions for "Hello World\nSecond Line Here\nThird Line\nFourth"
    let expected_chars = vec![
        'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd',  // end of line 1
        '\n', // newline is at position 11
    ];

    println!("\nStarting comprehensive cursor visibility test...");
    println!("Testing first line: 'Hello World'");

    // Move through first line character by character
    for (step, expected_char) in expected_chars.iter().enumerate() {
        harness.render().unwrap();

        let cursor_pos = harness.cursor_position();
        println!("\nStep {step}: cursor at buffer position {cursor_pos}");

        // Find cursor on screen using the harness's cursor detection
        let cursors = harness.find_all_cursors();
        assert!(
            !cursors.is_empty(),
            "Step {step}: Cursor not visible at buffer position {cursor_pos}! Expected char: '{expected_char}'"
        );

        let (x, y, char_at_cursor, _is_primary) = &cursors[0];
        println!("  Screen position: ({x}, {y}), char: '{char_at_cursor}'");

        // For newline, we expect to see a space since we add it for visibility
        if *expected_char == '\n' {
            println!("  At newline - expecting space or newline indicator");
        } else {
            // Verify the character matches (accounting for rendered character)
            let expected_str = expected_char.to_string();
            assert_eq!(
                *char_at_cursor, expected_str,
                "Step {step}: Cursor at wrong character. Expected '{expected_str}', got '{char_at_cursor}'"
            );
        }

        // Move right for next iteration
        if step < expected_chars.len() - 1 {
            harness
                .send_key(KeyCode::Right, KeyModifiers::NONE)
                .unwrap();
        }
    }

    println!("\nTesting navigation to second line...");

    // Move to start of second line
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    let after_down = harness.cursor_position();
    println!("After Down: cursor at buffer position {after_down}");

    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    let after_home = harness.cursor_position();
    println!("After Home: cursor at buffer position {after_home}");

    harness.render().unwrap();

    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor should be visible at start of second line"
    );
    let (x, y, char_at_cursor, _is_primary) = &cursors[0];
    println!(
        "At start of line 2: screen ({x}, {y}), char: '{char_at_cursor}', buffer pos: {after_home}"
    );

    // Position 12 should be 'S' (first char of "Second")
    // But we need to be flexible in case the cursor is shown differently
    if after_home == 12 {
        // If we're at the 'S', it should show 'S' with REVERSED
        assert_eq!(*char_at_cursor, "S", "Should be at 'S' of 'Second'");
    } else {
        println!("WARNING: Cursor not at expected position 12, it's at {after_home}");
    }

    // Move through "Second" character by character
    let second_chars = ['S', 'e', 'c', 'o', 'n', 'd'];
    for (i, expected_char) in second_chars.iter().enumerate() {
        harness.render().unwrap();

        let cursors = harness.find_all_cursors();
        assert!(
            !cursors.is_empty(),
            "Cursor not visible at char {i} of 'Second'"
        );

        let (_, _, char_at_cursor, _is_primary) = &cursors[0];
        let expected_str = expected_char.to_string();
        assert_eq!(
            *char_at_cursor, expected_str,
            "At position {i} of 'Second': expected '{expected_str}', got '{char_at_cursor}'"
        );

        if i < second_chars.len() - 1 {
            harness
                .send_key(KeyCode::Right, KeyModifiers::NONE)
                .unwrap();
        }
    }

    println!("\nTesting vertical navigation...");

    // Test moving up and down
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor should be visible after moving down"
    );
    println!("After Down: cursor at {:?}", cursors[0]);

    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor should be visible after moving up"
    );
    println!("After Up: cursor at {:?}", cursors[0]);

    // Move to end of document
    harness
        .send_key(KeyCode::End, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor should be visible at end of document"
    );
    println!("At end of document: cursor at {:?}", cursors[0]);

    println!("\nCursor visibility test completed successfully!");
}

/// Test cursor visibility on empty lines
#[test]
fn test_cursor_visible_on_empty_line() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Start with empty buffer (empty line)
    harness.render().unwrap();

    // Should have exactly 1 cursor
    assert_eq!(harness.cursor_count(), 1);

    // Cursor should be visible on the empty line
    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor should be visible on empty line"
    );
    assert_eq!(cursors.len(), 1, "Should have exactly 1 visible cursor");

    // Type some text, then delete it to create an empty line again
    harness.type_text("Test").unwrap();
    for _ in 0..4 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Cursor should still be visible on empty line
    let cursors_after_delete = harness.find_all_cursors();
    assert!(
        !cursors_after_delete.is_empty(),
        "Cursor should be visible on empty line after deleting text"
    );

    // Add multiple empty lines and test cursor on different empty lines
    harness.type_text("\n\n\n").unwrap();
    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Cursor should be visible on the empty line we moved to
    let cursors_on_middle_empty = harness.find_all_cursors();
    assert!(
        !cursors_on_middle_empty.is_empty(),
        "Cursor should be visible on middle empty line"
    );
}

/// Test cursor visibility when editor first opens with empty buffer
#[test]
fn test_cursor_visible_on_initial_empty_buffer() {
    // Create harness with empty buffer (simulates opening editor)
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.render().unwrap();

    println!("Testing initial empty buffer cursor visibility...");
    println!(
        "Buffer length: {}",
        harness.editor().active_state().buffer.len()
    );
    println!(
        "Cursor position: {}",
        harness.editor().active_cursors().primary().position
    );

    // Use the harness's cursor detection which handles both hardware cursor and REVERSED cells
    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor must be visible when editor opens with empty buffer"
    );

    let (x, y, char_at_cursor, is_primary) = &cursors[0];
    println!(
        "Found cursor at screen position ({x}, {y}): '{char_at_cursor}' (primary: {is_primary})"
    );
    assert!(*is_primary, "The only cursor should be the primary cursor");

    // CRITICAL: The cursor must NOT be in the gutter area (column 0-7 typically)
    // It should be at the content area, which starts after the gutter
    let gutter_width = harness.editor().active_state().margins.left_total_width();
    println!("Gutter width: {}", gutter_width);
    println!("Cursor screen position: ({}, {})", x, y);
    println!(
        "Margins enabled: {}",
        harness.editor().active_state().margins.left_config.enabled
    );
    assert!(
        *x >= gutter_width as u16,
        "Cursor x position ({}) must be >= gutter width ({}) - cursor should not be in gutter area",
        x,
        gutter_width
    );
}

/// Test cursor position after Ctrl+End in various buffer states
/// This verifies the cursor renders at the correct screen position, not in the gutter
#[test]
fn test_ctrl_end_cursor_position() {
    use crossterm::event::{KeyCode, KeyModifiers};

    // Test 1: Empty buffer - Ctrl+End should keep cursor at (gutter_width, content_start_y)
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.render().unwrap();

        let gutter_width = harness.editor().active_state().margins.left_total_width();
        println!("Test 1: Empty buffer");
        println!("  Gutter width: {}", gutter_width);

        // Press Ctrl+End to jump to end of buffer
        harness
            .send_key(KeyCode::End, KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();

        let (cursor_x, _cursor_y) = harness.screen_cursor_position();
        println!("  Cursor x after Ctrl+End: {}", cursor_x);
        assert!(
            cursor_x >= gutter_width as u16,
            "Empty buffer: Cursor x ({}) should be >= gutter width ({})",
            cursor_x,
            gutter_width
        );
    }

    // Test 2: Buffer with trailing newline - Ctrl+End should put cursor on empty line after newline
    // The implicit line after the newline should have a line number in the gutter
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("hello\n").unwrap();
        harness.render().unwrap();

        let gutter_width = harness.editor().active_state().margins.left_total_width();
        println!("Test 2: Buffer with trailing newline 'hello\\n'");
        println!("  Gutter width: {}", gutter_width);

        // Press Ctrl+End to jump to end of buffer
        harness
            .send_key(KeyCode::End, KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();

        let (cursor_x, cursor_y) = harness.screen_cursor_position();
        println!(
            "  Cursor position after Ctrl+End: ({}, {})",
            cursor_x, cursor_y
        );
        assert!(
            cursor_x >= gutter_width as u16,
            "Trailing newline: Cursor x ({}) should be >= gutter width ({})",
            cursor_x,
            gutter_width
        );

        // Check that the gutter shows a line number for the implicit line after the newline
        // The cursor should be on line 2 (0-indexed y position relative to content area)
        // Get the row text where cursor is positioned and check the gutter
        let row_text = harness.get_row_text(cursor_y);
        println!("  Row text at cursor y={}: '{}'", cursor_y, row_text);

        // The gutter should contain "2" for line 2 (the implicit line after "hello\n")
        // Gutter format is typically: " N │" where N is right-aligned line number
        let gutter_text: String = row_text.chars().take(gutter_width).collect();
        println!("  Gutter text: '{}'", gutter_text);
        assert!(
            gutter_text.contains("2"),
            "Trailing newline: Gutter should show line number 2 for the implicit line, got: '{}'",
            gutter_text
        );
    }

    // Test 3: Buffer ending with empty line (two newlines) - Ctrl+End on last empty line
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("hello\n\n").unwrap();
        harness.render().unwrap();

        let gutter_width = harness.editor().active_state().margins.left_total_width();
        println!("Test 3: Buffer with empty line 'hello\\n\\n'");
        println!("  Gutter width: {}", gutter_width);

        // Press Ctrl+End to jump to end of buffer
        harness
            .send_key(KeyCode::End, KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();

        let (cursor_x, _cursor_y) = harness.screen_cursor_position();
        println!("  Cursor x after Ctrl+End: {}", cursor_x);
        assert!(
            cursor_x >= gutter_width as u16,
            "Empty line: Cursor x ({}) should be >= gutter width ({})",
            cursor_x,
            gutter_width
        );
    }

    // Test 4: Buffer without trailing newline - Ctrl+End should put cursor after last char
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("hello").unwrap();
        harness.render().unwrap();

        let gutter_width = harness.editor().active_state().margins.left_total_width();
        println!("Test 4: Buffer without trailing newline 'hello'");
        println!("  Gutter width: {}", gutter_width);

        // Press Ctrl+End to jump to end of buffer
        harness
            .send_key(KeyCode::End, KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();

        let (cursor_x, _cursor_y) = harness.screen_cursor_position();
        println!("  Cursor x after Ctrl+End: {}", cursor_x);
        // Cursor should be at gutter_width + 5 (after "hello")
        let expected_x = gutter_width as u16 + 5;
        assert!(
            cursor_x >= gutter_width as u16,
            "No trailing newline: Cursor x ({}) should be >= gutter width ({})",
            cursor_x,
            gutter_width
        );
        assert_eq!(
            cursor_x, expected_x,
            "No trailing newline: Cursor x ({}) should be at end of 'hello' ({})",
            cursor_x, expected_x
        );
    }
}

/// Test cursor visibility when opening a file
#[test]
fn test_cursor_visible_when_opening_file() {
    use std::fs;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");
    fs::write(&file_path, "Hello World\nSecond Line").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    println!("Testing cursor visibility when opening file...");
    println!(
        "Buffer content: {}",
        harness.editor().active_state().buffer.to_string().unwrap()
    );
    println!(
        "Buffer length: {}",
        harness.editor().active_state().buffer.len()
    );
    println!(
        "Cursor position: {}",
        harness.editor().active_cursors().primary().position
    );

    // Use the harness's cursor detection which handles both hardware cursor and REVERSED cells
    let cursors = harness.find_all_cursors();
    assert!(
        !cursors.is_empty(),
        "Cursor must be visible when opening a file"
    );

    let (x, y, char_at_cursor, is_primary) = &cursors[0];
    println!(
        "Found cursor at screen position ({x}, {y}): '{char_at_cursor}' (primary: {is_primary})"
    );
    assert!(*is_primary, "The only cursor should be the primary cursor");
}

/// Test to investigate cursor behavior with identical line content
#[test]
fn test_identical_lines_cursor_positions() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines with IDENTICAL content
    harness.type_text("abc\nabc\nabc\nabc").unwrap();
    harness.assert_buffer_content("abc\nabc\nabc\nabc");

    // Go to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Get initial cursor position
    let initial_pos = harness.cursor_position();
    println!("Initial cursor position: {initial_pos}");

    // Add first cursor below
    harness.editor_mut().add_cursor_below();
    println!("After adding 1st cursor below:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!(
            "  Cursor {:?}: position={}, anchor={:?}",
            id, cursor.position, cursor.anchor
        );
    }

    // Add second cursor below
    harness.editor_mut().add_cursor_below();
    println!("After adding 2nd cursor below:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!(
            "  Cursor {:?}: position={}, anchor={:?}",
            id, cursor.position, cursor.anchor
        );
    }

    // Add third cursor below
    harness.editor_mut().add_cursor_below();
    println!("After adding 3rd cursor below:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!(
            "  Cursor {:?}: position={}, anchor={:?}",
            id, cursor.position, cursor.anchor
        );
    }

    let cursor_count = harness.editor().active_cursors().iter().count();
    println!("Total cursors: {cursor_count}");
    assert_eq!(cursor_count, 4, "Should have 4 cursors");

    // Type "xyz"
    harness.type_text("xyz").unwrap();

    // Verify the complete buffer content
    harness.assert_buffer_content("xyzabc\nxyzabc\nxyzabc\nxyzabc");
}

/// Test multi-cursor End key movement - all cursors should move to end of their respective lines
/// Issue #632: When multiple cursors press End, they should all be at end of their lines
/// and visible at the correct positions (not at start of line)
#[test]
fn test_multi_cursor_end_key_positioning() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new_no_wrap(80, 24).unwrap();

    // Create multiple lines with different content
    harness.type_text("Hello\nWorld\nTest").unwrap();
    harness.assert_buffer_content("Hello\nWorld\nTest");

    // Go to start of document
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Add cursors on all three lines
    harness.editor_mut().add_cursor_below(); // Cursor on line 2
    harness.editor_mut().add_cursor_below(); // Cursor on line 3
    harness.render().unwrap();

    // Should have 3 cursors
    assert_eq!(harness.cursor_count(), 3);

    // Print initial cursor positions
    println!("Before End key:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!("  Cursor {:?}: position={}", id, cursor.position);
    }

    // Press End key to move all cursors to end of their lines
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Print cursor positions after End key
    println!("\nAfter End key:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!("  Cursor {:?}: position={}", id, cursor.position);
    }

    // Verify cursor positions:
    // Line 1: "Hello\n" (0-5), cursor should be at 5 (on \n)
    // Line 2: "World\n" (6-11), cursor should be at 11 (on \n)
    // Line 3: "Test" (12-15), cursor should be at 16 (after last char, no newline)
    let positions: Vec<usize> = harness
        .editor()
        .active_cursors()
        .iter()
        .map(|(_, c)| c.position)
        .collect();

    // Each cursor should be at the end of its respective line
    assert!(
        positions.contains(&5),
        "Should have cursor at position 5 (end of 'Hello')"
    );
    assert!(
        positions.contains(&11),
        "Should have cursor at position 11 (end of 'World')"
    );
    assert!(
        positions.contains(&16),
        "Should have cursor at position 16 (end of 'Test')"
    );

    // Find all visible cursors
    let visible_cursors = harness.find_all_cursors();
    println!("\nVisible cursors on screen:");
    for (x, y, char_at, is_primary) in &visible_cursors {
        println!(
            "  Screen ({}, {}): char='{}', primary={}",
            x, y, char_at, is_primary
        );
    }

    // Should have 3 visible cursors (1 primary + 2 secondary)
    assert!(
        visible_cursors.len() >= 3,
        "Should have 3 visible cursors, found {}. Screen:\n{}",
        visible_cursors.len(),
        harness.screen_to_string()
    );

    // Verify cursors are at different y positions (different lines)
    let y_positions: Vec<u16> = visible_cursors.iter().map(|(_, y, _, _)| *y).collect();
    let unique_y_positions: std::collections::HashSet<_> = y_positions.iter().collect();
    assert_eq!(
        unique_y_positions.len(),
        3,
        "Cursors should be on 3 different lines. Y positions: {:?}",
        y_positions
    );

    // Verify cursors are NOT at the start of lines (x should be > gutter width)
    let gutter_width = harness.editor().active_state().margins.left_total_width() as u16;
    for (x, y, char_at, _) in &visible_cursors {
        // Cursor at end of line should have x > gutter_width + 0 (i.e., not at column 0 of content)
        // "Hello" is 5 chars, "World" is 5 chars, "Test" is 4 chars
        // So cursors should be at x = gutter_width + 5, gutter_width + 5, gutter_width + 4
        println!(
            "Cursor at ({}, {}): char='{}', gutter_width={}",
            x, y, char_at, gutter_width
        );
        assert!(
            *x > gutter_width,
            "Cursor at y={} should be past column 0 (x={} should be > gutter_width={}). This cursor is at the START of line instead of END!",
            y, x, gutter_width
        );
    }
}

/// Test that pressing Esc returns to original cursor position, not last added cursor
#[test]
fn test_esc_returns_to_original_cursor_position() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multiple lines
    harness
        .type_text("Line 1\nLine 2\nLine 3\nLine 4\nLine 5")
        .unwrap();
    harness.assert_buffer_content("Line 1\nLine 2\nLine 3\nLine 4\nLine 5");

    // Go to start of Line 1
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();

    // Get the original cursor position (should be at start of Line 1, position 0)
    let original_position = harness.cursor_position();
    println!("Original cursor position: {original_position} (should be at start of Line 1)");
    assert_eq!(original_position, 0, "Should start at position 0");

    // Add cursors to lines below (Line 2, 3, 4)
    harness.editor_mut().add_cursor_below(); // Add to Line 2
    harness.editor_mut().add_cursor_below(); // Add to Line 3
    harness.editor_mut().add_cursor_below(); // Add to Line 4

    // Should have 4 cursors now
    assert_eq!(harness.editor().active_cursors().iter().count(), 4);

    // Print cursor positions for debugging
    println!("After adding cursors:");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!("  Cursor {:?}: position={}", id, cursor.position);
    }

    // The "primary" cursor is now at Line 4 (the last one we added)
    // But when we press Esc, we expect to return to Line 1 (original position)

    // Press Esc to remove secondary cursors
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should have only 1 cursor now
    assert_eq!(harness.editor().active_cursors().iter().count(), 1);

    // The cursor should be at the ORIGINAL position (Line 1, position 0)
    // NOT at the last added cursor position (Line 4)
    let final_position = harness.cursor_position();
    println!("Final cursor position: {final_position} (should be back at original position 0)");

    assert_eq!(
        final_position, original_position,
        "After pressing Esc, cursor should return to original position {original_position} but is at {final_position}"
    );
}

/// Test auto-close parentheses with multiple cursors on separate lines
/// Repro: Create file, add 3 empty lines, go to first line, add 2 cursors below, type "foo()"
/// Issue: Auto-close parentheses may interfere with multiple cursor editing
#[test]
fn test_auto_close_parens_multiple_cursors() {
    use crate::common::harness::HarnessOptions;
    use crossterm::event::{KeyCode, KeyModifiers};
    use fresh::config::Config;
    use std::fs;
    use tempfile::TempDir;

    // Create harness with auto_indent enabled (required for auto-close)
    let mut config = Config::default();
    config.editor.auto_indent = true;
    let mut harness = EditorTestHarness::create(
        80,
        24,
        HarnessOptions::new()
            .with_config(config)
            .without_empty_plugins_dir(),
    )
    .unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.py");
    // Create file with .py extension so it's recognized as Python
    fs::write(&file_path, "").unwrap();

    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Verify language is detected as Python (for auto-close to work)
    let language = harness.editor().active_state().language.clone();
    println!("Detected language: {}", language);
    assert_eq!(language, "python", "File should be detected as Python");

    // =========================================================================
    // STEP 1: First verify auto-close works with SINGLE cursor
    // =========================================================================
    harness.type_text("test(").unwrap();
    harness.render().unwrap();

    let single_cursor_content = harness.get_buffer_content().unwrap();
    assert_eq!(
        single_cursor_content, "test()",
        "BASELINE: Auto-close should work with single cursor. Got: {:?}",
        single_cursor_content
    );
    println!(
        "✓ Single cursor auto-close works: {:?}",
        single_cursor_content
    );

    // Clear and start fresh for multi-cursor test
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap(); // Select all
    harness
        .send_key(KeyCode::Backspace, KeyModifiers::NONE)
        .unwrap(); // Delete
    harness.render().unwrap();

    // =========================================================================
    // STEP 2: Now test with multiple cursors
    // =========================================================================

    // Create three empty lines by pressing Enter 3 times
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Buffer should be "\n\n\n" (3 newlines)
    harness.assert_buffer_content("\n\n\n");

    // Go to the first line
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Add two cursors below (so we have cursors on lines 1, 2, and 3)
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Should have 3 cursors
    assert_eq!(
        harness.editor().active_cursors().iter().count(),
        3,
        "Should have 3 cursors"
    );

    // Print cursor positions before typing
    println!("\nBefore typing 'foo()':");
    for (id, cursor) in harness.editor().active_cursors().iter() {
        println!("  Cursor {:?}: position={}", id, cursor.position);
    }

    // Type "foo" character by character
    harness.type_text("foo").unwrap();
    harness.render().unwrap();

    println!("\nAfter typing 'foo':");
    println!("Buffer: {:?}", harness.get_buffer_content().unwrap());

    // Now type '(' - this should auto-close to '()'
    harness.type_text("(").unwrap();
    harness.render().unwrap();

    println!("\nAfter typing '(':");
    println!("Buffer: {:?}", harness.get_buffer_content().unwrap());

    // Buffer should now have "foo()" on each of the 3 lines
    // Expected: "foo()\nfoo()\nfoo()\n"
    let buffer_content = harness.get_buffer_content().unwrap();
    assert_eq!(
        buffer_content, "foo()\nfoo()\nfoo()\n",
        "Auto-close should have added closing paren on ALL lines with multiple cursors. Buffer: {:?}",
        buffer_content
    );
    println!("✓ Auto-close works with multiple cursors");

    // Now type ')' - this should skip over the existing ')' on ALL cursors (not add another)
    harness.type_text(")").unwrap();
    harness.render().unwrap();

    println!("\nAfter typing ')':");
    println!("Buffer: {:?}", harness.get_buffer_content().unwrap());

    // Final buffer should be "foo()\nfoo()\nfoo()\n" - no double parens
    // BUG: With multiple cursors, skip-over positions are miscalculated causing
    // `)` to be inserted at wrong positions instead of skipping
    let final_buffer = harness.get_buffer_content().unwrap();
    assert_eq!(
        final_buffer, "foo()\nfoo()\nfoo()\n",
        "Skip-over should work with multiple cursors - typing ')' should skip existing ')' on ALL lines. Got: {:?}",
        final_buffer
    );
}

/// Test that cut with multiple cursor selections works correctly
/// Each cursor has a selection, and cut should remove all selected text
#[test]
fn test_multicursor_cut() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type content with repeated words
    harness
        .type_text("hello world\nhello world\nhello world\n")
        .unwrap();
    harness.render().unwrap();

    // Move to beginning
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Add cursors below (should have 3 cursors, one per line)
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Verify 3 cursors
    assert_eq!(
        harness.editor().active_cursors().iter().count(),
        3,
        "Should have 3 cursors"
    );

    // Select "hello" on each line with Shift+End (word at start of each line)
    // First, select the word "hello" by pressing Shift+Right 5 times
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::SHIFT)
            .unwrap();
    }
    harness.render().unwrap();

    // Verify all cursors have selections
    for (id, cursor) in harness.editor().active_cursors().iter() {
        assert!(
            cursor.selection_range().is_some(),
            "Cursor {:?} should have a selection",
            id
        );
        let range = cursor.selection_range().unwrap();
        assert_eq!(
            range.end - range.start,
            5,
            "Selection should be 5 characters (hello), got {}",
            range.end - range.start
        );
    }

    // Perform cut (Ctrl+X)
    harness
        .send_key(KeyCode::Char('x'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Buffer should now have " world" on each line (hello removed)
    let buffer_content = harness.get_buffer_content().unwrap();
    assert_eq!(
        buffer_content, " world\n world\n world\n",
        "Cut should remove 'hello' from all lines. Got: {:?}",
        buffer_content
    );
}

/// Test that cut with multiple non-overlapping selections preserves correct positions
#[test]
fn test_multicursor_cut_same_line() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type content with two instances of "foo" on same line
    harness.type_text("foo bar foo baz").unwrap();
    harness.render().unwrap();

    // Move cursor to start
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Select first "foo" using Ctrl+D (add cursor at next match)
    // First, select "foo" with Shift+Right 3 times
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::SHIFT)
            .unwrap();
    }
    harness.render().unwrap();

    // Add cursor at next "foo" match
    harness.editor_mut().add_cursor_at_next_match();
    harness.render().unwrap();

    // Should have 2 cursors
    assert_eq!(
        harness.editor().active_cursors().iter().count(),
        2,
        "Should have 2 cursors"
    );

    // Cut - should remove both "foo"s
    harness
        .send_key(KeyCode::Char('x'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Buffer should now have " bar  baz" (both "foo"s removed)
    let buffer_content = harness.get_buffer_content().unwrap();
    assert_eq!(
        buffer_content, " bar  baz",
        "Cut should remove both 'foo' instances. Got: {:?}",
        buffer_content
    );
}

/// Test that cut with multiple cursors can be undone in a single undo operation
/// This tests the bug where multiple cursor cut undo was not batched properly
#[test]
fn test_multicursor_cut_undo_batched() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type content with repeated words
    harness
        .type_text("hello world\nhello world\nhello world\n")
        .unwrap();
    harness.render().unwrap();

    // Move to beginning
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Add cursors below (should have 3 cursors, one per line)
    harness.editor_mut().add_cursor_below();
    harness.editor_mut().add_cursor_below();
    harness.render().unwrap();

    // Verify 3 cursors
    assert_eq!(
        harness.editor().active_cursors().iter().count(),
        3,
        "Should have 3 cursors"
    );

    // Select "hello" on each line with Shift+Right 5 times
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::SHIFT)
            .unwrap();
    }
    harness.render().unwrap();

    // Perform cut (Ctrl+X)
    harness
        .send_key(KeyCode::Char('x'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify cut worked
    let buffer_after_cut = harness.get_buffer_content().unwrap();
    assert_eq!(
        buffer_after_cut, " world\n world\n world\n",
        "Cut should remove 'hello' from all lines"
    );

    // Undo with a single Ctrl+Z - should restore all "hello"s at once
    harness
        .send_key(KeyCode::Char('z'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Buffer should be restored to original content after single undo
    let buffer_after_undo = harness.get_buffer_content().unwrap();
    assert_eq!(
        buffer_after_undo, "hello world\nhello world\nhello world\n",
        "Single undo should restore all 'hello' instances (undo should be batched)"
    );
}