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
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
use crate::common::harness::EditorTestHarness;
use crossterm::event::{KeyCode, KeyModifiers};
use tempfile::TempDir;

/// Test that selections are visually visible on screen
#[test]
fn test_selection_visual_rendering() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type some text
    harness.type_text("Hello World").unwrap();

    // Move to start of line
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Select the word "Hello" using Shift+Right (5 times)
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::SHIFT)
            .unwrap();
    }
    harness.render().unwrap();

    // Verify the cursor has a selection in the buffer
    let cursor = harness.editor().active_cursors().primary();
    let cursor_pos = cursor.position;
    let selection = cursor.selection_range();
    assert!(selection.is_some(), "Cursor should have a selection");

    let range = selection.unwrap();
    assert_eq!(range.start, 0, "Selection should start at position 0");
    assert_eq!(range.end, 5, "Selection should end at position 5");

    println!("Cursor position: {cursor_pos}, Selection: {range:?}");

    // Verify the selected text is "Hello"
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "Hello", "Selected text should be 'Hello'");

    // Get the screen rendering
    let _screen = harness.screen_to_string();

    // The screen should contain the text "Hello World"
    harness.assert_screen_contains("Hello World");

    // Check that the selected characters have the theme's selection background
    // Gutter takes up 8 characters: " " (indicator) + "   1" (line num) + " │ " (separator)
    // So "Hello" starts at column 8
    let buffer = harness.buffer();
    let theme = harness.editor().theme();
    let selection_bg = theme.selection_bg;

    // Get content area bounds from harness (accounts for menu bar, tab bar, status bar)
    let (content_first_row, _content_last_row) = harness.content_area_rows();
    let first_line_row = content_first_row as u16;

    // Check first character 'H' at position (8, first_line_row) - should have selection background
    let h_pos = buffer.index_of(8, first_line_row);
    let h_cell = &buffer.content[h_pos];
    assert_eq!(h_cell.symbol(), "H");
    assert_eq!(
        h_cell.bg, selection_bg,
        "Selected character 'H' should have selection background"
    );

    // Check fourth character 'l' at position (11, first_line_row) - should have selection background
    let l_pos = buffer.index_of(11, first_line_row);
    let l_cell = &buffer.content[l_pos];
    assert_eq!(l_cell.symbol(), "l");
    assert_eq!(
        l_cell.bg, selection_bg,
        "Selected character 'l' should have selection background"
    );

    // Check fifth character 'o' at position (12, first_line_row) - byte position 4, IN selection
    let o_pos = buffer.index_of(12, first_line_row);
    let o_cell = &buffer.content[o_pos];
    assert_eq!(o_cell.symbol(), "o");
    // This 'o' is at byte position 4, which is in the selection range 0..5
    // But the cursor is at position 5, not 4, so this should have selection background
    assert_eq!(
        o_cell.bg, selection_bg,
        "Selected character 'o' (byte 4) should have selection background"
    );

    // Check character ' ' (space) at position (13, first_line_row) - byte position 5, cursor position
    let space_pos = buffer.index_of(13, first_line_row);
    let space_cell = &buffer.content[space_pos];
    assert_eq!(space_cell.symbol(), " ");
    // This space is at byte position 5, which is the cursor position
    // It should NOT have selection background (cursor takes precedence over selection)
    // Also, position 5 is not in the selection range 0..5 anyway
    assert_ne!(
        space_cell.bg, selection_bg,
        "Cursor position (byte 5, space) should NOT have selection background"
    );
}

/// Test select word functionality (Ctrl+W)
#[test]
fn test_select_word() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type some text with multiple words
    harness.type_text("hello world test").unwrap();

    // Move to the middle of "world"
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..8 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Now cursor is at position 8 (in the middle of "world")
    // Select word with Ctrl+W
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();

    // Verify the selection
    let cursor = harness.editor().active_cursors().primary();
    let selection = cursor.selection_range();
    assert!(selection.is_some(), "Cursor should have a selection");

    let range = selection.unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "world", "Should select the word 'world'");
}

/// Test select word at start of word
#[test]
fn test_select_word_at_start() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("hello world").unwrap();

    // Move to start of "world"
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..6 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Select word
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "world", "Should select the word 'world'");
}

/// Test select word at end of word
#[test]
fn test_select_word_at_end() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("hello world").unwrap();

    // Move to end of "hello"
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Select word
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "hello", "Should select the word 'hello'");
}

/// Test select line functionality (Ctrl+L)
#[test]
fn test_select_line() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type multiple lines
    harness
        .type_text("first line\nsecond line\nthird line")
        .unwrap();

    // Move to start of document, then down to second line
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Select line with Ctrl+L
    harness
        .send_key(KeyCode::Char('l'), KeyModifiers::CONTROL)
        .unwrap();

    // Verify the selection includes the entire line
    let cursor = harness.editor().active_cursors().primary();
    let selection = cursor.selection_range();
    assert!(selection.is_some(), "Cursor should have a selection");

    let range = selection.unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "second line\n",
        "Should select the entire line including newline"
    );
}

/// Test select line on first line
#[test]
fn test_select_line_first() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("first line\nsecond line").unwrap();

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

    // Select line
    harness
        .send_key(KeyCode::Char('l'), KeyModifiers::CONTROL)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "first line\n",
        "Should select the first line"
    );
}

/// Test select line on last line (no trailing newline)
#[test]
fn test_select_line_last() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("first line\nsecond line").unwrap();

    // Select line (cursor is already on last line)
    harness
        .send_key(KeyCode::Char('l'), KeyModifiers::CONTROL)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "second line",
        "Should select the last line without newline"
    );
}

/// Test select word with multiple cursors
#[test]
fn test_select_word_multi_cursor() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type text with words
    harness.type_text("hello world test").unwrap();

    // Move to "hello"
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Add cursor at "world" using Ctrl+D (add cursor at next match)
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .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();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap();

    // Now we have "hello" selected, add cursor at next space or different word
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();

    // Add cursor above at same column
    harness
        .send_key(KeyCode::Down, KeyModifiers::CONTROL | KeyModifiers::ALT)
        .unwrap();

    // This test validates multi-cursor infrastructure is ready
    assert!(
        harness.editor().active_cursors().count() >= 1,
        "Should have at least one cursor"
    );
}

/// Test expand selection functionality (Ctrl+Shift+Right)
#[test]
fn test_expand_selection() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Type text with multiple words
    harness.type_text("hello world test").unwrap();

    // Move to middle of "hello" (position 3, second 'l')
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // First expand should select from cursor to end of current word
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "lo",
        "First expand should select from cursor to end of word"
    );

    // Second expand should extend to include " world"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "lo world",
        "Second expand should include next word"
    );

    // Third expand should extend to include " test"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "lo world test",
        "Third expand should include third word"
    );
}

/// Test expand selection when starting with no selection
#[test]
fn test_expand_selection_no_initial_selection() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("foo bar baz").unwrap();

    // Move to middle of "bar" (position 5, on 'a')
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Expand with no initial selection should select from cursor to end of word
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ar",
        "Should select from cursor to end of word"
    );
}

/// Test expand selection performance with moderately large buffer
/// This test ensures that selection operations don't read the entire buffer
#[test]
#[ignore]
fn test_expand_selection_large_buffer_performance() {
    use crossterm::event::{KeyCode, KeyModifiers};
    use std::fs;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large.txt");

    // Create a moderately large file (~100KB of text)
    let large_text = "word ".repeat(20_000); // ~100KB of text
    fs::write(&file_path, &large_text).unwrap();

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

    // Move to a position near the middle
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    for _ in 0..50 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // Expand selection - this used to hang/timeout with large buffers
    // because it would read the entire buffer. Now it should complete quickly
    // by only reading a small window around the cursor.
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    // Verify it works correctly
    let cursor = harness.editor().active_cursors().primary();
    assert!(
        cursor.selection_range().is_some(),
        "Should have a selection"
    );

    // The selected text should be a word (not testing exact content since position may vary)
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert!(!selected_text.is_empty(), "Selection should not be empty");
}

/// Test with an extremely large buffer (simulating the 63MB file issue)
/// This verifies the windowed reading approach works with very large files
#[test]
#[ignore] // This test takes a long time - run with --ignored flag
fn test_expand_selection_very_large_buffer() {
    use crossterm::event::{KeyCode, KeyModifiers};
    use std::fs;
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("very_large.txt");

    // Create a very large file (~10MB of text - representative of the issue)
    let large_text = "word ".repeat(2_000_000); // ~10MB of text
    fs::write(&file_path, &large_text).unwrap();

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

    // Move to various positions in the file and test expand selection
    // Test near the beginning
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    for _ in 0..100 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    assert!(
        cursor.selection_range().is_some(),
        "Should have selection at start"
    );

    // Test in the middle (move down many lines)
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap(); // Clear selection
    for _ in 0..1000 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }

    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    assert!(
        cursor.selection_range().is_some(),
        "Should have selection in middle"
    );

    // All operations should complete without hanging
}

/// Test selecting words after scrolling down beyond initial viewport
/// Ensures word selection works correctly at any position, not just visible lines
#[test]
fn test_select_word_after_scrolling() {
    use crossterm::event::{KeyCode, KeyModifiers};

    // Initialize tracing
    use tracing_subscriber::EnvFilter;
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::DEBUG.into()))
        .with_test_writer()
        .try_init();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create a buffer with many lines (more than viewport height)
    let content: String = (0..100)
        .map(|i| format!("line{i} word{i} test{i}"))
        .collect::<Vec<_>>()
        .join("\n");
    let _fixture = harness.load_buffer_from_text(&content).unwrap();

    // Scroll down past the initial viewport
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    // Use send_key_repeat to avoid rendering after each key press (much faster)
    harness
        .send_key_repeat(KeyCode::Down, KeyModifiers::NONE, 50)
        .unwrap();

    // Move to middle of a word on line 50
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    // Use send_key_repeat to avoid rendering after each key press (much faster)
    harness
        .send_key_repeat(KeyCode::Right, KeyModifiers::NONE, 10)
        .unwrap();

    // Select word with Ctrl+W
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);

    // Should have selected "word50" at line 50
    assert!(
        selected_text.contains("word"),
        "Should select a word after scrolling"
    );
    assert!(!selected_text.is_empty(), "Selection should not be empty");
}

/// Test expand selection after scrolling down
#[test]
fn test_expand_selection_after_scrolling() {
    use crossterm::event::{KeyCode, KeyModifiers};

    // Initialize tracing
    use tracing_subscriber::EnvFilter;
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::DEBUG.into()))
        .with_test_writer()
        .try_init();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create a buffer with many lines
    let content: String = (0..50)
        .map(|i| format!("alpha beta gamma delta epsilon line{i}"))
        .collect::<Vec<_>>()
        .join("\n");
    let _fixture = harness.load_buffer_from_text(&content).unwrap();

    // Scroll down to line 30
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    // Use send_key_repeat to avoid rendering after each key press (much faster)
    harness
        .send_key_repeat(KeyCode::Down, KeyModifiers::NONE, 30)
        .unwrap();

    // Move to middle of "alpha" (position 3, 'h')
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    for _ in 0..3 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }

    // First expand should select from cursor to end of word
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ha",
        "First expand should select from cursor to end of word"
    );

    // Second expand should extend to include " beta"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ha beta",
        "Second expand should include next word"
    );
}

/// Test expand selection (Ctrl+Shift+Right) across line boundaries
/// Ensures selection can expand from end of one line to beginning of next
#[test]
fn test_expand_selection_across_lines() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Create multi-line content with words at line boundaries
    harness
        .type_text("first line ending\nsecond line starting here")
        .unwrap();

    // Position cursor at "ending" on first line
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();
    // Move back to start of "ending"
    for _ in 0..6 {
        harness.send_key(KeyCode::Left, KeyModifiers::NONE).unwrap();
    }

    // First expand: select "ending"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ending",
        "Should select 'ending' on first line"
    );

    // Second expand: should cross the newline and select "second" on next line
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ending\nsecond",
        "Should cross line boundary and select 'second'"
    );

    // Third expand: should continue to "line"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "ending\nsecond line",
        "Should include 'line' from second line"
    );
}

/// Test expand selection starting at end of line
#[test]
fn test_expand_selection_from_line_end() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("first line\nsecond word here").unwrap();

    // Position cursor at end of first line (before newline)
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();

    // First expand from end of line - should jump to next word on next line
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);

    // The selection should include the newline and "second"
    assert!(!selected_text.is_empty(), "Should select something");
    assert!(
        selected_text.contains("second"),
        "Should jump to next line and select 'second'"
    );

    // Continue expanding to ensure we can reach the next line
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);

    // After multiple expands, we should definitely reach "second" on the next line
    assert!(
        selected_text.contains("second"),
        "Should eventually reach 'second' on next line"
    );
}

/// Test select word with hyphen - hyphen should be a word separator
#[test]
fn test_select_word_with_hyphen() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("foo-bar").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "foo",
        "Hyphen should be a word separator, selecting 'foo'"
    );
}

/// Test select word with underscore - underscore should be a word character
#[test]
fn test_select_word_with_underscore() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("baz_qux").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "baz_qux",
        "Underscore should be a word char, selecting 'baz_qux'"
    );
}

/// Test select word with numbers - alphanumeric should be a word
#[test]
fn test_select_word_with_numbers() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("test123").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "test123",
        "Alphanumeric should be a single word"
    );
}

/// Test select word with @ symbol - @ should be a word separator
#[test]
fn test_select_word_with_at_symbol() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("user@domain").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "user",
        "@ should be a word separator, selecting 'user'"
    );
}

/// Test select word with dot - dot should be a word separator
#[test]
fn test_select_word_with_dot() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("domain.com").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "domain",
        ". should be a word separator, selecting 'domain'"
    );
}

/// Test expand selection (Ctrl+Shift+Right) when cursor is on a non-word character
/// From punctuation, Ctrl+Right consumes all punctuation and stops at word boundary
#[test]
fn test_expand_selection_on_non_word_char() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Test case: cursor on first * in "**-word"
    harness.type_text("**-word").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Cursor is now on the first *, press Ctrl+Shift+Right to expand selection
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range();

    // Should select punctuation only: "**-" (stops at word boundary)
    assert!(
        range.is_some(),
        "Should have a selection after Ctrl+Shift+Right"
    );

    if let Some(range) = range {
        let selected_text = harness
            .editor_mut()
            .active_state_mut()
            .get_text_range(range.start, range.end);
        assert_eq!(
            selected_text, "**-",
            "Should select punctuation only (stops at word boundary)"
        );
    }
}

/// Test expand selection starting on a word character
#[test]
fn test_expand_selection_on_word_char() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("hello world").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Cursor on 'h' in "hello", press Ctrl+Shift+Right
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "hello", "Should select the current word");
}

/// Test expand selection from middle of word
/// Should select from cursor to end of current word only
#[test]
fn test_expand_selection_from_middle_of_word() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("Event").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    // Move cursor to 'v' (second character)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();

    // Press Ctrl+Shift+Right from 'v' in "Event"
    harness
        .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    // Should select from 'v' to end: "vent", not the whole word "Event"
    assert_eq!(
        selected_text, "vent",
        "Should select from cursor to end of word"
    );
}

/// Test select word left (Ctrl+Shift+Left) when cursor is on a non-word character
/// Should select backward from cursor through non-word chars, then to start of previous word
#[test]
fn test_select_word_left_on_non_word_char() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    harness.type_text("word**-").unwrap();
    // Cursor is at end after typing (after the '-')

    // Press Ctrl+Shift+Left to select backward
    // First step: should select punctuation "**-"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range();

    assert!(
        range.is_some(),
        "Should have a selection after Ctrl+Shift+Left"
    );

    if let Some(range) = range {
        let selected_text = harness
            .editor_mut()
            .active_state_mut()
            .get_text_range(range.start, range.end);
        assert_eq!(
            selected_text, "**-",
            "Should select backward from cursor through non-word chars"
        );
    }

    // Press Ctrl+Shift+Left again to select the word "word"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        .unwrap();

    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);

    assert_eq!(
        selected_text, "word**-",
        "Should extend selection to include 'word' after second step"
    );
}

/// Test select previous word with non-alphanumeric characters
/// Moving backward should also respect word boundaries (alphanumeric + underscore)
#[test]
fn test_select_prev_word_with_special_chars() {
    use crossterm::event::{KeyCode, KeyModifiers};
    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Same test text but working backwards
    harness
        .type_text("start foo-bar baz_qux test123 user@domain.com")
        .unwrap();

    // Cursor is at end of text after typing
    // Move back one word and select "com" (. is a separator)
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "com", "Should select 'com' backwards");

    // Move back and select "domain"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "domain", "Should select 'domain' backwards");

    // Move back and select "user"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "user",
        "Should select 'user' backwards (@ is a separator)"
    );

    // Move back and select "test123"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "test123",
        "Should select 'test123' backwards"
    );

    // Move back and select "baz_qux"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "baz_qux",
        "Should select 'baz_qux' backwards (underscore is a word char)"
    );

    // Move back and select "bar"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(selected_text, "bar", "Should select 'bar' backwards");

    // Move back and select "foo"
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Left, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('w'), KeyModifiers::CONTROL)
        .unwrap();
    let cursor = harness.editor().active_cursors().primary();
    let range = cursor.selection_range().unwrap();
    let selected_text = harness
        .editor_mut()
        .active_state_mut()
        .get_text_range(range.start, range.end);
    assert_eq!(
        selected_text, "foo",
        "Should select 'foo' backwards (hyphen is a separator)"
    );
}

/// Test Shift+Up selection (select from cursor to previous line)
#[test]
fn test_select_up() {
    // Initialize tracing
    use tracing_subscriber::EnvFilter;
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::DEBUG.into()))
        .with_test_writer()
        .try_init();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a file with multiple lines
    let content = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n";
    std::fs::write(&file_path, content).unwrap();

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

    // Move to line 3 (start of "Line 3")
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Verify cursor is at start of line 3
    let cursor_pos = harness.cursor_position();
    let buffer_content = harness.get_buffer_content().unwrap();
    assert_eq!(&buffer_content[cursor_pos..cursor_pos + 6], "Line 3");

    // No selection yet
    harness.assert_no_selection();
    tracing::trace!(
        "Initial state - selected text: {:?}",
        harness.get_selected_text()
    );

    // Press Shift+Up to select upward
    harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    harness.render().unwrap();

    // Should now have a selection
    assert!(
        harness.has_selection(),
        "Should have selection after Shift+Up"
    );

    // The selection should include "Line 2\n"
    let selected = harness.get_selected_text();
    tracing::trace!("After first Shift+Up - selected text: {:?}", selected);
    assert_eq!(selected, "Line 2\n", "Selection should be 'Line 2\n'");

    // Press Shift+Up again to extend selection further
    harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    harness.render().unwrap();

    // Selection should now include both lines
    let selected = harness.get_selected_text();
    tracing::trace!("After second Shift+Up - selected text: {:?}", selected);
    assert_eq!(
        selected, "Line 1\nLine 2\n",
        "Selection should span two lines"
    );
}

/// Test Shift+Down selection (select from cursor to next line)
#[test]
fn test_select_down() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a file with multiple lines
    let content = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n";
    std::fs::write(&file_path, content).unwrap();

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

    // Cursor starts at position 0 (beginning of file)
    harness.assert_no_selection();

    // Press Shift+Down to select downward
    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Should now have a selection
    assert!(
        harness.has_selection(),
        "Should have selection after Shift+Down"
    );

    // The selection should include "Line 1\n"
    let selected = harness.get_selected_text();
    assert_eq!(selected, "Line 1\n", "Selection should be 'Line 1\n'");

    // Press Shift+Down again to extend selection
    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Selection should now include two lines
    let selected = harness.get_selected_text();
    assert_eq!(
        selected, "Line 1\nLine 2\n",
        "Selection should span two lines"
    );

    // Press Shift+Down once more
    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Selection should now include three lines
    let selected = harness.get_selected_text();
    assert_eq!(
        selected, "Line 1\nLine 2\nLine 3\n",
        "Selection should span three lines"
    );
}

/// Test Shift+Up and Shift+Down together (reversing selection direction)
#[test]
fn test_select_up_down_reversal() {
    // Initialize tracing
    use tracing_subscriber::EnvFilter;
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::DEBUG.into()))
        .with_test_writer()
        .try_init();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    let content = "Line 1\nLine 2\nLine 3\nLine 4\n";
    std::fs::write(&file_path, content).unwrap();

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

    // Move to line 2
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    tracing::trace!(
        "Initial state (at line 2) - selected text: {:?}",
        harness.get_selected_text()
    );

    // Select down two lines
    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();
    tracing::trace!(
        "After first Shift+Down - selected text: {:?}",
        harness.get_selected_text()
    );

    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    let selected = harness.get_selected_text();
    tracing::trace!("After second Shift+Down - selected text: {:?}", selected);
    assert_eq!(selected, "Line 2\nLine 3\n");

    // Now go back up one line (shrink selection)
    harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    harness.render().unwrap();

    let selected = harness.get_selected_text();
    tracing::trace!(
        "After first Shift+Up (shrinking) - selected text: {:?}",
        selected
    );
    assert_eq!(selected, "Line 2\n", "Selection should shrink");

    // Go up again - this should collapse the selection (back to anchor)
    harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    harness.render().unwrap();

    // After going past the anchor, selection collapses
    // This is expected behavior - we've moved back to where we started
    let selected = harness.get_selected_text();
    tracing::trace!(
        "After second Shift+Up (at/past anchor) - selected text: {:?}",
        selected
    );
    // Selection might be empty now (collapsed at anchor) or might have reversed
    // Either behavior is acceptable
}

/// Test Shift+PageDown selection (select a page down)
#[test]
fn test_select_page_down() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a file with many lines (more than can fit on screen)
    let mut content = String::new();
    for i in 1..=50 {
        content.push_str(&format!("Line {i}\n"));
    }
    std::fs::write(&file_path, &content).unwrap();

    // Use smaller height to make page behavior predictable
    let mut harness = EditorTestHarness::new(80, 10).unwrap();
    harness.open_file(&file_path).unwrap();

    // Cursor starts at beginning
    harness.assert_no_selection();

    // Press Shift+PageDown to select a page down
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Should have a selection
    assert!(
        harness.has_selection(),
        "Should have selection after Shift+PageDown"
    );

    let selected = harness.get_selected_text();
    // With height 10, viewport height varies based on status bars
    // Selection should include multiple lines (at least 4)
    let selected_lines = selected.lines().count();
    assert!(
        selected_lines >= 4,
        "Should select approximately a page of lines, got {selected_lines} lines"
    );

    // Verify selection includes multiple lines starting from Line 1
    assert!(selected.contains("Line 1"));
    assert!(selected.contains("Line 2"));
}

/// Test Shift+PageUp selection (select a page up)
#[test]
fn test_select_page_up() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a file with many lines
    let mut content = String::new();
    for i in 1..=50 {
        content.push_str(&format!("Line {i}\n"));
    }
    std::fs::write(&file_path, &content).unwrap();

    // Use smaller height to make page behavior predictable
    let mut harness = EditorTestHarness::new(80, 10).unwrap();
    harness.open_file(&file_path).unwrap();

    // Move down several pages first
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Now we're somewhere in the middle of the file
    let cursor_before = harness.cursor_position();
    assert!(cursor_before > 100, "Should be well into the file");

    harness.assert_no_selection();

    // Press Shift+PageUp to select a page up
    harness
        .send_key(KeyCode::PageUp, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Should have a selection
    assert!(
        harness.has_selection(),
        "Should have selection after Shift+PageUp"
    );

    let selected = harness.get_selected_text();
    let selected_lines = selected.lines().count();
    assert!(
        selected_lines >= 4,
        "Should select approximately a page of lines, got {selected_lines} lines"
    );

    // Selection should not be empty
    assert!(!selected.is_empty(), "Selection should not be empty");
}

/// Test Shift+PageDown and Shift+PageUp together
#[test]
fn test_select_page_up_down_combination() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a file with many lines
    let mut content = String::new();
    for i in 1..=100 {
        content.push_str(&format!("Line {i}\n"));
    }
    std::fs::write(&file_path, &content).unwrap();

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

    // Move to middle of file
    for _ in 0..5 {
        harness
            .send_key(KeyCode::PageDown, KeyModifiers::NONE)
            .unwrap();
    }

    // Select page down
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    assert!(harness.has_selection());
    let selection_after_page_down = harness.get_selected_text();
    let _lines_down = selection_after_page_down.lines().count();

    // Now select page up (should shrink/reverse selection)
    harness
        .send_key(KeyCode::PageUp, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Selection might still exist but should be different
    let selection_after_page_up = harness.get_selected_text();

    // The selections should be different
    assert_ne!(
        selection_after_page_down, selection_after_page_up,
        "Selections should differ after PageUp"
    );
}

// =============================================================================
// Ctrl+Left/Right Word Jump Tests
// =============================================================================
//
// Word jump behavior:
// - Ctrl+Right: jump to END of current word, then to end of next word
// - Ctrl+Left: jump to BEGINNING of current word, then to beginning of previous word
// - Ctrl+Shift+Left/Right: same movement pattern but extends selection
//
// Key properties tested:
// 1. Ctrl+Right from anywhere in a word -> end of that word
// 2. Ctrl+Left from anywhere in a word -> beginning of that word
// 3. Movement is symmetric: jumping right N times then left N times returns to start
// 4. Selection variants move to the same positions as non-selection variants

/// Property test: Ctrl+Right should jump to end of current word
/// From any position within a word, Ctrl+Right lands at the word's end.
/// From whitespace/punctuation, it lands at end of next token.
#[test]
fn test_ctrl_right_jumps_to_word_end() {
    // Test 1: Simple words with spaces
    // "hello world test"
    //  01234 56789A BCDEF  (positions in hex-ish for clarity)
    {
        let text = "hello world test";
        let expected_destinations: Vec<(usize, usize)> = vec![
            (0, 5),   // from 'h' -> end of "hello"
            (1, 5),   // from 'e' -> end of "hello"
            (2, 5),   // from 'l' -> end of "hello"
            (3, 5),   // from 'l' -> end of "hello"
            (4, 5),   // from 'o' -> end of "hello"
            (5, 11),  // from space -> end of "world"
            (6, 11),  // from 'w' -> end of "world"
            (7, 11),  // from 'o' -> end of "world"
            (8, 11),  // from 'r' -> end of "world"
            (9, 11),  // from 'l' -> end of "world"
            (10, 11), // from 'd' -> end of "world"
            (11, 16), // from space -> end of "test"
            (12, 16), // from 't' -> end of "test"
            (13, 16), // from 'e' -> end of "test"
            (14, 16), // from 's' -> end of "test"
            (15, 16), // from 't' -> end of "test"
            (16, 16), // from end -> stay at end
        ];

        for (start_pos, expected_end) in expected_destinations {
            let mut harness = EditorTestHarness::new(80, 24).unwrap();
            harness.type_text(text).unwrap();
            harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

            for _ in 0..start_pos {
                harness
                    .send_key(KeyCode::Right, KeyModifiers::NONE)
                    .unwrap();
            }
            assert_eq!(harness.cursor_position(), start_pos);

            harness
                .send_key(KeyCode::Right, KeyModifiers::CONTROL)
                .unwrap();

            assert_eq!(
                harness.cursor_position(),
                expected_end,
                "Simple text: from position {}, Ctrl+Right should jump to {} (got {})",
                start_pos,
                expected_end,
                harness.cursor_position()
            );
        }
    }

    // Test 2: Multiline with punctuation before newline
    // "bla::{\n   next"
    // Positions: b=0, l=1, a=2, :=3, :=4, {=5, \n=6, ' '=7, ' '=8, ' '=9, n=10, e=11, x=12, t=13
    // From after "bla" (position 3, on ':'), Ctrl+Right should stop at end of line (position 6)
    {
        let text = "bla::{\n   next";
        let expected_destinations: Vec<(usize, usize)> = vec![
            (0, 3),   // from 'b' -> end of "bla"
            (1, 3),   // from 'l' -> end of "bla"
            (2, 3),   // from 'a' -> end of "bla"
            (3, 6),   // from ':' -> end of punctuation "::{" (before newline)
            (4, 6),   // from ':' -> end of punctuation "::{" (before newline)
            (5, 6),   // from '{' -> end of punctuation (before newline)
            (6, 14),  // from newline -> skip whitespace, end of "next"
            (7, 14),  // from space -> end of "next"
            (8, 14),  // from space -> end of "next"
            (9, 14),  // from space -> end of "next"
            (10, 14), // from 'n' -> end of "next"
            (11, 14), // from 'e' -> end of "next"
            (12, 14), // from 'x' -> end of "next"
            (13, 14), // from 't' -> end of "next"
            (14, 14), // from end -> stay at end
        ];

        for (start_pos, expected_end) in expected_destinations {
            let mut harness = EditorTestHarness::new(80, 24).unwrap();
            harness.type_text(text).unwrap();
            harness
                .send_key(KeyCode::Home, KeyModifiers::CONTROL)
                .unwrap();

            for _ in 0..start_pos {
                harness
                    .send_key(KeyCode::Right, KeyModifiers::NONE)
                    .unwrap();
            }
            assert_eq!(harness.cursor_position(), start_pos);

            harness
                .send_key(KeyCode::Right, KeyModifiers::CONTROL)
                .unwrap();

            assert_eq!(
                harness.cursor_position(),
                expected_end,
                "Multiline: from position {}, Ctrl+Right should jump to {} (got {})",
                start_pos,
                expected_end,
                harness.cursor_position()
            );
        }
    }
}

/// Property test: Ctrl+Left should jump to beginning of current word
/// From any position within a word, Ctrl+Left lands at the word's beginning.
/// From whitespace/punctuation, it lands at beginning of previous token.
#[test]
fn test_ctrl_left_jumps_to_word_beginning() {
    // Test 1: Simple words with spaces
    // "hello world test"
    {
        let text = "hello world test";
        let expected_destinations: Vec<(usize, usize)> = vec![
            (0, 0),   // from start -> stay at start
            (1, 0),   // from 'e' -> start of "hello"
            (2, 0),   // from 'l' -> start of "hello"
            (3, 0),   // from 'l' -> start of "hello"
            (4, 0),   // from 'o' -> start of "hello"
            (5, 0),   // from space -> start of "hello"
            (6, 0),   // from 'w' (start of word) -> start of "hello"
            (7, 6),   // from 'o' -> start of "world"
            (8, 6),   // from 'r' -> start of "world"
            (9, 6),   // from 'l' -> start of "world"
            (10, 6),  // from 'd' -> start of "world"
            (11, 6),  // from space -> start of "world"
            (12, 6),  // from 't' (start of word) -> start of "world"
            (13, 12), // from 'e' -> start of "test"
            (14, 12), // from 's' -> start of "test"
            (15, 12), // from 't' -> start of "test"
            (16, 12), // from end -> start of "test"
        ];

        for (start_pos, expected_end) in expected_destinations {
            let mut harness = EditorTestHarness::new(80, 24).unwrap();
            harness.type_text(text).unwrap();
            harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

            for _ in 0..start_pos {
                harness
                    .send_key(KeyCode::Right, KeyModifiers::NONE)
                    .unwrap();
            }
            assert_eq!(harness.cursor_position(), start_pos);

            harness
                .send_key(KeyCode::Left, KeyModifiers::CONTROL)
                .unwrap();

            assert_eq!(
                harness.cursor_position(),
                expected_end,
                "Simple text: from position {}, Ctrl+Left should jump to {} (got {})",
                start_pos,
                expected_end,
                harness.cursor_position()
            );
        }
    }

    // Test 2: Multiline with punctuation before newline
    // "bla::{\n   next"
    // Positions: b=0, l=1, a=2, :=3, :=4, {=5, \n=6, ' '=7, ' '=8, ' '=9, n=10, e=11, x=12, t=13
    // From "next" on second line, Ctrl+Left should navigate back across lines
    {
        let text = "bla::{\n   next";
        let expected_destinations: Vec<(usize, usize)> = vec![
            (0, 0),   // from 'b' -> stay at start
            (1, 0),   // from 'l' -> start of "bla"
            (2, 0),   // from 'a' -> start of "bla"
            (3, 0),   // from ':' -> start of "bla"
            (4, 3),   // from ':' -> start of punctuation "::"
            (5, 3),   // from '{' -> start of punctuation "::"
            (6, 3),   // from newline -> start of punctuation
            (7, 3),   // from space -> start of punctuation (skips whitespace)
            (8, 3),   // from space -> start of punctuation
            (9, 3),   // from space -> start of punctuation
            (10, 3),  // from 'n' (start of "next") -> start of punctuation
            (11, 10), // from 'e' -> start of "next"
            (12, 10), // from 'x' -> start of "next"
            (13, 10), // from 't' -> start of "next"
            (14, 10), // from end -> start of "next"
        ];

        for (start_pos, expected_end) in expected_destinations {
            let mut harness = EditorTestHarness::new(80, 24).unwrap();
            harness.type_text(text).unwrap();
            harness
                .send_key(KeyCode::Home, KeyModifiers::CONTROL)
                .unwrap();

            for _ in 0..start_pos {
                harness
                    .send_key(KeyCode::Right, KeyModifiers::NONE)
                    .unwrap();
            }
            assert_eq!(harness.cursor_position(), start_pos);

            harness
                .send_key(KeyCode::Left, KeyModifiers::CONTROL)
                .unwrap();

            assert_eq!(
                harness.cursor_position(),
                expected_end,
                "Multiline: from position {}, Ctrl+Left should jump to {} (got {})",
                start_pos,
                expected_end,
                harness.cursor_position()
            );
        }
    }
}

/// Property test: Word jump should be reversible (roundtrip)
/// Jumping right N times then left N times should return to the starting position.
/// Note: Ctrl+Right goes to word ENDS, Ctrl+Left goes to word STARTS, so they
/// visit different intermediate positions, but the roundtrip should work.
#[test]
fn test_word_jump_symmetry() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.type_text("one two three four five").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    let start_position = harness.cursor_position();
    assert_eq!(start_position, 0);

    // Jump right 5 times (through all words)
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
    }
    let end_position = harness.cursor_position();
    assert_eq!(
        end_position, 23,
        "Should be at end of text after 5 Ctrl+Right"
    );

    // Jump left 5 times (back through all words)
    for _ in 0..5 {
        harness
            .send_key(KeyCode::Left, KeyModifiers::CONTROL)
            .unwrap();
    }
    let final_position = harness.cursor_position();

    // Should return to start
    assert_eq!(
        final_position, start_position,
        "Jumping right then left should return to start position"
    );
}

/// Property test: Ctrl+Shift+Left/Right should move to same positions as Ctrl+Left/Right
/// The only difference is that the selection variant maintains/extends selection.
#[test]
fn test_selection_movement_matches_regular_movement() {
    // Test 1: Simple single-line text
    {
        let text = "alpha beta gamma delta";

        let mut harness1 = EditorTestHarness::new(80, 24).unwrap();
        harness1.type_text(text).unwrap();
        harness1
            .send_key(KeyCode::Home, KeyModifiers::NONE)
            .unwrap();

        let mut harness2 = EditorTestHarness::new(80, 24).unwrap();
        harness2.type_text(text).unwrap();
        harness2
            .send_key(KeyCode::Home, KeyModifiers::NONE)
            .unwrap();

        for i in 0..4 {
            harness1
                .send_key(KeyCode::Right, KeyModifiers::CONTROL)
                .unwrap();
            harness2
                .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
                .unwrap();

            assert_eq!(
                harness1.cursor_position(),
                harness2.cursor_position(),
                "Simple text: After {} Ctrl+Right jumps, positions should match",
                i + 1
            );
        }
    }

    // Test 2: Multiline text with punctuation before newline
    // This is the critical case: "bla::{\n   next"
    // From after "bla", both Ctrl+Right and Ctrl+Shift+Right should stop at position 6 (end of line)
    {
        let text = "bla::{\n   next";

        let mut harness1 = EditorTestHarness::new(80, 24).unwrap();
        harness1.type_text(text).unwrap();
        harness1
            .send_key(KeyCode::Home, KeyModifiers::CONTROL)
            .unwrap();

        let mut harness2 = EditorTestHarness::new(80, 24).unwrap();
        harness2.type_text(text).unwrap();
        harness2
            .send_key(KeyCode::Home, KeyModifiers::CONTROL)
            .unwrap();

        // First jump: from 'b' to end of "bla" (position 3)
        harness1
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        harness2
            .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
            .unwrap();

        assert_eq!(
            harness1.cursor_position(),
            harness2.cursor_position(),
            "Multiline: After 1st jump, Ctrl+Right ({}) and Ctrl+Shift+Right ({}) should match",
            harness1.cursor_position(),
            harness2.cursor_position()
        );

        // Second jump: from ':' to end of punctuation (position 6, before newline)
        harness1
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        harness2
            .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
            .unwrap();

        assert_eq!(
            harness1.cursor_position(),
            harness2.cursor_position(),
            "Multiline: After 2nd jump (punctuation), Ctrl+Right ({}) and Ctrl+Shift+Right ({}) should match - both should stop at end of line",
            harness1.cursor_position(),
            harness2.cursor_position()
        );

        // Third jump: from newline to end of "next" (position 14)
        harness1
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        harness2
            .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
            .unwrap();

        assert_eq!(
            harness1.cursor_position(),
            harness2.cursor_position(),
            "Multiline: After 3rd jump, Ctrl+Right ({}) and Ctrl+Shift+Right ({}) should match",
            harness1.cursor_position(),
            harness2.cursor_position()
        );
    }

    // Test 3: Ctrl+Left vs Ctrl+Shift+Left
    {
        let text = "alpha beta gamma delta";

        let mut harness3 = EditorTestHarness::new(80, 24).unwrap();
        harness3.type_text(text).unwrap();

        let mut harness4 = EditorTestHarness::new(80, 24).unwrap();
        harness4.type_text(text).unwrap();

        for i in 0..4 {
            harness3
                .send_key(KeyCode::Left, KeyModifiers::CONTROL)
                .unwrap();
            harness4
                .send_key(KeyCode::Left, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
                .unwrap();

            assert_eq!(
                harness3.cursor_position(),
                harness4.cursor_position(),
                "After {} Ctrl+Left jumps, positions should match",
                i + 1
            );
        }

        // Verify selection is actually created with Shift variant
        assert!(
            harness4.has_selection(),
            "Ctrl+Shift+Left should create selection"
        );
    }
}

/// Sanity test: Known text with explicit expected positions for word navigation
/// This test uses concrete values to clearly document the desired behavior.
#[test]
fn test_word_navigation_sanity() {
    // Test 1: Simple words with spaces - "hello world test"
    // Positions: h=0, e=1, l=2, l=3, o=4, space=5, w=6, o=7, r=8, l=9, d=10, space=11, t=12...
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("hello world test").unwrap();
        harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

        // From 'h' (position 0), jump to end of "hello" (position 5)
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(harness.cursor_position(), 5, "From word start to word end");

        // From space (position 5), jump to end of "world" (position 11)
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(
            harness.cursor_position(),
            11,
            "From whitespace to next word end"
        );
    }

    // Test 2: Punctuation behavior - "event::{ thing"
    // Positions: e=0, v=1, e=2, n=3, t=4, :=5, :=6, {=7, space=8, t=9, h=10, i=11, n=12, g=13
    // From after "event" (on ":"), Ctrl+Right should stop after all punctuation "::{" (position 8)
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("event::{ thing").unwrap();
        harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

        // From 'e' (position 0), jump to end of "event" (position 5)
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(harness.cursor_position(), 5, "From word to end of word");

        // From ':' (position 5), jump to end of punctuation "::{" (position 8)
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(
            harness.cursor_position(),
            8,
            "From punctuation to end of punctuation run"
        );

        // From space (position 8), jump to end of "thing" (position 14)
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(
            harness.cursor_position(),
            14,
            "From whitespace to end of next word"
        );
    }

    // Test 3: Ctrl+Left behavior
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("alpha beta").unwrap();
        // Cursor is at end (position 10)

        // From end, jump to start of "beta" (position 6)
        harness
            .send_key(KeyCode::Left, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(
            harness.cursor_position(),
            6,
            "From end to start of last word"
        );

        // From start of "beta", jump to start of "alpha" (position 0)
        harness
            .send_key(KeyCode::Left, KeyModifiers::CONTROL)
            .unwrap();
        assert_eq!(
            harness.cursor_position(),
            0,
            "From word start to previous word start"
        );
    }

    // Test 4: Ctrl+Shift+Right selection
    {
        let mut harness = EditorTestHarness::new(80, 24).unwrap();
        harness.type_text("foo bar").unwrap();
        harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

        // Ctrl+Shift+Right should select "foo"
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
            .unwrap();
        assert_eq!(harness.cursor_position(), 3);
        let selected = harness.get_selected_text();
        assert_eq!(selected, "foo", "Should select first word");

        // Continue - should extend selection to include " bar"
        harness
            .send_key(KeyCode::Right, KeyModifiers::CONTROL | KeyModifiers::SHIFT)
            .unwrap();
        let selected = harness.get_selected_text();
        assert_eq!(selected, "foo bar", "Should extend selection to next word");
    }
}

/// Test that selection works correctly at file boundaries
#[test]
fn test_select_at_file_boundaries() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    let content = "Line 1\nLine 2\nLine 3\n";
    std::fs::write(&file_path, content).unwrap();

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

    // At start of file, Shift+Up should not panic or cause issues
    harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    harness.render().unwrap();
    // Either no selection or empty selection is fine

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

    // At end of file, Shift+Down should not panic
    harness
        .send_key(KeyCode::Down, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Select all the way up from end
    for _ in 0..5 {
        harness.send_key(KeyCode::Up, KeyModifiers::SHIFT).unwrap();
    }
    harness.render().unwrap();

    // After selecting upward from end, we should have some content selected
    // The key thing is that the editor doesn't crash at boundaries
    let _selected = harness.get_selected_text();
    // Just verify we can get selected text without panicking
    // The test validates that boundary operations don't crash
}

// =============================================================================
// Ctrl+D (Add Cursor at Next Match) Tests
// =============================================================================

/// Test that Ctrl+D selects the entire current word when cursor is in the middle
/// This matches behavior in other editors like VSCode
#[test]
fn test_ctrl_d_selects_entire_word_from_middle() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    // Text with repeated word "hello"
    harness.type_text("hello world hello").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Move cursor to middle of "hello" (position 2, on 'l')
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    assert_eq!(harness.cursor_position(), 2);

    // Press Ctrl+D - should select the ENTIRE word "hello", not just "llo"
    harness
        .send_key(KeyCode::Char('d'), KeyModifiers::CONTROL)
        .unwrap();

    let selected = harness.get_selected_text();
    assert_eq!(
        selected, "hello",
        "Ctrl+D from middle of word should select entire word 'hello', not just from cursor"
    );
}

/// Test that Ctrl+D finds next match after selecting current word
#[test]
fn test_ctrl_d_finds_next_match() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.type_text("foo bar foo baz foo").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // First Ctrl+D should select "foo"
    harness
        .send_key(KeyCode::Char('d'), KeyModifiers::CONTROL)
        .unwrap();
    let selected = harness.get_selected_text();
    assert_eq!(selected, "foo", "First Ctrl+D should select 'foo'");

    // Second Ctrl+D should add cursor at next "foo" (position 8)
    harness
        .send_key(KeyCode::Char('d'), KeyModifiers::CONTROL)
        .unwrap();

    // Should now have 2 cursors, both selecting "foo"
    let cursor_count = harness.cursor_count();
    assert_eq!(cursor_count, 2, "Should have 2 cursors after second Ctrl+D");
}

/// Test that Ctrl+D works correctly when cursor is at word start
#[test]
fn test_ctrl_d_at_word_start() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.type_text("test word test").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Cursor is at start of "test" (position 0)
    assert_eq!(harness.cursor_position(), 0);

    // Ctrl+D should select entire word "test"
    harness
        .send_key(KeyCode::Char('d'), KeyModifiers::CONTROL)
        .unwrap();

    let selected = harness.get_selected_text();
    assert_eq!(
        selected, "test",
        "Ctrl+D at word start should select 'test'"
    );
}

/// Test that Ctrl+D works correctly when cursor is at word end
#[test]
fn test_ctrl_d_at_word_end() {
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.type_text("word test word").unwrap();
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Move to end of "word" (position 4)
    for _ in 0..4 {
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
    }
    assert_eq!(harness.cursor_position(), 4);

    // Ctrl+D should select entire word "word" (going backward to include the whole word)
    harness
        .send_key(KeyCode::Char('d'), KeyModifiers::CONTROL)
        .unwrap();

    let selected = harness.get_selected_text();
    assert_eq!(
        selected, "word",
        "Ctrl+D at word end should select entire 'word'"
    );
}