opentui_rust 0.2.1

High-performance terminal UI rendering engine with alpha blending and diffed buffers
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
//! Editable text buffer with cursor and undo/redo.
//!
//! This module provides [`EditBuffer`], which wraps a [`TextBuffer`] with
//! editing capabilities including cursor movement, text insertion/deletion,
//! and undo/redo history.
//!
//! # Examples
//!
//! ```
//! use opentui_rust::EditBuffer;
//!
//! let mut buf = EditBuffer::with_text("Hello World");
//!
//! // Move cursor to end of line and delete backward
//! buf.move_to_line_end();
//! buf.delete_backward(); // Removes 'd'
//! buf.commit(); // Create undo checkpoint
//! assert_eq!(buf.text(), "Hello Worl");
//!
//! // Undo restores deleted text
//! buf.undo();
//! assert_eq!(buf.text(), "Hello World");
//! ```

// Iterator patterns are clearer in their current form
#![allow(clippy::while_let_on_iterator)]
// if-let-else is clearer than map_or for complex logic
#![allow(clippy::option_if_let_else)]

use crate::highlight::HighlightedBuffer;
use crate::text::TextBuffer;

/// Cursor position in the buffer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Cursor {
    /// Character offset in the buffer.
    pub offset: usize,
    /// Line number (0-indexed).
    pub row: usize,
    /// Column number (0-indexed).
    pub col: usize,
}

impl Cursor {
    /// Create a new cursor at position.
    #[must_use]
    pub fn new(offset: usize, row: usize, col: usize) -> Self {
        Self { offset, row, col }
    }

    /// Create a cursor at the beginning.
    #[must_use]
    pub fn start() -> Self {
        Self::default()
    }
}

/// Cursor position info with offset and visual column.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CursorPosition {
    pub row: usize,
    pub col: usize,
    pub offset: usize,
}

/// An edit operation for undo/redo.
#[derive(Clone, Debug)]
enum EditOp {
    Insert { offset: usize, text: String },
    Delete { offset: usize, text: String },
}

impl EditOp {
    fn invert(&self) -> Self {
        match self {
            Self::Insert { offset, text } => Self::Delete {
                offset: *offset,
                text: text.clone(),
            },
            Self::Delete { offset, text } => Self::Insert {
                offset: *offset,
                text: text.clone(),
            },
        }
    }
}

/// Default maximum number of undo groups to retain.
const DEFAULT_MAX_HISTORY_DEPTH: usize = 1000;

/// Edit history for undo/redo with bounded memory usage.
#[derive(Clone, Debug)]
struct History {
    undo_stack: Vec<Vec<EditOp>>,
    redo_stack: Vec<Vec<EditOp>>,
    current_group: Vec<EditOp>,
    /// Maximum number of undo groups to retain. Oldest entries are dropped when exceeded.
    max_depth: usize,
}

impl Default for History {
    fn default() -> Self {
        Self {
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            current_group: Vec::new(),
            max_depth: DEFAULT_MAX_HISTORY_DEPTH,
        }
    }
}

impl History {
    fn new() -> Self {
        Self::default()
    }

    /// Create a history with a custom maximum depth.
    fn with_max_depth(max_depth: usize) -> Self {
        Self {
            max_depth,
            ..Self::default()
        }
    }

    fn push(&mut self, op: EditOp) {
        self.current_group.push(op);
        self.redo_stack.clear();
    }

    fn commit(&mut self) {
        if !self.current_group.is_empty() {
            self.undo_stack
                .push(std::mem::take(&mut self.current_group));
            // Enforce depth limit by dropping oldest entries
            if self.undo_stack.len() > self.max_depth {
                let excess = self.undo_stack.len() - self.max_depth;
                self.undo_stack.drain(..excess);
            }
        }
    }

    fn pop_undo(&mut self) -> Option<Vec<EditOp>> {
        self.commit();
        self.undo_stack.pop()
    }

    fn push_redo(&mut self, ops: Vec<EditOp>) {
        self.redo_stack.push(ops);
    }

    fn pop_redo(&mut self) -> Option<Vec<EditOp>> {
        self.redo_stack.pop()
    }

    fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty() || !self.current_group.is_empty()
    }

    fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    fn clear(&mut self) {
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.current_group.clear();
    }
}

/// Text buffer with editing operations, cursor, and undo/redo.
///
/// `EditBuffer` is the primary type for text editing. It tracks cursor
/// position, maintains undo/redo history, and provides operations for:
///
/// - **Cursor movement**: Lines, words, characters, document bounds
/// - **Text editing**: Insert, delete, backspace with cursor tracking
/// - **Line operations**: Duplicate, move, delete lines
/// - **History**: Grouped undo/redo with configurable depth limit
///
/// # History Management
///
/// Edit operations are grouped automatically. Call [`commit`](Self::commit)
/// to force a group boundary (e.g., after a pause in typing). The history depth
/// is bounded (default 1000 groups) to limit memory usage.
#[derive(Default)]
pub struct EditBuffer {
    buffer: HighlightedBuffer,
    cursor: Cursor,
    history: History,
}

impl EditBuffer {
    /// Create a new empty edit buffer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an edit buffer with initial text.
    #[must_use]
    pub fn with_text(text: &str) -> Self {
        Self {
            buffer: HighlightedBuffer::new(TextBuffer::with_text(text)),
            cursor: Cursor::start(),
            history: History::new(),
        }
    }

    /// Create an edit buffer with a custom maximum undo history depth.
    ///
    /// The default is 1000 undo groups. Set a lower value for memory-constrained
    /// environments or a higher value for documents that need extensive undo history.
    #[must_use]
    pub fn with_max_history_depth(max_depth: usize) -> Self {
        Self {
            buffer: HighlightedBuffer::new(TextBuffer::new()),
            cursor: Cursor::start(),
            history: History::with_max_depth(max_depth),
        }
    }

    /// Set the maximum undo history depth.
    ///
    /// If the current history exceeds the new depth, oldest entries will be
    /// pruned on the next commit.
    pub fn set_max_history_depth(&mut self, max_depth: usize) {
        self.history.max_depth = max_depth;
    }

    /// Get the current maximum undo history depth.
    #[must_use]
    pub fn max_history_depth(&self) -> usize {
        self.history.max_depth
    }

    /// Get the underlying text buffer.
    #[must_use]
    pub fn buffer(&self) -> &TextBuffer {
        self.buffer.buffer()
    }

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

    /// Replace the entire text, resetting cursor and history.
    pub fn set_text(&mut self, text: &str) {
        self.buffer.set_text(text);
        self.cursor = Cursor::start();
        self.history.clear();
        self.update_cursor_position();
    }

    /// Get mutable access to the text buffer.
    pub fn buffer_mut(&mut self) -> &mut TextBuffer {
        self.buffer.buffer_mut()
    }

    /// Get the highlighted buffer.
    #[must_use]
    pub fn highlighted_buffer(&self) -> &HighlightedBuffer {
        &self.buffer
    }

    /// Get mutable access to the highlighted buffer.
    pub fn highlighted_buffer_mut(&mut self) -> &mut HighlightedBuffer {
        &mut self.buffer
    }

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

    /// Set the cursor position.
    pub fn set_cursor(&mut self, cursor: Cursor) {
        self.cursor = cursor;
        self.clamp_cursor();
    }

    /// Set the cursor by character offset.
    pub fn set_cursor_by_offset(&mut self, offset: usize) {
        self.cursor.offset = offset.min(self.buffer.len_chars());
        self.update_cursor_position();
    }

    /// Get cursor position info.
    #[must_use]
    pub fn get_cursor_position(&self) -> CursorPosition {
        CursorPosition {
            row: self.cursor.row,
            col: self.cursor.col,
            offset: self.cursor.offset,
        }
    }

    /// Move cursor left.
    pub fn move_left(&mut self) {
        if self.cursor.offset > 0 {
            self.cursor.offset -= 1;
            self.update_cursor_position();
        }
    }

    /// Move cursor right.
    pub fn move_right(&mut self) {
        if self.cursor.offset < self.buffer.len_chars() {
            self.cursor.offset += 1;
            self.update_cursor_position();
        }
    }

    /// Move cursor up.
    pub fn move_up(&mut self) {
        if self.cursor.row > 0 {
            self.cursor.row -= 1;
            self.update_cursor_from_row_col();
        }
    }

    /// Move cursor down.
    pub fn move_down(&mut self) {
        if self.cursor.row + 1 < self.buffer.len_lines() {
            self.cursor.row += 1;
            self.update_cursor_from_row_col();
        }
    }

    /// Move cursor to start of line.
    pub fn move_to_line_start(&mut self) {
        self.cursor.col = 0;
        self.update_cursor_from_row_col();
    }

    /// Move cursor to end of line.
    pub fn move_to_line_end(&mut self) {
        if let Some(line) = self.buffer.line(self.cursor.row) {
            self.cursor.col = line.trim_end_matches('\n').chars().count();
            self.update_cursor_from_row_col();
        }
    }

    /// Move to specific row and column.
    pub fn move_to(&mut self, row: usize, col: usize) {
        self.cursor.row = row.min(self.buffer.len_lines().saturating_sub(1));
        self.cursor.col = col;
        self.update_cursor_from_row_col();
    }

    /// Jump to a specific line (start of line).
    pub fn goto_line(&mut self, row: usize) {
        let row = row.min(self.buffer.len_lines().saturating_sub(1));
        self.cursor.row = row;
        self.cursor.col = 0;
        self.update_cursor_from_row_col();
    }

    /// Insert text at cursor.
    pub fn insert(&mut self, text: &str) {
        let offset = self.cursor.offset;
        self.buffer.rope_mut().insert(offset, text);
        let line_delta = text.chars().filter(|&ch| ch == '\n').count();
        let start_row = self.cursor.row;
        let end_row = start_row.saturating_add(line_delta + 1);
        self.buffer.mark_dirty(start_row, end_row);
        self.history.push(EditOp::Insert {
            offset,
            text: text.to_string(),
        });

        self.cursor.offset += text.chars().count();
        self.update_cursor_position();
    }

    /// Delete character before cursor.
    pub fn delete_backward(&mut self) {
        if self.cursor.offset == 0 {
            return;
        }

        let start = self.cursor.offset - 1;
        let deleted = self
            .buffer
            .rope()
            .slice(start..self.cursor.offset)
            .to_string();

        self.buffer.rope_mut().remove(start..self.cursor.offset);
        self.buffer
            .mark_dirty(self.cursor.row.saturating_sub(1), self.cursor.row + 1); // might affect prev line
        self.history.push(EditOp::Delete {
            offset: start,
            text: deleted,
        });

        self.cursor.offset = start;
        self.update_cursor_position();
    }

    /// Delete character after cursor.
    pub fn delete_forward(&mut self) {
        if self.cursor.offset >= self.buffer.len_chars() {
            return;
        }

        let end = self.cursor.offset + 1;
        let deleted = self
            .buffer
            .rope()
            .slice(self.cursor.offset..end)
            .to_string();

        self.buffer.rope_mut().remove(self.cursor.offset..end);
        let start_row = self.cursor.row;
        let end_row = if deleted.contains('\n') {
            start_row.saturating_add(2)
        } else {
            start_row.saturating_add(1)
        };
        self.buffer.mark_dirty(start_row, end_row);
        self.history.push(EditOp::Delete {
            offset: self.cursor.offset,
            text: deleted,
        });

        self.update_cursor_position();
    }

    /// Delete a range between two cursors.
    pub fn delete_range(&mut self, start: Cursor, end: Cursor) {
        let start_offset = start.offset.min(end.offset);
        let end_offset = start.offset.max(end.offset);
        self.delete_range_offsets(start_offset, end_offset);
    }

    /// Delete a range between character offsets.
    pub fn delete_range_offsets(&mut self, start: usize, end: usize) {
        if start >= end || start >= self.buffer.len_chars() {
            return;
        }
        let end = end.min(self.buffer.len_chars());
        let (start_row, end_row, deleted) = {
            let rope = self.buffer.rope();
            let start_row = rope.char_to_line(start);
            let end_row = rope.char_to_line(end.saturating_sub(1));
            let deleted = rope.slice(start..end).to_string();
            (start_row, end_row, deleted)
        };
        self.buffer.rope_mut().remove(start..end);

        self.buffer.mark_dirty(start_row, end_row.saturating_add(1));

        self.history.push(EditOp::Delete {
            offset: start,
            text: deleted,
        });
        self.cursor.offset = start;
        self.update_cursor_position();
    }

    /// Delete the current line (including trailing newline if present).
    pub fn delete_line(&mut self) {
        let line_start = self.buffer.rope().line_to_char(self.cursor.row);
        if let Some(line) = self.buffer.rope().line(self.cursor.row) {
            let line_chars = line.len_chars();
            let line_end = line_start + line_chars;
            self.delete_range_offsets(line_start, line_end);
        }
    }

    /// Duplicate the current line (insert copy below).
    pub fn duplicate_line(&mut self) {
        let line_start = self.buffer.rope().line_to_char(self.cursor.row);
        if let Some(line) = self.buffer.rope().line(self.cursor.row) {
            let line_text = line.to_string();
            // Insert at the end of the current line
            let insert_pos = line_start + line.len_chars();

            // Build the text to insert:
            // - If original line has newline: insert the line as-is (already ends with \n)
            // - If original line has no newline (last line): prepend \n, don't append
            let text_to_insert = if line_text.ends_with('\n') {
                line_text.clone()
            } else {
                format!("\n{line_text}")
            };

            self.buffer.rope_mut().insert(insert_pos, &text_to_insert);
            self.buffer.mark_dirty(self.cursor.row, self.cursor.row + 2);

            self.history.push(EditOp::Insert {
                offset: insert_pos,
                text: text_to_insert,
            });
            // Move cursor to the duplicated line
            self.cursor.row += 1;
            self.update_cursor_from_row_col();
        }
    }

    /// Move the current line up (swap with the line above).
    pub fn move_line_up(&mut self) {
        if self.cursor.row == 0 {
            return;
        }

        let target_row = self.cursor.row - 1;
        let target_col = self.cursor.col;
        let current_line_start = self.buffer.rope().line_to_char(self.cursor.row);
        let prev_line_start = self.buffer.rope().line_to_char(target_row);

        if let (Some(current_line), Some(prev_line)) = (
            self.buffer.rope().line(self.cursor.row),
            self.buffer.rope().line(target_row),
        ) {
            let current_text = current_line.to_string();
            let prev_text = prev_line.to_string();

            // Delete from start of previous line to end of current line
            let end_pos = current_line_start + current_line.len_chars();
            self.delete_range_offsets(prev_line_start, end_pos);

            // Insert current line first, then previous line
            let new_text = if current_text.ends_with('\n') {
                format!("{current_text}{prev_text}")
            } else if prev_text.ends_with('\n') {
                format!("{current_text}\n{}", prev_text.trim_end_matches('\n'))
            } else {
                format!("{current_text}\n{prev_text}")
            };

            self.buffer.rope_mut().insert(prev_line_start, &new_text);
            self.buffer.mark_dirty(target_row, target_row + 2);

            self.history.push(EditOp::Insert {
                offset: prev_line_start,
                text: new_text,
            });

            // Update cursor to the new position (one row up, same column)
            self.cursor.row = target_row;
            self.cursor.col = target_col;
            self.update_cursor_from_row_col();
        }
    }

    /// Move the current line down (swap with the line below).
    pub fn move_line_down(&mut self) {
        let total_lines = self.buffer.len_lines();
        if self.cursor.row >= total_lines.saturating_sub(1) {
            return;
        }

        let target_row = self.cursor.row + 1;
        let target_col = self.cursor.col;
        let current_line_start = self.buffer.rope().line_to_char(self.cursor.row);
        let next_line_start = self.buffer.rope().line_to_char(target_row);

        if let (Some(current_line), Some(next_line)) = (
            self.buffer.rope().line(self.cursor.row),
            self.buffer.rope().line(target_row),
        ) {
            let current_text = current_line.to_string();
            let next_text = next_line.to_string();

            // Delete from start of current line to end of next line
            let end_pos = next_line_start + next_line.len_chars();

            self.delete_range_offsets(current_line_start, end_pos);

            // Insert next line first, then current line
            let new_text = if next_text.ends_with('\n') {
                format!("{next_text}{current_text}")
            } else if current_text.ends_with('\n') {
                format!("{next_text}\n{}", current_text.trim_end_matches('\n'))
            } else {
                format!("{next_text}\n{current_text}")
            };

            self.buffer.rope_mut().insert(current_line_start, &new_text);
            self.buffer.mark_dirty(self.cursor.row, self.cursor.row + 2);

            self.history.push(EditOp::Insert {
                offset: current_line_start,
                text: new_text,
            });

            // Update cursor to the new position (one row down, same column)
            self.cursor.row = target_row;
            self.cursor.col = target_col;
            self.update_cursor_from_row_col();
        }
    }

    /// Replace the entire text, clearing history.
    pub fn replace_text(&mut self, text: &str) {
        self.set_text(text);
    }

    /// Get the next word boundary (character offset).
    #[must_use]
    pub fn get_next_word_boundary(&self) -> usize {
        let text = self.buffer.to_string();
        let mut chars = text.chars().enumerate().skip(self.cursor.offset);
        let mut in_word = false;
        let mut last_idx = self.cursor.offset;

        while let Some((idx, ch)) = chars.next() {
            let word_char = ch.is_alphanumeric() || ch == '_';
            if in_word && !word_char {
                return idx;
            }
            if !in_word && word_char {
                in_word = true;
            }
            last_idx = idx + 1;
        }
        last_idx
    }

    /// Get the previous word boundary (character offset).
    #[must_use]
    pub fn get_prev_word_boundary(&self) -> usize {
        let text = self.buffer.to_string();
        let chars: Vec<char> = text.chars().collect();
        if self.cursor.offset == 0 {
            return 0;
        }
        let mut idx = self.cursor.offset.min(chars.len());

        // Skip any non-word characters first
        while idx > 0 {
            let ch = chars[idx - 1];
            if ch.is_alphanumeric() || ch == '_' {
                break;
            }
            idx -= 1;
        }
        // Then skip word characters
        while idx > 0 {
            let ch = chars[idx - 1];
            if !(ch.is_alphanumeric() || ch == '_') {
                break;
            }
            idx -= 1;
        }
        idx
    }

    /// Move cursor to the next word boundary.
    pub fn move_word_right(&mut self) {
        let boundary = self.get_next_word_boundary();
        self.set_cursor_by_offset(boundary);
    }

    /// Move cursor to the previous word boundary.
    pub fn move_word_left(&mut self) {
        let boundary = self.get_prev_word_boundary();
        self.set_cursor_by_offset(boundary);
    }

    /// Delete from cursor to the next word boundary.
    pub fn delete_word_forward(&mut self) {
        let end = self.get_next_word_boundary();
        if end > self.cursor.offset {
            self.delete_range_offsets(self.cursor.offset, end);
        }
    }

    /// Delete from cursor to the previous word boundary.
    pub fn delete_word_backward(&mut self) {
        let start = self.get_prev_word_boundary();
        if start < self.cursor.offset {
            self.delete_range_offsets(start, self.cursor.offset);
        }
    }

    /// Get end of line offset for current line.
    #[must_use]
    pub fn get_eol(&self) -> usize {
        if let Some(line) = self.buffer.rope().line(self.cursor.row) {
            let line_chars = line.len_chars();
            let has_newline = line_chars > 0 && line.char(line_chars - 1) == '\n';
            let line_len = if has_newline {
                line_chars - 1
            } else {
                line_chars
            };
            let line_start = self.buffer.rope().line_to_char(self.cursor.row);
            line_start + line_len
        } else {
            self.cursor.offset
        }
    }

    /// Undo the last edit.
    pub fn undo(&mut self) -> bool {
        let Some(ops) = self.history.pop_undo() else {
            return false;
        };

        let mut redo_ops = Vec::new();
        for op in ops.into_iter().rev() {
            self.apply_op(&op.invert());
            redo_ops.push(op);
        }
        redo_ops.reverse();
        self.history.push_redo(redo_ops);

        true
    }

    /// Redo the last undone edit.
    pub fn redo(&mut self) -> bool {
        let Some(ops) = self.history.pop_redo() else {
            return false;
        };

        for op in &ops {
            self.apply_op(op);
        }
        self.history.undo_stack.push(ops);

        true
    }

    /// Check if undo is available.
    #[must_use]
    pub fn can_undo(&self) -> bool {
        self.history.can_undo()
    }

    /// Check if redo is available.
    #[must_use]
    pub fn can_redo(&self) -> bool {
        self.history.can_redo()
    }

    /// Commit current edits as an undo group.
    pub fn commit(&mut self) {
        self.history.commit();
    }

    /// Clear the undo/redo history.
    ///
    /// This removes all undo and redo entries. Useful when loading new content
    /// where previous history is no longer relevant.
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    fn apply_op(&mut self, op: &EditOp) {
        match op {
            EditOp::Insert { offset, text } => {
                self.buffer.rope_mut().insert(*offset, text);

                let row = self.buffer.rope().char_to_line(*offset);
                let line_delta = text.chars().filter(|&ch| ch == '\n').count();
                self.buffer
                    .mark_dirty(row, row.saturating_add(line_delta + 1));

                self.cursor.offset = offset + text.chars().count();
            }
            EditOp::Delete { offset, text } => {
                let end = offset + text.chars().count();
                let (start_row, end_row) = {
                    let rope = self.buffer.rope();
                    let start_row = rope.char_to_line(*offset);
                    let end_row = rope.char_to_line(end.saturating_sub(1));
                    (start_row, end_row)
                };
                self.buffer.rope_mut().remove(*offset..end);
                self.buffer.mark_dirty(start_row, end_row.saturating_add(1));

                self.cursor.offset = *offset;
            }
        }
        self.update_cursor_position();
    }

    fn update_cursor_position(&mut self) {
        let rope = self.buffer.rope();
        self.cursor.row = rope
            .inner()
            .char_to_line(self.cursor.offset.min(rope.len_chars()));
        let line_start = rope.line_to_char(self.cursor.row);
        self.cursor.col = self.cursor.offset.saturating_sub(line_start);
    }

    fn update_cursor_from_row_col(&mut self) {
        let rope = self.buffer.rope();
        let line_start = rope.line_to_char(self.cursor.row);

        if let Some(line) = rope.line(self.cursor.row) {
            let line_chars = line.len_chars();
            // Only exclude newline if actually present at end of line
            let has_newline = line_chars > 0 && line.char(line_chars - 1) == '\n';
            let line_len = if has_newline {
                line_chars - 1
            } else {
                line_chars
            };
            self.cursor.col = self.cursor.col.min(line_len);
        }

        self.cursor.offset = line_start + self.cursor.col;
    }

    fn clamp_cursor(&mut self) {
        self.cursor.offset = self.cursor.offset.min(self.buffer.len_chars());
        self.update_cursor_position();
    }
}

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

    #[test]
    fn test_edit_basic() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        assert_eq!(edit.text(), "Hello");
        assert_eq!(edit.cursor().offset, 5);
    }

    #[test]
    fn test_edit_delete() {
        let mut edit = EditBuffer::with_text("Hello");
        edit.move_to(0, 5);
        edit.delete_backward();
        assert_eq!(edit.text(), "Hell");
    }

    #[test]
    fn test_edit_undo() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        edit.insert(" World");
        edit.commit();
        assert_eq!(edit.text(), "Hello World");

        edit.undo();
        assert_eq!(edit.text(), "Hello");

        edit.undo();
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_edit_redo() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();

        edit.undo();
        assert_eq!(edit.text(), "");

        edit.redo();
        assert_eq!(edit.text(), "Hello");
    }

    #[test]
    fn test_cursor_movement() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");
        edit.move_to(0, 0);
        assert_eq!(edit.cursor().row, 0);

        edit.move_down();
        assert_eq!(edit.cursor().row, 1);

        edit.move_up();
        assert_eq!(edit.cursor().row, 0);
    }

    #[test]
    fn test_history_depth_limit() {
        let mut edit = EditBuffer::with_max_history_depth(3);
        assert_eq!(edit.max_history_depth(), 3);

        // Add 5 undo groups
        for i in 0..5 {
            edit.insert(&format!("{i}"));
            edit.commit();
        }
        assert_eq!(edit.text(), "01234");

        // Should only be able to undo 3 times (depth limit)
        assert!(edit.undo()); // undo "4"
        assert!(edit.undo()); // undo "3"
        assert!(edit.undo()); // undo "2"
        assert!(!edit.undo()); // no more undo available

        // Text should be "01" (groups 0 and 1 were pruned)
        assert_eq!(edit.text(), "01");
    }

    #[test]
    fn test_set_max_history_depth() {
        let mut edit = EditBuffer::new();
        assert_eq!(edit.max_history_depth(), 1000); // default

        edit.set_max_history_depth(50);
        assert_eq!(edit.max_history_depth(), 50);
    }

    #[test]
    fn test_delete_range_offsets() {
        let mut edit = EditBuffer::with_text("Hello, world!");
        // Deleting positions 5-6 removes "," and " "
        edit.delete_range_offsets(5, 6);
        assert_eq!(edit.text(), "Hello world!");
    }

    #[test]
    fn test_delete_line() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        edit.move_to(1, 0);
        edit.delete_line();
        assert_eq!(edit.text(), "Line 1\nLine 3");
    }

    #[test]
    fn test_word_boundaries() {
        let mut edit = EditBuffer::with_text("hello world");
        edit.set_cursor_by_offset(0);
        assert_eq!(edit.get_next_word_boundary(), 5);
        edit.set_cursor_by_offset(6);
        assert_eq!(edit.get_prev_word_boundary(), 0);
    }

    #[test]
    fn test_move_word_right() {
        let mut edit = EditBuffer::with_text("hello world test");
        edit.set_cursor_by_offset(0);
        edit.move_word_right();
        assert_eq!(edit.cursor().offset, 5);
        edit.move_word_right();
        assert_eq!(edit.cursor().offset, 11);
    }

    #[test]
    fn test_move_word_left() {
        let mut edit = EditBuffer::with_text("hello world test");
        edit.set_cursor_by_offset(16);
        edit.move_word_left();
        assert_eq!(edit.cursor().offset, 12);
        edit.move_word_left();
        assert_eq!(edit.cursor().offset, 6);
    }

    #[test]
    fn test_delete_word_forward() {
        let mut edit = EditBuffer::with_text("hello world");
        edit.set_cursor_by_offset(0);
        edit.delete_word_forward();
        assert_eq!(edit.text(), " world");
    }

    #[test]
    fn test_delete_word_backward() {
        let mut edit = EditBuffer::with_text("hello world");
        edit.set_cursor_by_offset(11);
        edit.delete_word_backward();
        assert_eq!(edit.text(), "hello ");
    }

    #[test]
    fn test_goto_line() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        edit.goto_line(2);
        assert_eq!(edit.cursor().row, 2);
        assert_eq!(edit.cursor().col, 0);
    }

    #[test]
    fn test_duplicate_line() {
        eprintln!("[TEST] test_duplicate_line: Testing line duplication");
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        edit.goto_line(1);
        eprintln!("[TEST] Before duplicate: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);

        edit.duplicate_line();

        eprintln!("[TEST] After duplicate: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);
        assert_eq!(edit.text(), "Line 1\nLine 2\nLine 2\nLine 3");
        assert_eq!(
            edit.cursor().row,
            2,
            "Cursor should move to duplicated line"
        );
        eprintln!("[TEST] SUCCESS: Line duplication works correctly");
    }

    #[test]
    fn test_duplicate_last_line() {
        eprintln!(
            "[TEST] test_duplicate_last_line: Testing last line duplication (no trailing newline)"
        );
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");
        edit.goto_line(1);
        eprintln!("[TEST] Before duplicate: {:?}", edit.text());

        edit.duplicate_line();

        eprintln!("[TEST] After duplicate: {:?}", edit.text());
        assert_eq!(edit.text(), "Line 1\nLine 2\nLine 2");
        eprintln!("[TEST] SUCCESS: Last line duplication works correctly");
    }

    #[test]
    fn test_move_line_up() {
        eprintln!("[TEST] test_move_line_up: Testing moving line up");
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        edit.goto_line(1);
        eprintln!("[TEST] Before move: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);

        edit.move_line_up();

        eprintln!("[TEST] After move: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);
        assert_eq!(edit.text(), "Line 2\nLine 1\nLine 3");
        assert_eq!(edit.cursor().row, 0, "Cursor should follow the moved line");
        eprintln!("[TEST] SUCCESS: Move line up works correctly");
    }

    #[test]
    fn test_move_line_up_at_top() {
        eprintln!("[TEST] test_move_line_up_at_top: Testing move line up at first line (no-op)");
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");
        edit.goto_line(0);

        edit.move_line_up();

        assert_eq!(edit.text(), "Line 1\nLine 2", "Should be unchanged");
        assert_eq!(edit.cursor().row, 0);
        eprintln!("[TEST] SUCCESS: Move line up at top is a no-op");
    }

    #[test]
    fn test_move_line_down() {
        eprintln!("[TEST] test_move_line_down: Testing moving line down");
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        edit.goto_line(1);
        eprintln!("[TEST] Before move: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);

        edit.move_line_down();

        eprintln!("[TEST] After move: {:?}", edit.text());
        eprintln!("[TEST] Cursor at row: {}", edit.cursor().row);
        assert_eq!(edit.text(), "Line 1\nLine 3\nLine 2");
        assert_eq!(edit.cursor().row, 2, "Cursor should follow the moved line");
        eprintln!("[TEST] SUCCESS: Move line down works correctly");
    }

    #[test]
    fn test_move_line_down_at_bottom() {
        eprintln!(
            "[TEST] test_move_line_down_at_bottom: Testing move line down at last line (no-op)"
        );
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");
        edit.goto_line(1);

        edit.move_line_down();

        assert_eq!(edit.text(), "Line 1\nLine 2", "Should be unchanged");
        assert_eq!(edit.cursor().row, 1);
        eprintln!("[TEST] SUCCESS: Move line down at bottom is a no-op");
    }

    #[test]
    fn test_line_operations_with_undo() {
        eprintln!("[TEST] test_line_operations_with_undo: Testing undo for line operations");
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");
        let original = edit.text().clone();
        edit.goto_line(1);

        // Duplicate and undo
        edit.duplicate_line();
        assert_ne!(edit.text(), original);
        edit.undo();
        assert_eq!(
            edit.text(),
            original,
            "Undo should restore original after duplicate"
        );

        // Move up and undo
        edit.goto_line(1);
        edit.move_line_up();
        assert_ne!(edit.text(), original);
        edit.undo();
        edit.undo(); // Need two undos - one for delete, one for insert
        assert_eq!(
            edit.text(),
            original,
            "Undo should restore original after move up"
        );

        eprintln!("[TEST] SUCCESS: Undo works for line operations");
    }

    // =========================================================================
    // Additional Text Editing Buffer Tests (bd-2jxq)
    // =========================================================================

    #[test]
    fn test_delete_char_forward() {
        let mut edit = EditBuffer::with_text("Hello");
        edit.set_cursor_by_offset(0); // At start
        edit.delete_forward();
        assert_eq!(edit.text(), "ello");
        assert_eq!(edit.cursor().offset, 0);
    }

    #[test]
    fn test_delete_forward_at_end() {
        let mut edit = EditBuffer::with_text("Hello");
        edit.set_cursor_by_offset(5); // At end
        edit.delete_forward(); // Should be no-op
        assert_eq!(edit.text(), "Hello");
    }

    #[test]
    fn test_newline_insert_splits_line() {
        let mut edit = EditBuffer::with_text("HelloWorld");
        edit.set_cursor_by_offset(5); // Between Hello and World
        edit.insert("\n");
        assert_eq!(edit.text(), "Hello\nWorld");
        assert_eq!(edit.cursor().row, 1);
        assert_eq!(edit.cursor().col, 0);
    }

    #[test]
    fn test_join_lines_backspace_at_start() {
        let mut edit = EditBuffer::with_text("Hello\nWorld");
        edit.goto_line(1);
        edit.move_to_line_start();
        edit.delete_backward(); // Removes the newline
        assert_eq!(edit.text(), "HelloWorld");
        assert_eq!(edit.cursor().offset, 5);
    }

    #[test]
    fn test_insert_utf8_chars() {
        let mut edit = EditBuffer::new();
        edit.insert("日本語");
        assert_eq!(edit.text(), "日本語");
        assert_eq!(edit.cursor().offset, 3); // 3 characters
    }

    #[test]
    fn test_delete_utf8_chars() {
        let mut edit = EditBuffer::with_text("日本語");
        edit.set_cursor_by_offset(3); // At end
        edit.delete_backward();
        assert_eq!(edit.text(), "日本");
        edit.delete_backward();
        assert_eq!(edit.text(), "");
        edit.delete_backward();
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_insert_emoji() {
        let mut edit = EditBuffer::new();
        edit.insert("🎉🚀🔥");
        assert_eq!(edit.text(), "🎉🚀🔥");
        assert_eq!(edit.cursor().offset, 3);
    }

    #[test]
    fn test_cursor_at_line_start() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");
        edit.move_to(1, 0);
        assert_eq!(edit.cursor().col, 0);
        edit.move_to_line_start();
        assert_eq!(edit.cursor().col, 0);
    }

    #[test]
    fn test_cursor_at_line_end() {
        let mut edit = EditBuffer::with_text("Hello\nWorld");
        edit.move_to(0, 0);
        edit.move_to_line_end();
        assert_eq!(edit.cursor().col, 5); // "Hello" is 5 chars
    }

    #[test]
    fn test_undo_delete_restores_text() {
        let mut edit = EditBuffer::with_text("Hello World");
        edit.set_cursor_by_offset(11);
        edit.delete_backward(); // Delete 'd'
        edit.commit();
        assert_eq!(edit.text(), "Hello Worl");

        edit.undo();
        assert_eq!(edit.text(), "Hello World");
    }

    #[test]
    fn test_insert_at_middle() {
        let mut edit = EditBuffer::with_text("HelloWorld");
        edit.set_cursor_by_offset(5);
        edit.insert(" ");
        assert_eq!(edit.text(), "Hello World");
        assert_eq!(edit.cursor().offset, 6);
    }

    #[test]
    fn test_multiple_inserts_single_undo() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.insert(" ");
        edit.insert("World");
        // No commit - all in same undo group
        edit.undo();
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_clear_history() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        edit.insert(" World");
        edit.commit();
        assert!(edit.can_undo());

        edit.clear_history();
        assert!(!edit.can_undo());
        assert!(!edit.can_redo());
        // Text should be preserved
        assert_eq!(edit.text(), "Hello World");
    }

    #[test]
    fn test_get_eol() {
        let mut edit = EditBuffer::with_text("Hello\nWorld");
        edit.goto_line(0);
        assert_eq!(edit.get_eol(), 5); // "Hello" without newline

        edit.goto_line(1);
        assert_eq!(edit.get_eol(), 11); // Position after "World"
    }

    #[test]
    fn test_move_left_right_boundaries() {
        let mut edit = EditBuffer::with_text("AB");
        edit.set_cursor_by_offset(0);

        // Move left at start should be no-op
        edit.move_left();
        assert_eq!(edit.cursor().offset, 0);

        // Move right through text
        edit.move_right();
        assert_eq!(edit.cursor().offset, 1);
        edit.move_right();
        assert_eq!(edit.cursor().offset, 2);

        // Move right at end should be no-op
        edit.move_right();
        assert_eq!(edit.cursor().offset, 2);
    }

    #[test]
    fn test_empty_buffer_operations() {
        let mut edit = EditBuffer::new();
        assert_eq!(edit.text(), "");

        // Delete operations on empty buffer should be safe
        edit.delete_backward();
        edit.delete_forward();
        assert_eq!(edit.text(), "");

        // Cursor movement should be safe
        edit.move_left();
        edit.move_right();
        edit.move_up();
        edit.move_down();
        assert_eq!(edit.cursor().offset, 0);
    }

    #[test]
    fn test_set_text_resets_cursor() {
        let mut edit = EditBuffer::with_text("Hello World");
        edit.set_cursor_by_offset(6);
        assert_eq!(edit.cursor().offset, 6);

        edit.set_text("New");
        assert_eq!(edit.text(), "New");
        assert_eq!(edit.cursor().offset, 0); // Reset to start
    }

    // =============================================
    // Comprehensive Undo/Redo Tests (bd-gzb6)
    // =============================================

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

    #[test]
    fn test_undo_single_insert_restores_empty() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        assert_eq!(edit.text(), "Hello");

        assert!(edit.undo());
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_undo_single_delete_restores_text() {
        let mut edit = EditBuffer::with_text("Hello");
        edit.move_to(0, 5);
        edit.delete_backward();
        edit.commit();
        assert_eq!(edit.text(), "Hell");

        assert!(edit.undo());
        assert_eq!(edit.text(), "Hello");
    }

    #[test]
    fn test_undo_redo_roundtrip() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();

        edit.undo();
        assert_eq!(edit.text(), "");

        edit.redo();
        assert_eq!(edit.text(), "Hello");
    }

    #[test]
    fn test_multiple_undos() {
        let mut edit = EditBuffer::new();
        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();
        edit.insert("C");
        edit.commit();
        assert_eq!(edit.text(), "ABC");

        assert!(edit.undo());
        assert_eq!(edit.text(), "AB");
        assert!(edit.undo());
        assert_eq!(edit.text(), "A");
        assert!(edit.undo());
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_multiple_redos() {
        let mut edit = EditBuffer::new();
        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();
        edit.insert("C");
        edit.commit();

        edit.undo();
        edit.undo();
        edit.undo();
        assert_eq!(edit.text(), "");

        assert!(edit.redo());
        assert_eq!(edit.text(), "A");
        assert!(edit.redo());
        assert_eq!(edit.text(), "AB");
        assert!(edit.redo());
        assert_eq!(edit.text(), "ABC");
    }

    // --- Commit behavior ---

    #[test]
    fn test_commit_groups_edits() {
        let mut edit = EditBuffer::new();
        // Multiple inserts before commit = one undo group
        edit.insert("H");
        edit.insert("e");
        edit.insert("l");
        edit.insert("l");
        edit.insert("o");
        edit.commit();
        assert_eq!(edit.text(), "Hello");

        // One undo should revert all five inserts
        assert!(edit.undo());
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_empty_commit_is_harmless() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();

        // Commit with no changes since last commit
        edit.commit();
        edit.commit();

        // Undo should still work
        assert!(edit.undo());
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_multiple_commit_groups() {
        let mut edit = EditBuffer::new();
        edit.insert("First");
        edit.commit();
        edit.insert(" Second");
        edit.commit();
        edit.insert(" Third");
        edit.commit();

        assert_eq!(edit.text(), "First Second Third");

        edit.undo(); // Removes " Third"
        assert_eq!(edit.text(), "First Second");
        edit.undo(); // Removes " Second"
        assert_eq!(edit.text(), "First");
        edit.undo(); // Removes "First"
        assert_eq!(edit.text(), "");
    }

    // --- can_undo / can_redo ---

    #[test]
    fn test_can_undo_empty_history() {
        let edit = EditBuffer::new();
        assert!(!edit.can_undo());
    }

    #[test]
    fn test_can_undo_after_commit() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        assert!(edit.can_undo());
    }

    #[test]
    fn test_can_redo_empty() {
        let edit = EditBuffer::new();
        assert!(!edit.can_redo());
    }

    #[test]
    fn test_can_redo_after_undo() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        edit.undo();
        assert!(edit.can_redo());
    }

    #[test]
    fn test_cannot_redo_after_new_edit() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        edit.undo();
        assert!(edit.can_redo());

        // New edit clears redo stack
        edit.insert("World");
        edit.commit();
        assert!(!edit.can_redo());
    }

    // --- Edge cases ---

    #[test]
    fn test_undo_returns_false_on_empty_history() {
        let mut edit = EditBuffer::new();
        assert!(!edit.undo());
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_redo_returns_false_on_empty_redo_stack() {
        let mut edit = EditBuffer::new();
        assert!(!edit.redo());
    }

    #[test]
    fn test_new_edit_clears_redo_stack() {
        let mut edit = EditBuffer::new();
        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();

        edit.undo(); // Back to "A"
        assert!(edit.can_redo());

        edit.insert("C");
        edit.commit();
        assert!(!edit.can_redo());
        assert_eq!(edit.text(), "AC");
    }

    #[test]
    fn test_undo_multiline_delete() {
        let mut edit = EditBuffer::with_text("Line1\nLine2\nLine3");
        // Select and delete "Line2\n"
        edit.set_cursor_by_offset(6); // Start of "Line2"
        edit.delete_forward(); // L
        edit.delete_forward(); // i
        edit.delete_forward(); // n
        edit.delete_forward(); // e
        edit.delete_forward(); // 2
        edit.delete_forward(); // \n
        edit.commit();
        assert_eq!(edit.text(), "Line1\nLine3");

        edit.undo();
        assert_eq!(edit.text(), "Line1\nLine2\nLine3");
    }

    // --- History depth limits ---

    #[test]
    fn test_history_depth_limit_extended() {
        let mut edit = EditBuffer::with_max_history_depth(3);

        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();
        edit.insert("C");
        edit.commit();
        edit.insert("D");
        edit.commit();
        assert_eq!(edit.text(), "ABCD");

        // With max depth 3, oldest entry should be pruned
        // We should only be able to undo 3 times
        assert!(edit.undo()); // "ABC"
        assert!(edit.undo()); // "AB"
        assert!(edit.undo()); // "A"
        // Fourth undo should fail (oldest entry pruned)
        assert!(!edit.undo());
        assert_eq!(edit.text(), "A");
    }

    #[test]
    fn test_set_max_history_depth_and_verify() {
        let mut edit = EditBuffer::new();
        edit.set_max_history_depth(2);
        assert_eq!(edit.max_history_depth(), 2);

        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();
        edit.insert("C");
        edit.commit();

        // Only 2 undos should work
        assert!(edit.undo());
        assert!(edit.undo());
        assert!(!edit.undo());
    }

    #[test]
    fn test_clear_history_preserves_text() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        assert!(edit.can_undo());

        edit.clear_history();
        assert!(!edit.can_undo());
        assert!(!edit.can_redo());
        assert_eq!(edit.text(), "Hello"); // Text preserved
    }

    #[test]
    fn test_clear_history_clears_redo() {
        let mut edit = EditBuffer::new();
        edit.insert("Hello");
        edit.commit();
        edit.undo();
        assert!(edit.can_redo());

        edit.clear_history();
        assert!(!edit.can_redo());
    }

    // --- Undo with different edit types ---

    #[test]
    fn test_undo_delete_backward() {
        let mut edit = EditBuffer::with_text("ABC");
        edit.set_cursor_by_offset(3); // End
        edit.delete_backward();
        edit.commit();
        assert_eq!(edit.text(), "AB");

        edit.undo();
        assert_eq!(edit.text(), "ABC");
    }

    #[test]
    fn test_undo_delete_forward() {
        let mut edit = EditBuffer::with_text("ABC");
        edit.set_cursor_by_offset(0); // Start
        edit.delete_forward();
        edit.commit();
        assert_eq!(edit.text(), "BC");

        edit.undo();
        assert_eq!(edit.text(), "ABC");
    }

    #[test]
    fn test_undo_redo_complex_sequence() {
        let mut edit = EditBuffer::new();

        edit.insert("Hello");
        edit.commit();
        edit.insert(" World");
        edit.commit();
        assert_eq!(edit.text(), "Hello World");

        edit.undo();
        assert_eq!(edit.text(), "Hello");

        // Insert something new (clears redo)
        edit.insert(" Rust");
        edit.commit();
        assert_eq!(edit.text(), "Hello Rust");

        // Can't redo " World" anymore
        assert!(!edit.can_redo());

        // Can still undo
        edit.undo();
        assert_eq!(edit.text(), "Hello");
        edit.undo();
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_undo_redo_preserves_text_integrity() {
        let mut edit = EditBuffer::new();
        let text = "The quick brown fox";
        edit.insert(text);
        edit.commit();

        // Undo and redo multiple times
        for _ in 0..5 {
            edit.undo();
            assert_eq!(edit.text(), "");
            edit.redo();
            assert_eq!(edit.text(), text);
        }
    }

    // =========================================================================
    // Edge Case and Stress Tests (bd-2r2p)
    // =========================================================================

    // --- Large Document Handling ---

    #[test]
    fn test_large_document_line_count() {
        // Create a document with 1000 lines
        let mut lines = String::new();
        for i in 0..1000 {
            writeln!(&mut lines, "Line {i}").expect("write to String should not fail");
        }
        let mut edit = EditBuffer::with_text(&lines);

        assert_eq!(edit.buffer().len_lines(), 1001); // 1000 lines + trailing empty line from \n

        // Navigate to middle
        edit.goto_line(500);
        assert_eq!(edit.cursor().row, 500);

        // Insert at middle
        edit.insert("INSERTED");
        assert!(edit.text().contains("INSERTED"));
    }

    #[test]
    fn test_long_line_handling() {
        // Create a line with 1000 characters
        let long_line: String = "X".repeat(1000);
        let mut edit = EditBuffer::with_text(&long_line);

        assert_eq!(edit.text().len(), 1000);

        // Move to middle of long line
        edit.move_to(0, 500);
        assert_eq!(edit.cursor().col, 500);

        // Insert in middle
        edit.insert("Y");
        assert_eq!(edit.text().len(), 1001);
    }

    #[test]
    fn test_rapid_insert_delete_cycles() {
        let mut edit = EditBuffer::new();

        // Rapid insert/delete cycle
        for _ in 0..100 {
            edit.insert("test");
            edit.delete_backward();
            edit.delete_backward();
            edit.delete_backward();
            edit.delete_backward();
        }

        // Should end up empty
        assert_eq!(edit.text(), "");
    }

    // --- Undo/Redo Edge Cases ---

    #[test]
    fn test_many_undo_operations() {
        let mut edit = EditBuffer::with_max_history_depth(100);

        // Create 50 commits
        for i in 0..50 {
            edit.insert(&format!("{i} "));
            edit.commit();
        }

        // Undo all
        let mut undo_count = 0;
        while edit.undo() {
            undo_count += 1;
        }

        assert_eq!(undo_count, 50);
        assert_eq!(edit.text(), "");
    }

    #[test]
    fn test_undo_after_clear() {
        let mut edit = EditBuffer::with_text("Hello World");
        edit.commit();

        // Clear by deleting the full range
        let len = edit.text().len();
        edit.delete_range_offsets(0, len);
        edit.commit();

        assert_eq!(edit.text(), "");

        // Undo should restore
        edit.undo();
        assert_eq!(edit.text(), "Hello World");
    }

    #[test]
    fn test_redo_invalidated_by_new_edit() {
        let mut edit = EditBuffer::new();
        edit.insert("A");
        edit.commit();
        edit.insert("B");
        edit.commit();

        edit.undo(); // Undo "B"
        assert!(edit.can_redo());

        edit.insert("C"); // New edit invalidates redo
        assert!(!edit.can_redo());

        assert_eq!(edit.text(), "AC");
    }

    // --- Unicode Edge Cases ---

    #[test]
    fn test_cursor_through_emoji() {
        let mut edit = EditBuffer::with_text("A👨‍👩‍👧B");

        edit.set_cursor_by_offset(0);
        assert_eq!(edit.cursor().offset, 0);

        edit.move_right(); // Past 'A'
        let offset_after_a = edit.cursor().offset;
        assert_eq!(offset_after_a, 1);

        edit.move_right(); // Past emoji (should skip whole grapheme cluster)
        let offset_after_emoji = edit.cursor().offset;
        assert!(
            offset_after_emoji > offset_after_a,
            "Should have moved past emoji"
        );

        edit.move_right(); // Past 'B'
        // Should be at end
    }

    #[test]
    fn test_delete_in_grapheme_cluster() {
        // Family emoji is a grapheme cluster
        let mut edit = EditBuffer::with_text("👨‍👩‍👧");

        let len = edit.text().len();
        edit.set_cursor_by_offset(len); // Move to end
        edit.delete_backward(); // Should delete entire grapheme

        // Text should be empty (whole grapheme deleted)
        assert!(
            edit.text().is_empty() || !edit.text().contains("👨‍👩‍👧"),
            "Grapheme cluster should be deleted as unit"
        );
    }

    #[test]
    fn test_unicode_combining_characters() {
        // e + combining acute accent
        let mut edit = EditBuffer::with_text("e\u{0301}"); // é as base + combining

        let end_offset = edit.text().len();
        edit.set_cursor_by_offset(end_offset); // Move to end

        edit.delete_backward();

        // Should delete as grapheme unit
        assert!(
            edit.text().len() < end_offset,
            "Should have deleted combining sequence"
        );
    }

    // --- Cursor Edge Cases ---

    #[test]
    fn test_cursor_at_document_end() {
        let mut edit = EditBuffer::with_text("Hello");

        edit.set_cursor_by_offset(edit.text().len()); // Move to end
        assert_eq!(edit.cursor().offset, 5);

        // Moving right at end should be no-op
        edit.move_right();
        assert_eq!(edit.cursor().offset, 5);

        // Moving right again should still be no-op
        edit.move_right();
        assert_eq!(edit.cursor().offset, 5);
    }

    #[test]
    fn test_cursor_at_document_start() {
        let mut edit = EditBuffer::with_text("Hello");

        edit.set_cursor_by_offset(0);
        assert_eq!(edit.cursor().offset, 0);

        // Moving backward at start should be no-op
        edit.move_left();
        assert_eq!(edit.cursor().offset, 0);

        // Moving left at start should be no-op
        edit.move_left();
        assert_eq!(edit.cursor().offset, 0);
    }

    #[test]
    fn test_cursor_through_empty_lines() {
        let mut edit = EditBuffer::with_text("Line1\n\n\nLine4");

        edit.goto_line(0);
        edit.move_down(); // To empty line 1
        assert_eq!(edit.cursor().row, 1);
        assert_eq!(edit.cursor().col, 0);

        edit.move_down(); // To empty line 2
        assert_eq!(edit.cursor().row, 2);
        assert_eq!(edit.cursor().col, 0);

        edit.move_down(); // To Line4
        assert_eq!(edit.cursor().row, 3);
    }

    #[test]
    fn test_move_up_at_first_line() {
        let mut edit = EditBuffer::with_text("First line\nSecond line");

        edit.goto_line(0);
        edit.move_up(); // Should be no-op at first line

        assert_eq!(edit.cursor().row, 0);
    }

    #[test]
    fn test_move_down_at_last_line() {
        let mut edit = EditBuffer::with_text("First line\nLast line");

        edit.goto_line(1);
        edit.move_down(); // Should be no-op at last line

        assert_eq!(edit.cursor().row, 1);
    }

    // --- Selection Edge Cases ---

    #[test]
    fn test_delete_empty_selection() {
        let mut edit = EditBuffer::with_text("Hello");

        // Delete range of zero length should be no-op
        edit.delete_range_offsets(2, 2);
        assert_eq!(edit.text(), "Hello");
    }

    #[test]
    fn test_selection_across_line_boundaries() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2\nLine 3");

        // Delete from middle of line 1 to middle of line 3
        edit.delete_range_offsets(3, 17); // "e 1\nLine 2\nLin"

        assert_eq!(edit.text(), "Line 3");
    }

    // --- Empty Buffer Edge Cases ---

    #[test]
    fn test_operations_on_empty_buffer() {
        let mut edit = EditBuffer::new();

        // All these should be safe no-ops
        edit.delete_backward();
        edit.delete_forward();
        edit.move_right();
        edit.move_left();
        edit.move_up();
        edit.move_down();
        edit.move_word_left();
        edit.move_word_right();

        assert_eq!(edit.text(), "");
        assert_eq!(edit.cursor().offset, 0);
    }

    #[test]
    fn test_undo_on_empty_buffer() {
        let mut edit = EditBuffer::new();

        // Undo on empty buffer should return false
        assert!(!edit.undo());
        assert!(!edit.redo());
    }

    // --- Line Boundary Edge Cases ---

    #[test]
    fn test_delete_at_line_start() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");

        edit.goto_line(1);
        edit.move_to_line_start();
        edit.delete_backward(); // Should join lines

        assert_eq!(edit.text(), "Line 1Line 2");
    }

    #[test]
    fn test_delete_at_line_end() {
        let mut edit = EditBuffer::with_text("Line 1\nLine 2");

        edit.goto_line(0);
        edit.move_to_line_end();
        edit.delete_forward(); // Should delete newline and join lines

        assert_eq!(edit.text(), "Line 1Line 2");
    }
}