ftui-text 0.4.0

Text layout, wrapping, and grapheme width for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Core text editing operations on top of Rope + CursorNavigator.
//!
//! [`Editor`] combines a [`Rope`] with a [`CursorPosition`] and provides
//! the standard editing operations (insert, delete, cursor movement) that
//! power TextArea and other editing widgets.
//!
//! # Example
//! ```
//! use ftui_text::editor::Editor;
//!
//! let mut ed = Editor::new();
//! ed.insert_text("hello");
//! ed.insert_char(' ');
//! ed.insert_text("world");
//! assert_eq!(ed.text(), "hello world");
//!
//! // Move cursor and delete
//! ed.move_left();
//! ed.move_left();
//! ed.move_left();
//! ed.move_left();
//! ed.move_left();
//! ed.delete_backward(); // deletes the space
//! assert_eq!(ed.text(), "helloworld");
//! ```

use crate::cursor::{CursorNavigator, CursorPosition};
use crate::rope::Rope;

/// A single edit operation for undo/redo.
#[derive(Debug, Clone)]
enum EditOp {
    Insert {
        byte_offset: usize,
        text: String,
    },
    Delete {
        byte_offset: usize,
        text: String,
    },
    Replace {
        byte_offset: usize,
        deleted: String,
        inserted: String,
    },
}

impl EditOp {
    fn inverse(&self) -> Self {
        match self {
            Self::Insert { byte_offset, text } => Self::Delete {
                byte_offset: *byte_offset,
                text: text.clone(),
            },
            Self::Delete { byte_offset, text } => Self::Insert {
                byte_offset: *byte_offset,
                text: text.clone(),
            },
            Self::Replace {
                byte_offset,
                deleted,
                inserted,
            } => Self::Replace {
                byte_offset: *byte_offset,
                deleted: inserted.clone(),
                inserted: deleted.clone(),
            },
        }
    }

    fn byte_len(&self) -> usize {
        match self {
            Self::Insert { text, .. } => text.len(),
            Self::Delete { text, .. } => text.len(),
            Self::Replace {
                deleted, inserted, ..
            } => deleted.len() + inserted.len(),
        }
    }
}

/// Selection defined by anchor (fixed) and head (moving with cursor).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selection {
    /// The fixed end of the selection.
    pub anchor: CursorPosition,
    /// The moving end (same as cursor).
    pub head: CursorPosition,
}

impl Selection {
    /// Byte range of the selection (start, end) where start <= end.
    #[must_use]
    pub fn byte_range(&self, nav: &CursorNavigator<'_>) -> (usize, usize) {
        let a = nav.to_byte_index(self.anchor);
        let b = nav.to_byte_index(self.head);
        if a <= b { (a, b) } else { (b, a) }
    }

    /// Whether the selection is empty (anchor == head).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.anchor == self.head
    }
}

/// Core text editor combining Rope storage with cursor management.
///
/// Provides insert/delete/move operations with grapheme-aware cursor
/// handling, undo/redo, and selection support.
/// Cursor is always kept in valid bounds.
#[derive(Debug, Clone)]
pub struct Editor {
    /// The text buffer.
    rope: Rope,
    /// Current cursor position.
    cursor: CursorPosition,
    /// Active selection (None when no selection).
    selection: Option<Selection>,
    /// Undo stack: (operation, cursor-before).
    undo_stack: Vec<(EditOp, CursorPosition)>,
    /// Redo stack: (operation, cursor-before).
    redo_stack: Vec<(EditOp, CursorPosition)>,
    /// Maximum undo history depth.
    max_history: usize,
    /// Current size of undo history in bytes.
    current_undo_size: usize,
    /// Maximum size of undo history in bytes (default 10MB).
    max_undo_size: usize,
}

impl Default for Editor {
    fn default() -> Self {
        Self::new()
    }
}

impl Editor {
    /// Create an empty editor.
    #[must_use]
    pub fn new() -> Self {
        Self {
            rope: Rope::new(),
            cursor: CursorPosition::default(),
            selection: None,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            max_history: 1000,
            current_undo_size: 0,
            max_undo_size: 10 * 1024 * 1024, // 10MB default
        }
    }

    /// Create an editor with initial text. Cursor starts at the end.
    #[must_use]
    pub fn with_text(text: &str) -> Self {
        let rope = Rope::from_text(text);
        let nav = CursorNavigator::new(&rope);
        let cursor = nav.document_end();
        Self {
            rope,
            cursor,
            selection: None,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            max_history: 1000,
            current_undo_size: 0,
            max_undo_size: 10 * 1024 * 1024,
        }
    }

    /// Set the maximum undo history depth.
    pub fn set_max_history(&mut self, max: usize) {
        self.max_history = max;
    }

    /// Set the maximum undo history size in bytes.
    pub fn set_max_undo_size(&mut self, bytes: usize) {
        self.max_undo_size = bytes;
        // Prune if now over limit
        while self.current_undo_size > self.max_undo_size && !self.undo_stack.is_empty() {
            let (op, _) = self.undo_stack.remove(0);
            self.current_undo_size -= op.byte_len();
        }
    }

    /// Get the full text content as a string.
    #[must_use]
    pub fn text(&self) -> String {
        self.rope.to_string()
    }

    /// Get a reference to the underlying rope.
    #[must_use]
    pub fn rope(&self) -> &Rope {
        &self.rope
    }

    /// Get the current cursor position.
    #[must_use]
    pub fn cursor(&self) -> CursorPosition {
        self.cursor
    }

    /// Set cursor position (will be clamped to valid bounds). Clears selection.
    pub fn set_cursor(&mut self, pos: CursorPosition) {
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.clamp(pos);
        self.selection = None;
    }

    /// Current selection, if any.
    #[must_use]
    pub fn selection(&self) -> Option<Selection> {
        self.selection
    }

    /// Whether undo is available.
    #[must_use]
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Whether redo is available.
    #[must_use]
    pub fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    /// Check if the editor is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rope.is_empty()
    }

    /// Number of lines in the buffer.
    #[must_use]
    pub fn line_count(&self) -> usize {
        self.rope.len_lines()
    }

    /// Get the text of a specific line (without trailing newline).
    #[must_use]
    pub fn line_text(&self, line: usize) -> Option<String> {
        self.rope.line(line).map(|cow| {
            let s = cow.as_ref();
            s.trim_end_matches('\n').trim_end_matches('\r').to_string()
        })
    }

    // ====================================================================
    // Insert operations
    // ====================================================================

    /// Insert a single character at the cursor position.
    pub fn insert_char(&mut self, ch: char) {
        let mut buf = [0u8; 4];
        let s = ch.encode_utf8(&mut buf);
        self.insert_text(s);
    }

    /// Insert text at the cursor position. Deletes selection first if active.
    ///
    /// Control characters (except newline and tab) are stripped to prevent
    /// terminal corruption.
    pub fn insert_text(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }

        // Sanitize input: allow \n and \t, strip other control chars
        let sanitized: String = text
            .chars()
            .filter(|&c| !c.is_control() || c == '\n' || c == '\t')
            .collect();

        if sanitized.is_empty() {
            return;
        }

        if let Some((start_byte, deleted)) = self.extract_selection() {
            let char_idx = self.rope.byte_to_char(start_byte);

            self.push_undo(EditOp::Replace {
                byte_offset: start_byte,
                deleted,
                inserted: sanitized.clone(),
            });

            self.rope.insert(char_idx, &sanitized);

            let new_byte_idx = start_byte + sanitized.len();
            let nav = CursorNavigator::new(&self.rope);
            self.cursor = nav.from_byte_index(new_byte_idx);
        } else {
            let nav = CursorNavigator::new(&self.rope);
            let byte_idx = nav.to_byte_index(self.cursor);
            let char_idx = self.rope.byte_to_char(byte_idx);

            self.push_undo(EditOp::Insert {
                byte_offset: byte_idx,
                text: sanitized.clone(),
            });

            self.rope.insert(char_idx, &sanitized);

            // Move cursor to end of inserted text
            let new_byte_idx = byte_idx + sanitized.len();
            let nav = CursorNavigator::new(&self.rope);
            self.cursor = nav.from_byte_index(new_byte_idx);
        }
    }

    /// Insert a newline at the cursor position.
    pub fn insert_newline(&mut self) {
        self.insert_text("\n");
    }

    // ====================================================================
    // Delete operations
    // ====================================================================

    /// Delete the character before the cursor (backspace). Deletes selection if active.
    ///
    /// Returns `true` if a character was deleted.
    pub fn delete_backward(&mut self) -> bool {
        if self.delete_selection_inner() {
            return true;
        }
        let nav = CursorNavigator::new(&self.rope);
        let old_pos = self.cursor;
        let new_pos = nav.move_left(old_pos);

        if new_pos == old_pos {
            return false; // At beginning, nothing to delete
        }

        let start_byte = nav.to_byte_index(new_pos);
        let end_byte = nav.to_byte_index(old_pos);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.push_undo(EditOp::Delete {
            byte_offset: start_byte,
            text: deleted,
        });

        self.rope.remove(start_char..end_char);

        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.from_byte_index(start_byte);
        true
    }

    /// Delete the character after the cursor (delete key). Deletes selection if active.
    ///
    /// Returns `true` if a character was deleted.
    pub fn delete_forward(&mut self) -> bool {
        if self.delete_selection_inner() {
            return true;
        }
        let nav = CursorNavigator::new(&self.rope);
        let old_pos = self.cursor;
        let next_pos = nav.move_right(old_pos);

        if next_pos == old_pos {
            return false; // At end, nothing to delete
        }

        let start_byte = nav.to_byte_index(old_pos);
        let end_byte = nav.to_byte_index(next_pos);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.push_undo(EditOp::Delete {
            byte_offset: start_byte,
            text: deleted,
        });

        self.rope.remove(start_char..end_char);

        // Cursor stays at same position, just re-clamp
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.clamp(self.cursor);
        true
    }

    /// Delete the word before the cursor (Ctrl+Backspace).
    ///
    /// Returns `true` if any text was deleted.
    pub fn delete_word_backward(&mut self) -> bool {
        if self.delete_selection_inner() {
            return true;
        }
        let nav = CursorNavigator::new(&self.rope);
        let old_pos = self.cursor;
        let word_start = nav.move_word_left(old_pos);

        if word_start == old_pos {
            return false;
        }

        let start_byte = nav.to_byte_index(word_start);
        let end_byte = nav.to_byte_index(old_pos);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.push_undo(EditOp::Delete {
            byte_offset: start_byte,
            text: deleted,
        });

        self.rope.remove(start_char..end_char);

        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.from_byte_index(start_byte);
        true
    }

    /// Delete the word after the cursor (Ctrl+Delete).
    ///
    /// Returns `true` if any text was deleted.
    pub fn delete_word_forward(&mut self) -> bool {
        if self.delete_selection_inner() {
            return true;
        }
        let nav = CursorNavigator::new(&self.rope);
        let old_pos = self.cursor;
        let word_end = nav.move_word_right(old_pos);

        if word_end == old_pos {
            return false;
        }

        let start_byte = nav.to_byte_index(old_pos);
        let end_byte = nav.to_byte_index(word_end);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.push_undo(EditOp::Delete {
            byte_offset: start_byte,
            text: deleted,
        });

        self.rope.remove(start_char..end_char);

        // Re-clamp cursor just in case, matching other forward deletions
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.clamp(self.cursor);
        true
    }

    /// Delete from cursor to end of line (Ctrl+K).
    ///
    /// Returns `true` if any text was deleted.
    pub fn delete_to_end_of_line(&mut self) -> bool {
        if self.delete_selection_inner() {
            return true;
        }
        let nav = CursorNavigator::new(&self.rope);
        let old_pos = self.cursor;
        let line_end = nav.line_end(old_pos);

        if line_end == old_pos {
            // At end of line: delete the newline to join lines
            return self.delete_forward();
        }

        let start_byte = nav.to_byte_index(old_pos);
        let end_byte = nav.to_byte_index(line_end);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.push_undo(EditOp::Delete {
            byte_offset: start_byte,
            text: deleted,
        });

        self.rope.remove(start_char..end_char);

        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.clamp(self.cursor);
        true
    }

    // ====================================================================
    // Undo / redo
    // ====================================================================

    /// Push an edit operation onto the undo stack.
    fn push_undo(&mut self, op: EditOp) {
        let op_len = op.byte_len();
        self.undo_stack.push((op, self.cursor));
        self.current_undo_size += op_len;

        // Prune by count
        if self.undo_stack.len() > self.max_history {
            if let Some((removed_op, _)) = self.undo_stack.first() {
                self.current_undo_size =
                    self.current_undo_size.saturating_sub(removed_op.byte_len());
            }
            self.undo_stack.remove(0);
        }

        // Prune by size
        while self.current_undo_size > self.max_undo_size && !self.undo_stack.is_empty() {
            let (removed_op, _) = self.undo_stack.remove(0);
            self.current_undo_size = self.current_undo_size.saturating_sub(removed_op.byte_len());
        }

        self.redo_stack.clear();
    }

    /// Undo the last edit operation.
    pub fn undo(&mut self) -> bool {
        let Some((op, cursor_before)) = self.undo_stack.pop() else {
            return false;
        };
        self.current_undo_size = self.current_undo_size.saturating_sub(op.byte_len());
        let inverse = op.inverse();
        self.apply_op(&inverse);
        self.redo_stack.push((inverse, self.cursor));
        self.cursor = cursor_before;
        self.selection = None;
        true
    }

    /// Redo the last undone operation.
    pub fn redo(&mut self) -> bool {
        let Some((op, cursor_before)) = self.redo_stack.pop() else {
            return false;
        };
        let inverse = op.inverse();
        self.apply_op(&inverse);

        let op_len = inverse.byte_len();
        self.undo_stack.push((inverse, self.cursor));
        self.current_undo_size += op_len;

        // Ensure size limit after redo (edge case where redo grows stack)
        while self.current_undo_size > self.max_undo_size && !self.undo_stack.is_empty() {
            let (removed_op, _) = self.undo_stack.remove(0);
            self.current_undo_size = self.current_undo_size.saturating_sub(removed_op.byte_len());
        }

        self.cursor = cursor_before;
        self.selection = None;
        // Move cursor to the correct position after redo
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.clamp(self.cursor);
        true
    }

    /// Apply an edit operation directly to the rope.
    fn apply_op(&mut self, op: &EditOp) {
        match op {
            EditOp::Insert { byte_offset, text } => {
                let char_idx = self.rope.byte_to_char(*byte_offset);
                self.rope.insert(char_idx, text);
            }
            EditOp::Delete { byte_offset, text } => {
                let start_char = self.rope.byte_to_char(*byte_offset);
                let end_char = self.rope.byte_to_char(*byte_offset + text.len());
                self.rope.remove(start_char..end_char);
            }
            EditOp::Replace {
                byte_offset,
                deleted,
                inserted,
            } => {
                let start_char = self.rope.byte_to_char(*byte_offset);
                let end_char = self.rope.byte_to_char(*byte_offset + deleted.len());
                self.rope.remove(start_char..end_char);
                self.rope.insert(start_char, inserted);
            }
        }
    }

    // ====================================================================
    // Selection helpers
    // ====================================================================

    /// Delete the current selection if active, returning the deleted text and byte offset.
    /// If nothing was deleted, returns `None`. Does NOT push to the undo stack.
    fn extract_selection(&mut self) -> Option<(usize, String)> {
        let sel = self.selection.take()?;
        if sel.is_empty() {
            return None;
        }
        let nav = CursorNavigator::new(&self.rope);
        let (start_byte, end_byte) = sel.byte_range(&nav);
        let start_char = self.rope.byte_to_char(start_byte);
        let end_char = self.rope.byte_to_char(end_byte);
        let deleted = self.rope.slice(start_char..end_char).into_owned();

        self.rope.remove(start_char..end_char);
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.from_byte_index(start_byte);

        Some((start_byte, deleted))
    }

    /// Delete the current selection if active. Returns true if something was deleted.
    fn delete_selection_inner(&mut self) -> bool {
        if let Some((start_byte, deleted)) = self.extract_selection() {
            self.push_undo(EditOp::Delete {
                byte_offset: start_byte,
                text: deleted,
            });
            true
        } else {
            false
        }
    }

    // ====================================================================
    // Cursor movement (clears selection)
    // ====================================================================

    /// Move cursor left by one grapheme.
    pub fn move_left(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_left(self.cursor);
    }

    /// Move cursor right by one grapheme.
    pub fn move_right(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_right(self.cursor);
    }

    /// Move cursor up one line.
    pub fn move_up(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_up(self.cursor);
    }

    /// Move cursor down one line.
    pub fn move_down(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_down(self.cursor);
    }

    /// Move cursor left by one word.
    pub fn move_word_left(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_word_left(self.cursor);
    }

    /// Move cursor right by one word.
    pub fn move_word_right(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.move_word_right(self.cursor);
    }

    /// Move cursor to start of line.
    pub fn move_to_line_start(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.line_start(self.cursor);
    }

    /// Move cursor to end of line.
    pub fn move_to_line_end(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.line_end(self.cursor);
    }

    /// Move cursor to start of document.
    pub fn move_to_document_start(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.document_start();
    }

    /// Move cursor to end of document.
    pub fn move_to_document_end(&mut self) {
        self.selection = None;
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.document_end();
    }

    // ====================================================================
    // Selection extension
    // ====================================================================

    /// Extend selection left by one grapheme.
    pub fn select_left(&mut self) {
        self.extend_selection(|nav, pos| nav.move_left(pos));
    }

    /// Extend selection right by one grapheme.
    pub fn select_right(&mut self) {
        self.extend_selection(|nav, pos| nav.move_right(pos));
    }

    /// Extend selection up one line.
    pub fn select_up(&mut self) {
        self.extend_selection(|nav, pos| nav.move_up(pos));
    }

    /// Extend selection down one line.
    pub fn select_down(&mut self) {
        self.extend_selection(|nav, pos| nav.move_down(pos));
    }

    /// Extend selection left by one word.
    pub fn select_word_left(&mut self) {
        self.extend_selection(|nav, pos| nav.move_word_left(pos));
    }

    /// Extend selection right by one word.
    pub fn select_word_right(&mut self) {
        self.extend_selection(|nav, pos| nav.move_word_right(pos));
    }

    /// Select all text.
    pub fn select_all(&mut self) {
        let nav = CursorNavigator::new(&self.rope);
        let start = nav.document_start();
        let end = nav.document_end();
        self.selection = Some(Selection {
            anchor: start,
            head: end,
        });
        self.cursor = end;
    }

    /// Clear current selection without moving cursor.
    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    /// Get selected text, if any non-empty selection exists.
    #[must_use]
    pub fn selected_text(&self) -> Option<String> {
        let sel = self.selection?;
        if sel.is_empty() {
            return None;
        }
        let nav = CursorNavigator::new(&self.rope);
        let (start, end) = sel.byte_range(&nav);
        let start_char = self.rope.byte_to_char(start);
        let end_char = self.rope.byte_to_char(end);
        Some(self.rope.slice(start_char..end_char).into_owned())
    }

    fn extend_selection(
        &mut self,
        f: impl FnOnce(&CursorNavigator<'_>, CursorPosition) -> CursorPosition,
    ) {
        let nav = CursorNavigator::new(&self.rope);
        let new_head = f(&nav, self.cursor);
        self.extend_selection_to(new_head);
    }

    /// Extend selection to a specific cursor position.
    pub fn extend_selection_to(&mut self, new_head: CursorPosition) {
        let anchor = match self.selection {
            Some(sel) => sel.anchor,
            None => self.cursor,
        };
        let nav = CursorNavigator::new(&self.rope);
        let new_head = nav.clamp(new_head);
        self.cursor = new_head;
        self.selection = Some(Selection {
            anchor,
            head: new_head,
        });
    }

    // ====================================================================
    // Content replacement
    // ====================================================================

    /// Replace all content and reset cursor to end. Clears undo history.
    pub fn set_text(&mut self, text: &str) {
        self.rope.replace(text);
        let nav = CursorNavigator::new(&self.rope);
        self.cursor = nav.document_end();
        self.selection = None;
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.current_undo_size = 0;
    }

    /// Clear all content and reset cursor. Clears undo history.
    pub fn clear(&mut self) {
        self.rope.clear();
        self.cursor = CursorPosition::default();
        self.selection = None;
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.current_undo_size = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_editor_is_empty() {
        let ed = Editor::new();
        assert!(ed.is_empty());
        assert_eq!(ed.text(), "");
        assert_eq!(ed.cursor(), CursorPosition::default());
    }

    #[test]
    fn with_text_cursor_at_end() {
        let ed = Editor::with_text("hello");
        assert_eq!(ed.text(), "hello");
        assert_eq!(ed.cursor().line, 0);
        assert_eq!(ed.cursor().grapheme, 5);
    }

    #[test]
    fn insert_char_at_end() {
        let mut ed = Editor::new();
        ed.insert_char('a');
        ed.insert_char('b');
        ed.insert_char('c');
        assert_eq!(ed.text(), "abc");
        assert_eq!(ed.cursor().grapheme, 3);
    }

    #[test]
    fn insert_text() {
        let mut ed = Editor::new();
        ed.insert_text("hello world");
        assert_eq!(ed.text(), "hello world");
    }

    #[test]
    fn insert_in_middle() {
        let mut ed = Editor::with_text("helo");
        // Move cursor to position 3 (after "hel")
        ed.set_cursor(CursorPosition::new(0, 3, 3));
        ed.insert_char('l');
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn insert_newline() {
        let mut ed = Editor::with_text("hello world");
        // Move cursor after "hello"
        ed.set_cursor(CursorPosition::new(0, 5, 5));
        ed.insert_newline();
        assert_eq!(ed.text(), "hello\n world");
        assert_eq!(ed.cursor().line, 1);
        assert_eq!(ed.line_count(), 2);
    }

    #[test]
    fn delete_backward() {
        let mut ed = Editor::with_text("hello");
        assert!(ed.delete_backward());
        assert_eq!(ed.text(), "hell");
    }

    #[test]
    fn delete_backward_at_beginning() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        assert!(!ed.delete_backward());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn delete_backward_joins_lines() {
        let mut ed = Editor::with_text("hello\nworld");
        // Cursor at start of "world"
        ed.set_cursor(CursorPosition::new(1, 0, 0));
        assert!(ed.delete_backward());
        assert_eq!(ed.text(), "helloworld");
        assert_eq!(ed.line_count(), 1);
    }

    #[test]
    fn delete_forward() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        assert!(ed.delete_forward());
        assert_eq!(ed.text(), "ello");
    }

    #[test]
    fn delete_forward_at_end() {
        let mut ed = Editor::with_text("hello");
        assert!(!ed.delete_forward());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn delete_forward_joins_lines() {
        let mut ed = Editor::with_text("hello\nworld");
        // Cursor at end of "hello"
        ed.set_cursor(CursorPosition::new(0, 5, 5));
        assert!(ed.delete_forward());
        assert_eq!(ed.text(), "helloworld");
    }

    #[test]
    fn move_left_right() {
        let mut ed = Editor::with_text("abc");
        assert_eq!(ed.cursor().grapheme, 3);

        ed.move_left();
        assert_eq!(ed.cursor().grapheme, 2);

        ed.move_left();
        assert_eq!(ed.cursor().grapheme, 1);

        ed.move_right();
        assert_eq!(ed.cursor().grapheme, 2);
    }

    #[test]
    fn move_left_at_start_is_noop() {
        let mut ed = Editor::with_text("abc");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        ed.move_left();
        assert_eq!(ed.cursor().grapheme, 0);
        assert_eq!(ed.cursor().line, 0);
    }

    #[test]
    fn move_right_at_end_is_noop() {
        let mut ed = Editor::with_text("abc");
        ed.move_right();
        assert_eq!(ed.cursor().grapheme, 3);
    }

    #[test]
    fn move_up_down() {
        let mut ed = Editor::with_text("line 1\nline 2\nline 3");
        // Cursor at end of "line 3"
        assert_eq!(ed.cursor().line, 2);

        ed.move_up();
        assert_eq!(ed.cursor().line, 1);

        ed.move_up();
        assert_eq!(ed.cursor().line, 0);

        // At top, stays
        ed.move_up();
        assert_eq!(ed.cursor().line, 0);

        ed.move_down();
        assert_eq!(ed.cursor().line, 1);
    }

    #[test]
    fn move_to_line_start_end() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 5, 5));

        ed.move_to_line_start();
        assert_eq!(ed.cursor().grapheme, 0);

        ed.move_to_line_end();
        assert_eq!(ed.cursor().grapheme, 11);
    }

    #[test]
    fn move_to_document_start_end() {
        let mut ed = Editor::with_text("line 1\nline 2\nline 3");

        ed.move_to_document_start();
        assert_eq!(ed.cursor().line, 0);
        assert_eq!(ed.cursor().grapheme, 0);

        ed.move_to_document_end();
        assert_eq!(ed.cursor().line, 2);
    }

    #[test]
    fn move_word_left_right() {
        let mut ed = Editor::with_text("hello world foo");
        // Cursor at end (grapheme 15)
        let start = ed.cursor().grapheme;

        ed.move_word_left();
        let after_first = ed.cursor().grapheme;
        assert!(after_first < start, "word_left should move cursor left");

        ed.move_word_left();
        let after_second = ed.cursor().grapheme;
        assert!(
            after_second < after_first,
            "second word_left should move further left"
        );

        ed.move_word_right();
        let after_right = ed.cursor().grapheme;
        assert!(
            after_right > after_second,
            "word_right should move cursor right"
        );
    }

    #[test]
    fn delete_word_backward() {
        let mut ed = Editor::with_text("hello world");
        assert!(ed.delete_word_backward());
        assert_eq!(ed.text(), "hello ");
    }

    #[test]
    fn delete_word_forward() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        assert!(ed.delete_word_forward());
        assert_eq!(ed.text(), "world");
    }

    #[test]
    fn delete_to_end_of_line() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 5, 5));
        assert!(ed.delete_to_end_of_line());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn delete_to_end_joins_when_at_line_end() {
        let mut ed = Editor::with_text("hello\nworld");
        ed.set_cursor(CursorPosition::new(0, 5, 5));
        assert!(ed.delete_to_end_of_line());
        assert_eq!(ed.text(), "helloworld");
    }

    #[test]
    fn set_text_replaces_content() {
        let mut ed = Editor::with_text("old");
        ed.set_text("new content");
        assert_eq!(ed.text(), "new content");
    }

    #[test]
    fn clear_resets() {
        let mut ed = Editor::with_text("hello");
        ed.clear();
        assert!(ed.is_empty());
        assert_eq!(ed.cursor(), CursorPosition::default());
    }

    #[test]
    fn line_text_works() {
        let ed = Editor::with_text("line 0\nline 1\nline 2");
        assert_eq!(ed.line_text(0), Some("line 0".to_string()));
        assert_eq!(ed.line_text(1), Some("line 1".to_string()));
        assert_eq!(ed.line_text(2), Some("line 2".to_string()));
        assert_eq!(ed.line_text(3), None);
    }

    #[test]
    fn cursor_stays_in_bounds_after_delete() {
        let mut ed = Editor::with_text("a");
        assert!(ed.delete_backward());
        assert_eq!(ed.text(), "");
        assert_eq!(ed.cursor(), CursorPosition::default());

        // Further deletes are no-ops
        assert!(!ed.delete_backward());
        assert!(!ed.delete_forward());
    }

    #[test]
    fn multiline_editing() {
        let mut ed = Editor::new();
        ed.insert_text("first");
        ed.insert_newline();
        ed.insert_text("second");
        ed.insert_newline();
        ed.insert_text("third");

        assert_eq!(ed.text(), "first\nsecond\nthird");
        assert_eq!(ed.line_count(), 3);
        assert_eq!(ed.cursor().line, 2);

        // Move up and insert at start of middle line
        ed.move_up();
        ed.move_to_line_start();
        ed.insert_text(">> ");
        assert_eq!(ed.line_text(1), Some(">> second".to_string()));
    }

    // ================================================================
    // Undo / Redo tests
    // ================================================================

    #[test]
    fn undo_insert() {
        let mut ed = Editor::new();
        ed.insert_text("hello");
        assert!(ed.can_undo());
        assert!(ed.undo());
        assert_eq!(ed.text(), "");
    }

    #[test]
    fn undo_delete() {
        let mut ed = Editor::with_text("hello");
        ed.delete_backward();
        assert_eq!(ed.text(), "hell");
        assert!(ed.undo());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn redo_after_undo() {
        let mut ed = Editor::new();
        ed.insert_text("abc");
        ed.undo();
        assert_eq!(ed.text(), "");
        assert!(ed.can_redo());
        assert!(ed.redo());
        assert_eq!(ed.text(), "abc");
    }

    #[test]
    fn redo_cleared_on_new_edit() {
        let mut ed = Editor::new();
        ed.insert_text("abc");
        ed.undo();
        ed.insert_text("xyz");
        assert!(!ed.can_redo());
    }

    #[test]
    fn multiple_undo_redo() {
        let mut ed = Editor::new();
        ed.insert_text("a");
        ed.insert_text("b");
        ed.insert_text("c");
        assert_eq!(ed.text(), "abc");

        ed.undo();
        assert_eq!(ed.text(), "ab");
        ed.undo();
        assert_eq!(ed.text(), "a");
        ed.undo();
        assert_eq!(ed.text(), "");

        ed.redo();
        assert_eq!(ed.text(), "a");
        ed.redo();
        assert_eq!(ed.text(), "ab");
    }

    #[test]
    fn undo_restores_cursor() {
        let mut ed = Editor::new();
        let before = ed.cursor();
        ed.insert_text("x");
        ed.undo();
        assert_eq!(ed.cursor(), before);
    }

    #[test]
    fn max_history_respected() {
        let mut ed = Editor::new();
        ed.set_max_history(3);
        for c in ['a', 'b', 'c', 'd', 'e'] {
            ed.insert_text(&c.to_string());
        }
        assert!(ed.undo());
        assert!(ed.undo());
        assert!(ed.undo());
        assert!(!ed.undo());
        assert_eq!(ed.text(), "ab");
    }

    #[test]
    fn set_text_clears_undo() {
        let mut ed = Editor::new();
        ed.insert_text("abc");
        ed.set_text("new");
        assert!(!ed.can_undo());
        assert!(!ed.can_redo());
    }

    #[test]
    fn clear_clears_undo() {
        let mut ed = Editor::new();
        ed.insert_text("abc");
        ed.clear();
        assert!(!ed.can_undo());
    }

    // ================================================================
    // Selection tests
    // ================================================================

    #[test]
    fn select_right_creates_selection() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        ed.select_right();
        ed.select_right();
        ed.select_right();
        let sel = ed.selection().unwrap();
        assert_eq!(sel.anchor, CursorPosition::new(0, 0, 0));
        assert_eq!(sel.head.grapheme, 3);
        assert_eq!(ed.selected_text(), Some("hel".to_string()));
    }

    #[test]
    fn select_all_selects_everything() {
        let mut ed = Editor::with_text("abc\ndef");
        ed.select_all();
        assert_eq!(ed.selected_text(), Some("abc\ndef".to_string()));
    }

    #[test]
    fn insert_replaces_selection() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        for _ in 0..5 {
            ed.select_right();
        }
        ed.insert_text("goodbye");
        assert_eq!(ed.text(), "goodbye world");
        assert!(ed.selection().is_none());
    }

    #[test]
    fn delete_backward_removes_selection() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        for _ in 0..5 {
            ed.select_right();
        }
        ed.delete_backward();
        assert_eq!(ed.text(), " world");
    }

    #[test]
    fn movement_clears_selection() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        ed.select_right();
        ed.select_right();
        assert!(ed.selection().is_some());
        ed.move_right();
        assert!(ed.selection().is_none());
    }

    #[test]
    fn undo_selection_delete() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        for _ in 0..5 {
            ed.select_right();
        }
        ed.delete_backward();
        assert_eq!(ed.text(), " world");
        ed.undo();
        assert_eq!(ed.text(), "hello world");
    }

    // ================================================================
    // Edge case tests
    // ================================================================

    #[test]
    fn insert_empty_text_is_noop() {
        let mut ed = Editor::with_text("hello");
        let before = ed.text();
        ed.insert_text("");
        assert_eq!(ed.text(), before);
        // No undo entry for empty insert
        assert!(!ed.can_undo());
    }

    #[test]
    fn unicode_emoji_handling() {
        let mut ed = Editor::new();
        ed.insert_text("hello 🎉 world");
        assert_eq!(ed.text(), "hello 🎉 world");
        // Emoji counts as one grapheme
        ed.move_left(); // d
        ed.move_left(); // l
        ed.move_left(); // r
        ed.move_left(); // o
        ed.move_left(); // w
        ed.move_left(); // space
        ed.move_left(); // emoji (single grapheme move)
        ed.delete_backward(); // deletes space before emoji
        assert_eq!(ed.text(), "hello🎉 world");
    }

    #[test]
    fn unicode_combining_character() {
        let mut ed = Editor::new();
        // é as e + combining acute accent (decomposed form)
        ed.insert_text("caf\u{0065}\u{0301}");
        // Text stays in decomposed form (e + combining accent)
        assert_eq!(ed.text(), "caf\u{0065}\u{0301}");
        // The combining sequence is one grapheme, so delete_backward removes both
        ed.delete_backward();
        assert_eq!(ed.text(), "caf");
    }

    #[test]
    fn unicode_zwj_sequence() {
        let mut ed = Editor::new();
        // Woman astronaut: woman + ZWJ + rocket
        ed.insert_text("👩\u{200D}🚀");
        let text = ed.text();
        assert!(text.contains("👩"));
        // Move left should treat ZWJ sequence as one grapheme
        ed.move_left();
        // We're now before the ZWJ sequence
        ed.insert_char('x');
        assert!(ed.text().starts_with('x'));
    }

    #[test]
    fn unicode_cjk_wide_chars() {
        let mut ed = Editor::new();
        ed.insert_text("世界");
        assert_eq!(ed.text(), "世界");
        ed.move_left();
        assert_eq!(ed.cursor().grapheme, 1);
        ed.move_left();
        assert_eq!(ed.cursor().grapheme, 0);
    }

    #[test]
    fn crlf_handling() {
        let ed = Editor::with_text("hello\r\nworld");
        assert_eq!(ed.line_count(), 2);
        assert_eq!(ed.line_text(0), Some("hello".to_string()));
        assert_eq!(ed.line_text(1), Some("world".to_string()));
    }

    #[test]
    fn mixed_newlines() {
        let ed = Editor::with_text("line1\nline2\r\nline3");
        assert_eq!(ed.line_count(), 3);
        assert_eq!(ed.line_text(0), Some("line1".to_string()));
        assert_eq!(ed.line_text(1), Some("line2".to_string()));
        assert_eq!(ed.line_text(2), Some("line3".to_string()));
    }

    #[test]
    fn trailing_newline() {
        let ed = Editor::with_text("hello\n");
        assert_eq!(ed.line_count(), 2);
        assert_eq!(ed.line_text(0), Some("hello".to_string()));
        assert_eq!(ed.line_text(1), Some(String::new()));
    }

    #[test]
    fn only_newlines() {
        let ed = Editor::with_text("\n\n\n");
        assert_eq!(ed.line_count(), 4);
        for i in 0..4 {
            assert_eq!(ed.line_text(i), Some(String::new()));
        }
    }

    #[test]
    fn delete_word_backward_at_start_is_noop() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        assert!(!ed.delete_word_backward());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn delete_word_backward_multiple_spaces() {
        let mut ed = Editor::with_text("hello    world");
        // Cursor at end
        assert!(ed.delete_word_backward());
        // Should delete "world"
        let remaining = ed.text();
        assert!(remaining.starts_with("hello"));
    }

    #[test]
    fn delete_to_end_at_document_end() {
        let mut ed = Editor::with_text("hello");
        // Cursor already at end from with_text
        assert!(!ed.delete_to_end_of_line());
        assert_eq!(ed.text(), "hello");
    }

    #[test]
    fn select_word_operations() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        // move_word_right now skips the word and trailing whitespace
        ed.select_word_right();
        assert_eq!(ed.selected_text(), Some("hello ".to_string()));
        ed.clear_selection();
        ed.move_to_line_end();
        ed.select_word_left();
        assert_eq!(ed.selected_text(), Some("world".to_string()));
    }

    #[test]
    fn select_up_down() {
        let mut ed = Editor::with_text("line1\nline2\nline3");
        ed.set_cursor(CursorPosition::new(1, 3, 3));
        ed.select_up();
        let sel = ed.selection().expect("should have selection");
        assert_eq!(sel.anchor.line, 1);
        assert_eq!(sel.head.line, 0);
        ed.select_down();
        ed.select_down();
        let sel = ed.selection().expect("should have selection");
        assert_eq!(sel.head.line, 2);
    }

    #[test]
    fn selection_extending_preserves_anchor() {
        let mut ed = Editor::with_text("abcdef");
        ed.set_cursor(CursorPosition::new(0, 2, 2));
        ed.select_right();
        ed.select_right();
        ed.select_right();
        let sel = ed.selection().unwrap();
        assert_eq!(sel.anchor.grapheme, 2);
        assert_eq!(sel.head.grapheme, 5);
        // Now extend left
        ed.select_left();
        let sel = ed.selection().unwrap();
        assert_eq!(sel.anchor.grapheme, 2);
        assert_eq!(sel.head.grapheme, 4);
    }

    #[test]
    fn empty_selection_returns_none() {
        let mut ed = Editor::with_text("hello");
        ed.set_cursor(CursorPosition::new(0, 2, 2));
        // Create selection with same anchor and head
        ed.select_right();
        ed.select_left();
        // Now anchor == head
        let sel = ed.selection().unwrap();
        assert!(sel.is_empty());
        assert_eq!(ed.selected_text(), None);
    }

    #[test]
    fn cursor_clamp_after_set_text() {
        let mut ed = Editor::with_text("very long text here");
        ed.set_text("hi");
        // Cursor should be at end of "hi"
        assert_eq!(ed.cursor().line, 0);
        assert_eq!(ed.cursor().grapheme, 2);
    }

    #[test]
    fn undo_redo_with_selection() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 6, 6));
        // Select "world"
        for _ in 0..5 {
            ed.select_right();
        }
        ed.insert_text("universe");
        assert_eq!(ed.text(), "hello universe");

        // Atomic Replace: 1 undo restores the deleted text and removes inserted
        ed.undo();
        assert_eq!(ed.text(), "hello world");

        // 1 redo reapplies the edit
        ed.redo();
        assert_eq!(ed.text(), "hello universe");
    }

    #[test]
    fn rapid_insert_delete_cycle() {
        let mut ed = Editor::new();
        for i in 0..100 {
            ed.insert_char(char::from_u32('a' as u32 + (i % 26)).unwrap());
            if i % 3 == 0 {
                ed.delete_backward();
            }
        }
        // Should not panic, cursor should be valid
        let cursor = ed.cursor();
        assert!(cursor.line == 0);
        assert!(cursor.grapheme <= ed.text().chars().count());
    }

    #[test]
    fn multiline_select_all_and_replace() {
        let mut ed = Editor::with_text("line1\nline2\nline3");
        ed.select_all();
        ed.insert_text("replaced");
        assert_eq!(ed.text(), "replaced");
        assert_eq!(ed.line_count(), 1);
    }

    #[test]
    fn delete_forward_with_selection() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 0, 0));
        for _ in 0..5 {
            ed.select_right();
        }
        // delete_forward with selection should delete selection, not char after
        ed.delete_forward();
        assert_eq!(ed.text(), " world");
    }

    #[test]
    fn delete_word_backward_with_selection() {
        let mut ed = Editor::with_text("hello world");
        ed.set_cursor(CursorPosition::new(0, 6, 6));
        for _ in 0..5 {
            ed.select_right();
        }
        // Should delete selection, not word
        ed.delete_word_backward();
        assert_eq!(ed.text(), "hello ");
    }

    #[test]
    fn default_impl() {
        let ed = Editor::default();
        assert!(ed.is_empty());
        assert_eq!(ed.cursor(), CursorPosition::default());
    }

    #[test]
    fn line_text_out_of_bounds() {
        let ed = Editor::with_text("hello");
        assert_eq!(ed.line_text(0), Some("hello".to_string()));
        assert_eq!(ed.line_text(1), None);
        assert_eq!(ed.line_text(100), None);
    }

    #[test]
    fn rope_accessor() {
        let ed = Editor::with_text("test");
        let rope = ed.rope();
        assert_eq!(rope.len_bytes(), 4);
    }

    #[test]
    fn insert_text_sanitizes_controls() {
        let mut ed = Editor::new();
        // Insert text with ESC (\x1b) and BEL (\x07) mixed with safe chars
        ed.insert_text("hello\x1bworld\x07\n\t!");
        // Should contain "hello", "world", "\n", "\t", "!" but NO control chars
        assert_eq!(ed.text(), "helloworld\n\t!");
    }

    #[test]
    fn cursor_position_after_multiline_insert() {
        let mut ed = Editor::new();
        ed.insert_text("hello\nworld\nfoo");
        assert_eq!(ed.cursor().line, 2);
        assert_eq!(ed.line_count(), 3);
    }

    #[test]
    fn delete_backward_across_lines() {
        let mut ed = Editor::with_text("abc\ndef");
        ed.set_cursor(CursorPosition::new(1, 0, 0));
        ed.delete_backward();
        assert_eq!(ed.text(), "abcdef");
        assert_eq!(ed.cursor().line, 0);
        assert_eq!(ed.cursor().grapheme, 3);
    }

    #[test]
    fn very_long_line() {
        let long_text: String = "a".repeat(10000);
        let mut ed = Editor::with_text(&long_text);
        assert_eq!(ed.text().len(), 10000);
        ed.move_to_line_start();
        assert_eq!(ed.cursor().grapheme, 0);
        ed.move_to_line_end();
        assert_eq!(ed.cursor().grapheme, 10000);
    }

    #[test]
    fn many_lines() {
        let text: String = (0..1000)
            .map(|i| format!("line{i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let ed = Editor::with_text(&text);
        assert_eq!(ed.line_count(), 1000);
        assert_eq!(ed.line_text(999), Some("line999".to_string()));
    }

    #[test]
    fn selection_byte_range_order() {
        use crate::cursor::CursorNavigator;

        let mut ed = Editor::with_text("hello world");
        // Select backwards (anchor after head)
        ed.set_cursor(CursorPosition::new(0, 8, 8));
        ed.select_left();
        ed.select_left();
        ed.select_left();

        let sel = ed.selection().unwrap();
        let nav = CursorNavigator::new(ed.rope());
        let (start, end) = sel.byte_range(&nav);
        // byte_range should always have start <= end
        assert!(start <= end);
        assert_eq!(end - start, 3);
    }
}

// ================================================================
// Property-based tests
// ================================================================

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    // Strategy for generating valid text content (ASCII + some unicode)
    fn text_strategy() -> impl Strategy<Value = String> {
        prop::string::string_regex("[a-zA-Z0-9 \n]{0,100}")
            .unwrap()
            .prop_filter("non-empty or empty", |_| true)
    }

    // Strategy for text with unicode
    fn unicode_text_strategy() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop_oneof![
                Just("a".to_string()),
                Just(" ".to_string()),
                Just("\n".to_string()),
                Just("é".to_string()),
                Just("世".to_string()),
                Just("🎉".to_string()),
            ],
            0..50,
        )
        .prop_map(|v| v.join(""))
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        // Property: Cursor is always within valid bounds after any operation
        #[test]
        fn cursor_always_in_bounds(text in text_strategy()) {
            let mut ed = Editor::with_text(&text);

            // After creation
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || (c.line == 0 && ed.line_count() == 1));

            // After various movements
            ed.move_left();
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || (c.line == 0 && ed.line_count() == 1));

            ed.move_right();
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || (c.line == 0 && ed.line_count() == 1));

            ed.move_up();
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || (c.line == 0 && ed.line_count() == 1));

            ed.move_down();
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || (c.line == 0 && ed.line_count() == 1));

            ed.move_to_line_start();
            let c = ed.cursor();
            prop_assert_eq!(c.grapheme, 0);

            ed.move_to_document_start();
            let c = ed.cursor();
            prop_assert_eq!(c.line, 0);
            prop_assert_eq!(c.grapheme, 0);
        }

        // Property: Undo after insert restores original text
        #[test]
        fn undo_insert_restores_text(base in text_strategy(), insert in "[a-z]{1,20}") {
            let mut ed = Editor::with_text(&base);
            let original = ed.text();
            ed.insert_text(&insert);
            prop_assert!(ed.can_undo());
            ed.undo();
            prop_assert_eq!(ed.text(), original);
        }

        // Property: Undo after delete restores original text
        #[test]
        fn undo_delete_restores_text(text in "[a-zA-Z]{5,50}") {
            let mut ed = Editor::with_text(&text);
            let original = ed.text();
            if ed.delete_backward() {
                prop_assert!(ed.can_undo());
                ed.undo();
                prop_assert_eq!(ed.text(), original);
            }
        }

        // Property: Redo after undo restores the edit
        #[test]
        fn redo_after_undo_restores(text in text_strategy(), insert in "[a-z]{1,10}") {
            let mut ed = Editor::with_text(&text);
            ed.insert_text(&insert);
            let after_insert = ed.text();
            ed.undo();
            prop_assert!(ed.can_redo());
            ed.redo();
            prop_assert_eq!(ed.text(), after_insert);
        }

        // Property: select_all + delete = empty
        #[test]
        fn select_all_delete_empties(text in text_strategy()) {
            let mut ed = Editor::with_text(&text);
            ed.select_all();
            ed.delete_backward();
            prop_assert!(ed.is_empty());
        }

        // Property: Line count equals newline count + 1
        #[test]
        fn line_count_matches_newlines(text in text_strategy()) {
            let ed = Editor::with_text(&text);
            let newline_count = text.matches('\n').count();
            // Line count is at least 1, and each \n adds a line
            prop_assert_eq!(ed.line_count(), newline_count + 1);
        }

        // Property: text() roundtrip through set_text
        #[test]
        fn set_text_roundtrip(text in text_strategy()) {
            let mut ed = Editor::new();
            ed.set_text(&text);
            prop_assert_eq!(ed.text(), text);
        }

        // Property: Cursor stays in bounds after unicode operations
        #[test]
        fn unicode_cursor_bounds(text in unicode_text_strategy()) {
            let mut ed = Editor::with_text(&text);

            // Move around
            for _ in 0..10 {
                ed.move_left();
            }
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || ed.line_count() == 1);

            for _ in 0..10 {
                ed.move_right();
            }
            let c = ed.cursor();
            prop_assert!(c.line < ed.line_count() || ed.line_count() == 1);
        }

        // Property: insert_char then delete_backward = original (when no prior content at cursor)
        #[test]
        fn insert_delete_roundtrip(ch in prop::char::any().prop_filter("printable", |c| !c.is_control())) {
            let mut ed = Editor::new();
            ed.insert_char(ch);
            ed.delete_backward();
            prop_assert!(ed.is_empty());
        }

        // Property: Multiple undos don't panic and eventually can't undo
        #[test]
        fn multiple_undos_safe(ops in prop::collection::vec(0..3u8, 0..20)) {
            let mut ed = Editor::new();
            for op in ops {
                match op {
                    0 => { ed.insert_char('x'); }
                    1 => { ed.delete_backward(); }
                    _ => { ed.undo(); }
                }
            }
            // Should be able to undo until stack is empty
            while ed.can_undo() {
                prop_assert!(ed.undo());
            }
            prop_assert!(!ed.can_undo());
        }

        // Property: Selection byte_range always has start <= end
        #[test]
        fn selection_range_ordered(text in "[a-zA-Z]{10,50}") {
            use crate::cursor::CursorNavigator;

            let mut ed = Editor::with_text(&text);
            ed.set_cursor(CursorPosition::new(0, 5, 5));

            // Select in various directions
            ed.select_left();
            ed.select_left();

            if let Some(sel) = ed.selection() {
                let nav = CursorNavigator::new(ed.rope());
                let (start, end) = sel.byte_range(&nav);
                prop_assert!(start <= end);
            }

            ed.select_right();
            ed.select_right();
            ed.select_right();
            ed.select_right();

            if let Some(sel) = ed.selection() {
                let nav = CursorNavigator::new(ed.rope());
                let (start, end) = sel.byte_range(&nav);
                prop_assert!(start <= end);
            }
        }

        // Property: Word movement always makes progress or stays at boundary
        #[test]
        fn word_movement_progress(text in "[a-zA-Z ]{5,50}") {
            let mut ed = Editor::with_text(&text);
            ed.set_cursor(CursorPosition::new(0, 0, 0));

            let start = ed.cursor();
            ed.move_word_right();
            let after = ed.cursor();
            // Either made progress or was already at end
            prop_assert!(after.grapheme >= start.grapheme);

            ed.move_to_line_end();
            let end_pos = ed.cursor();
            ed.move_word_left();
            let after_left = ed.cursor();
            // Either made progress or was already at start
            prop_assert!(after_left.grapheme <= end_pos.grapheme);
        }

        // Property: Document start/end are at expected positions
        #[test]
        fn document_bounds(text in text_strategy()) {
            let mut ed = Editor::with_text(&text);

            ed.move_to_document_start();
            prop_assert_eq!(ed.cursor().line, 0);
            prop_assert_eq!(ed.cursor().grapheme, 0);

            ed.move_to_document_end();
            let c = ed.cursor();
            let last_line = ed.line_count().saturating_sub(1);
            prop_assert_eq!(c.line, last_line);
        }
    }
}