1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
//!
//! A text-area with text-styling abilities.
//!
use crate::_private::NonExhaustive;
use crate::event::{ReadOnly, TextOutcome};
use crate::textarea::core::{RopeGraphemes, TextRange};
use crossterm::event::KeyModifiers;
#[allow(unused_imports)]
use log::debug;
use rat_event::util::MouseFlags;
use rat_event::{ct_event, flow, FocusKeys, HandleEvent, MouseOnly};
use rat_focus::{FocusFlag, HasFocusFlag};
use rat_scrolled::event::ScrollOutcome;
use rat_scrolled::{layout_scroll, Scroll, ScrollArea, ScrollState};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Stylize;
use ratatui::style::Style;
use ratatui::widgets::{Block, StatefulWidget, StatefulWidgetRef, WidgetRef};
use ropey::{Rope, RopeSlice};
use std::cmp::{max, min};

/// Text area widget.
///
/// Backend used is [ropey](https://docs.rs/ropey/latest/ropey/), so large
/// texts are no problem. Editing time increases with the number of
/// styles applied. Everything below a million styles should be fine.
///
/// For emoji support this uses
/// [unicode_display_width](https://docs.rs/unicode-display-width/latest/unicode_display_width/index.html)
/// which helps with those double-width emojis. Input of emojis
/// strongly depends on the terminal. It may or may not work.
/// And even with display there are sometimes strange glitches
/// that I haven't found yet.
///
/// Keyboard and mouse are implemented for crossterm, but it should be
/// trivial to extend to other event-types. Every interaction is available
/// as function on the state.
///
/// Scrolling doesn't depend on the cursor, but the editing and move
/// functions take care that the cursor stays visible.
///
/// Wordwrap is not available. For display only use
/// [Paragraph](https://docs.rs/ratatui/latest/ratatui/widgets/struct.Paragraph.html), as
/// for editing: why?
///
/// You can directly access the underlying Rope for readonly purposes, and
/// conversion from/to byte/char positions are available. That should probably be
/// enough to write a parser that generates some styling.
///
/// The cursor must set externally on the ratatui Frame as usual.
/// [screen_cursor](TextAreaState::screen_cursor) gives you the correct value.
/// There is the inverse too [set_screen_cursor](TextAreaState::set_screen_cursor)
/// For more interactions you can use [from_screen_col](TextAreaState::from_screen_col),
/// and [to_screen_col](TextAreaState::to_screen_col). They calculate everything,
/// even in the presence of more complex graphemes and those double-width emojis.
///
#[derive(Debug, Default, Clone)]
pub struct TextArea<'a> {
    block: Option<Block<'a>>,
    hscroll: Option<Scroll<'a>>,
    h_max_offset: Option<usize>,
    vscroll: Option<Scroll<'a>>,

    style: Style,
    focus_style: Option<Style>,
    select_style: Option<Style>,
    text_style: Vec<Style>,
}

/// Combined style for the widget.
#[derive(Debug, Clone)]
pub struct TextAreaStyle {
    pub style: Style,
    pub focus: Option<Style>,
    pub select: Option<Style>,
    pub non_exhaustive: NonExhaustive,
}

/// State for the text-area.
///
#[derive(Debug, Clone)]
pub struct TextAreaState {
    /// Current focus state.
    pub focus: FocusFlag,
    /// Complete area.
    pub area: Rect,
    /// Area inside the borders.
    pub inner: Rect,
    /// Text edit core
    pub value: core::InputCore,

    /// Horizontal scroll
    pub hscroll: ScrollState,
    pub vscroll: ScrollState,

    /// Helper for mouse.
    pub mouse: MouseFlags,

    pub non_exhaustive: NonExhaustive,
}

impl Default for TextAreaStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            focus: None,
            select: None,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<'a> TextArea<'a> {
    /// New widget.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the combined style.
    #[inline]
    pub fn styles(mut self, style: TextAreaStyle) -> Self {
        self.style = style.style;
        self.focus_style = style.focus;
        self.select_style = style.select;
        self
    }

    /// Base style.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Style when focused.
    pub fn focus_style(mut self, style: Style) -> Self {
        self.focus_style = Some(style);
        self
    }

    /// Selection style.
    pub fn select_style(mut self, style: Style) -> Self {
        self.select_style = Some(style);
        self
    }

    /// List of text-styles.
    ///
    /// Use [TextAreaState::add_style()] to refer a text range to
    /// one of these styles.
    pub fn text_style<T: IntoIterator<Item = Style>>(mut self, styles: T) -> Self {
        self.text_style = styles.into_iter().collect();
        self
    }

    #[inline]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Scrollbars
    pub fn scroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.clone().override_horizontal());
        self.vscroll = Some(scroll.override_vertical());
        self
    }

    /// Scrollbars
    pub fn hscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.hscroll = Some(scroll.override_horizontal());
        self
    }

    /// Set a maximum horizontal offset. There is no default offset.
    pub fn set_horizontal_max_offset(mut self, offset: usize) -> Self {
        self.h_max_offset = Some(offset);
        self
    }

    /// Scrollbars
    pub fn vscroll(mut self, scroll: Scroll<'a>) -> Self {
        self.vscroll = Some(scroll.override_vertical());
        self
    }
}

impl<'a> StatefulWidgetRef for TextArea<'a> {
    type State = TextAreaState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(self, area, buf, state);
    }
}

impl<'a> StatefulWidget for TextArea<'a> {
    type State = TextAreaState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(&self, area, buf, state);
    }
}

fn render_ref(widget: &TextArea<'_>, area: Rect, buf: &mut Buffer, state: &mut TextAreaState) {
    state.area = area;

    let (hscroll_area, vscroll_area, inner_area) = layout_scroll(
        area,
        widget.block.as_ref(),
        widget.hscroll.as_ref(),
        widget.vscroll.as_ref(),
    );
    state.inner = inner_area;
    if let Some(h_max_offset) = widget.h_max_offset {
        state.hscroll.set_max_offset(h_max_offset);
    }
    state.hscroll.set_page_len(state.inner.width as usize);
    state
        .vscroll
        .set_max_offset(state.line_len().saturating_sub(state.inner.height as usize));
    state.vscroll.set_page_len(state.inner.height as usize);

    widget.block.render_ref(area, buf);
    if let Some(hscroll) = widget.hscroll.as_ref() {
        hscroll.render_ref(hscroll_area, buf, &mut state.hscroll);
    }
    if let Some(vscroll) = widget.vscroll.as_ref() {
        vscroll.render_ref(vscroll_area, buf, &mut state.vscroll);
    }

    let area = state.inner;

    let select_style = if let Some(select_style) = widget.select_style {
        select_style
    } else {
        Style::default().on_yellow()
    };
    let style = widget.style;

    buf.set_style(area, style);

    let selection = state.selection();
    let mut styles = Vec::new();

    let mut line_iter = state
        .value
        .iter_scrolled((state.hscroll.offset(), state.vscroll.offset()));
    for row in 0..area.height {
        if let Some(mut line) = line_iter.next() {
            let mut col = 0;
            let mut cx = 0;
            loop {
                if col >= area.width {
                    break;
                }

                let tmp_str;
                let ch = if let Some(ch) = line.next() {
                    if let Some(ch) = ch.as_str() {
                        // filter control characters
                        let c0 = ch.chars().next();
                        if c0 >= Some('\x20') {
                            ch
                        } else {
                            " "
                        }
                    } else {
                        tmp_str = ch.to_string();
                        tmp_str.as_str()
                    }
                } else {
                    " "
                };

                // text based
                let (ox, oy) = state.offset();
                let tx = cx as usize + ox;
                let ty = row as usize + oy;

                let mut style = style;
                // text-styles
                state.styles_at((tx, ty), &mut styles);
                for idx in styles.iter().copied() {
                    let Some(s) = widget.text_style.get(idx) else {
                        panic!("invalid style nr: {}", idx);
                    };
                    style = style.patch(*s);
                }
                // selection
                if selection.contains((tx, ty)) {
                    style = style.patch(select_style);
                };

                let cell = buf.get_mut(area.x + col, area.y + row);
                cell.set_symbol(ch);
                cell.set_style(style);

                // extra cells for wide chars.
                let ww = unicode_display_width::width(ch) as u16;
                for x in 1..ww {
                    let cell = buf.get_mut(area.x + col + x, area.y + row);
                    cell.set_symbol(" ");
                    cell.set_style(style);
                }

                col += max(ww, 1);
                cx += 1;
            }
        } else {
            for col in 0..area.width {
                let cell = buf.get_mut(area.x + col, area.y + row);
                cell.set_symbol(" ");
            }
        }
    }
}

impl Default for TextAreaState {
    fn default() -> Self {
        let mut s = Self {
            focus: Default::default(),
            area: Default::default(),
            inner: Default::default(),
            mouse: Default::default(),
            value: core::InputCore::default(),
            hscroll: Default::default(),
            non_exhaustive: NonExhaustive,
            vscroll: Default::default(),
        };
        s.hscroll.set_max_offset(usize::MAX);
        s
    }
}

impl HasFocusFlag for TextAreaState {
    fn focus(&self) -> &FocusFlag {
        &self.focus
    }

    fn area(&self) -> Rect {
        self.area
    }
}

impl TextAreaState {
    /// New State.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Clear everything.
    #[inline]
    pub fn clear(&mut self) -> bool {
        self.value.clear()
    }

    /// Current offset for scrolling.
    #[inline]
    pub fn offset(&self) -> (usize, usize) {
        (self.hscroll.offset(), self.vscroll.offset())
    }

    /// Set the offset for scrolling.
    #[inline]
    pub fn set_offset(&mut self, offset: (usize, usize)) -> bool {
        let c = self.hscroll.set_offset(offset.0);
        let r = self.vscroll.set_offset(offset.1);
        r || c
    }

    /// Cursor position.
    #[inline]
    pub fn cursor(&self) -> (usize, usize) {
        self.value.cursor()
    }

    /// Set the cursor position.
    /// This doesn't scroll the cursor to a visible position.
    /// Use [TextAreaState::scroll_cursor_to_visible()] for that.
    #[inline]
    pub fn set_cursor(&mut self, cursor: (usize, usize), extend_selection: bool) -> bool {
        self.value.set_cursor(cursor, extend_selection)
    }

    /// Selection anchor.
    #[inline]
    pub fn anchor(&self) -> (usize, usize) {
        self.value.anchor()
    }

    /// Text value
    #[inline]
    pub fn value(&self) -> String {
        self.value.value()
    }

    /// Text value
    #[inline]
    pub fn value_range(&self, range: TextRange) -> Option<RopeSlice<'_>> {
        self.value.value_range(range)
    }

    /// Text as Bytes iterator.
    #[inline]
    pub fn value_as_bytes(&self) -> ropey::iter::Bytes<'_> {
        self.value.value_as_bytes()
    }

    /// Text as Bytes iterator.
    #[inline]
    pub fn value_as_chars(&self) -> ropey::iter::Chars<'_> {
        self.value.value_as_chars()
    }

    /// Set the text value.
    /// Resets all internal state.
    #[inline]
    pub fn set_value<S: AsRef<str>>(&mut self, s: S) {
        self.vscroll.set_offset(0);
        self.hscroll.set_offset(0);

        self.value.set_value(s);
    }

    /// Set the text value as a Rope.
    /// Resets all internal state.
    #[inline]
    pub fn set_value_rope(&mut self, s: Rope) {
        self.vscroll.set_offset(0);
        self.hscroll.set_offset(0);

        self.value.set_value_rope(s);
    }

    /// Empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.value.is_empty()
    }

    /// Line count.
    #[inline]
    pub fn line_len(&self) -> usize {
        self.value.len_lines()
    }

    /// Line width as grapheme count.
    #[inline]
    pub fn line_width(&self, n: usize) -> Option<usize> {
        self.value.line_width(n)
    }

    /// Grapheme iterator for a given line.
    /// This contains the \n at the end.
    #[inline]
    pub fn line(&self, n: usize) -> Option<RopeGraphemes<'_>> {
        self.value.line(n)
    }

    /// Has a selection?
    #[inline]
    pub fn has_selection(&self) -> bool {
        self.value.has_selection()
    }

    /// Current selection.
    #[inline]
    pub fn selection(&self) -> TextRange {
        self.value.selection()
    }

    /// Set the selection.
    #[inline]
    pub fn set_selection(&mut self, range: TextRange) -> bool {
        self.value.set_selection(range)
    }

    /// Select all.
    #[inline]
    pub fn select_all(&mut self) -> bool {
        self.value.select_all()
    }

    /// Selection.
    #[inline]
    pub fn selected_value(&self) -> Option<RopeSlice<'_>> {
        self.value.value_range(self.value.selection())
    }

    /// Clear all set styles.
    #[inline]
    pub fn clear_styles(&mut self) {
        self.value.clear_styles();
    }

    /// Add a style for a [TextRange]. The style-nr refers to one
    /// of the styles set with the widget.
    #[inline]
    pub fn add_style(&mut self, range: TextRange, style: usize) {
        self.value.add_style(range, style);
    }

    /// All styles active at the given position.
    #[inline]
    pub fn styles_at(&self, pos: (usize, usize), result: &mut Vec<usize>) {
        self.value.styles_at(pos, result)
    }

    /// Convert a byte position to a text area position.
    /// Uses grapheme based column indexes.
    #[inline]
    pub fn byte_pos(&self, byte: usize) -> Option<(usize, usize)> {
        self.value.byte_pos(byte)
    }

    /// Convert a text area position to a byte range.
    /// Uses grapheme based column indexes.
    /// Returns (byte-start, byte-end) of the grapheme at the given position.
    #[inline]
    pub fn byte_at(&self, pos: (usize, usize)) -> Option<(usize, usize)> {
        self.value.byte_at(pos)
    }

    /// Convert a char position to a text area position.
    /// Uses grapheme based column indexes.
    #[inline]
    pub fn char_pos(&self, byte: usize) -> Option<(usize, usize)> {
        self.value.char_pos(byte)
    }

    /// Convert a text area position to a char position.
    /// Uses grapheme based column indexes.
    #[inline]
    pub fn char_at(&self, pos: (usize, usize)) -> Option<usize> {
        self.value.char_at(pos)
    }

    /// Insert a character at the cursor position.
    /// Removes the selection and inserts the char.
    pub fn insert_char(&mut self, c: char) -> bool {
        if self.value.has_selection() {
            self.value.remove(self.value.selection());
        }
        self.value.insert_char(self.value.cursor(), c);
        self.scroll_cursor_to_visible();
        true
    }

    /// Insert a line break at the cursor position.
    pub fn insert_newline(&mut self) -> bool {
        if self.value.has_selection() {
            self.value.remove(self.value.selection());
        }
        self.value.insert_newline(self.value.cursor());
        self.scroll_cursor_to_visible();
        true
    }

    /// Deletes the given range.
    pub fn delete_range(&mut self, range: TextRange) -> bool {
        if !range.is_empty() {
            self.value.remove(range);
            self.scroll_cursor_to_visible();
            true
        } else {
            false
        }
    }

    /// Deletes the next char or the current selection.
    /// Returns true if there was any real change.
    pub fn delete_next_char(&mut self) -> bool {
        let range = if self.value.has_selection() {
            self.selection()
        } else {
            let (cx, cy) = self.value.cursor();
            let c_line_width = self.value.line_width(cy).expect("width");
            let c_last_line = self.value.len_lines() - 1;

            let (ex, ey) = if cy == c_last_line && cx == c_line_width {
                (c_line_width, c_last_line)
            } else if cy != c_last_line && cx == c_line_width {
                (0, cy + 1)
            } else {
                (cx + 1, cy)
            };
            TextRange::new((cx, cy), (ex, ey))
        };

        self.delete_range(range)
    }

    /// Deletes the previous char or the selection.
    /// Returns true if there was any real change.
    pub fn delete_prev_char(&mut self) -> bool {
        let range = if self.value.has_selection() {
            self.selection()
        } else {
            let (cx, cy) = self.value.cursor();
            let (sx, sy) = if cy == 0 && cx == 0 {
                (0, 0)
            } else if cy != 0 && cx == 0 {
                let prev_line_width = self.value.line_width(cy - 1).expect("line_width");
                (prev_line_width, cy - 1)
            } else {
                (cx - 1, cy)
            };

            TextRange::new((sx, sy), (cx, cy))
        };

        self.delete_range(range)
    }

    pub fn delete_next_word(&mut self) -> bool {
        if self.value.has_selection() {
            self.value
                .set_selection(TextRange::new(self.cursor(), self.cursor()));
        }

        let (cx, cy) = self.value.cursor();
        let (ex, ey) = self
            .value
            .next_word_boundary((cx, cy))
            .expect("valid_cursor");

        let range = TextRange::new((cx, cy), (ex, ey));
        if !range.is_empty() {
            self.value.remove(range);
            self.scroll_cursor_to_visible();
            true
        } else {
            false
        }
    }

    pub fn delete_prev_word(&mut self) -> bool {
        if self.value.has_selection() {
            self.value
                .set_selection(TextRange::new(self.cursor(), self.cursor()));
        }

        let (cx, cy) = self.value.cursor();
        let (sx, sy) = self
            .value
            .prev_word_boundary((cx, cy))
            .expect("valid_cursor");

        let range = TextRange::new((sx, sy), (cx, cy));
        if !range.is_empty() {
            self.value.remove(range);
            self.scroll_cursor_to_visible();
            true
        } else {
            false
        }
    }

    /// Move the cursor left. Scrolls the cursor to visible.
    /// Returns true if there was any real change.
    pub fn move_left(&mut self, n: usize, extend_selection: bool) -> bool {
        let (mut cx, mut cy) = self.value.cursor();

        if cx == 0 {
            if cy > 0 {
                cy = cy.saturating_sub(1);
                let Some(c_line_width) = self.value.line_width(cy) else {
                    panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
                };
                cx = c_line_width;
            }
        } else {
            cx = cx.saturating_sub(n);
        }

        self.value.set_move_col(Some(cx));
        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor right. Scrolls the cursor to visible.
    /// Returns true if there was any real change.
    pub fn move_right(&mut self, n: usize, extend_selection: bool) -> bool {
        let (mut cx, mut cy) = self.value.cursor();
        let Some(c_line_width) = self.value.line_width(cy) else {
            panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
        };

        if cx == c_line_width {
            if cy + 1 < self.value.len_lines() {
                cy += 1;
                cx = 0;
            }
        } else {
            cx = min(cx + n, c_line_width)
        }

        self.value.set_move_col(Some(cx));
        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor up. Scrolls the cursor to visible.
    /// Returns true if there was any real change.
    pub fn move_up(&mut self, n: usize, extend_selection: bool) -> bool {
        let (mut cx, mut cy) = self.value.cursor();
        let Some(c_line_width) = self.value.line_width(cy) else {
            panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
        };

        cy = cy.saturating_sub(n);
        if let Some(xx) = self.value.move_col() {
            cx = min(xx, c_line_width);
        } else {
            cx = min(cx, c_line_width);
        }

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor down. Scrolls the cursor to visible.
    /// Returns true if there was any real change.
    pub fn move_down(&mut self, n: usize, extend_selection: bool) -> bool {
        let (mut cx, mut cy) = self.value.cursor();
        let Some(c_line_width) = self.value.line_width(cy) else {
            panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
        };

        cy = min(cy + n, self.value.len_lines() - 1);
        if let Some(xx) = self.value.move_col() {
            cx = min(xx, c_line_width);
        } else {
            cx = min(cx, c_line_width);
        }

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the start of the line.
    /// Scrolls the cursor to visible.
    /// Returns true if there was any real change.
    pub fn move_to_line_start(&mut self, extend_selection: bool) -> bool {
        let (mut cx, cy) = self.value.cursor();

        cx = 'f: {
            if cx > 0 {
                let Some(line) = self.value.line(cy) else {
                    panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
                };
                for (c, ch) in line.enumerate() {
                    if ch.as_str() != Some(" ") {
                        if cx != c {
                            break 'f c;
                        } else {
                            break 'f 0;
                        }
                    }
                }
            }
            0
        };

        self.value.set_move_col(Some(cx));
        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the end of the line. Scrolls to visible, if
    /// necessary.
    /// Returns true if there was any real change.
    pub fn move_to_line_end(&mut self, extend_selection: bool) -> bool {
        let (cx, cy) = self.value.cursor();
        let Some(c_line_width) = self.value.line_width(cy) else {
            panic!("invalid_cursor: {:?} value {:?}", (cx, cy), self.value);
        };

        let cx = c_line_width;

        self.value.set_move_col(Some(cx));
        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the document start.
    pub fn move_to_start(&mut self, extend_selection: bool) -> bool {
        let cx = 0;
        let cy = 0;

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the document end.
    pub fn move_to_end(&mut self, extend_selection: bool) -> bool {
        let len = self.value.len_lines();

        let cx = 0;
        let cy = len - 1;

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the start of the visible area.
    pub fn move_to_screen_start(&mut self, extend_selection: bool) -> bool {
        let (ox, oy) = self.offset();

        let cx = ox;
        let cy = oy;

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Move the cursor to the end of the visible area.
    pub fn move_to_screen_end(&mut self, extend_selection: bool) -> bool {
        let (ox, oy) = self.offset();
        let len = self.value.len_lines();

        let cx = ox;
        let cy = min(oy + self.vertical_page() - 1, len - 1);

        let c = self.value.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    pub fn move_to_next_word(&mut self, extend_selection: bool) -> bool {
        let (cx, cy) = self.value.cursor();

        let (px, py) = self
            .value
            .next_word_boundary((cx, cy))
            .expect("valid_cursor");

        let c = self.value.set_cursor((px, py), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    pub fn move_to_prev_word(&mut self, extend_selection: bool) -> bool {
        let (cx, cy) = self.value.cursor();

        let (px, py) = self
            .value
            .prev_word_boundary((cx, cy))
            .expect("valid_cursor");

        let c = self.value.set_cursor((px, py), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }

    /// Converts from a widget relative screen coordinate to a grapheme index.
    /// Row is a row-index into the value, not a screen-row.
    /// x is the relative screen position.
    pub fn from_screen_col(&self, row: usize, x: usize) -> Option<usize> {
        let (mut cx, cy) = (0usize, row);
        let (ox, _oy) = self.offset();

        let line = self.line(cy)?;
        let mut test = 0;
        for c in line.skip(ox).filter(|v| v != "\n") {
            if test >= x {
                break;
            }

            test += if let Some(c) = c.as_str() {
                unicode_display_width::width(c) as usize
            } else {
                unicode_display_width::width(c.to_string().as_str()) as usize
            };

            cx += 1;
        }

        Some(cx + ox)
    }

    /// Converts a grapheme based position to a screen position
    /// relative to the widget area.
    pub fn to_screen_col(&self, pos: (usize, usize)) -> Option<u16> {
        let (px, py) = pos;
        let (ox, _oy) = self.offset();

        let mut sx = 0;
        let line = self.line(py)?;
        for c in line.skip(ox).filter(|v| v != "\n").take(px - ox) {
            sx += if let Some(c) = c.as_str() {
                unicode_display_width::width(c) as usize
            } else {
                unicode_display_width::width(c.to_string().as_str()) as usize
            };
        }

        Some(sx as u16)
    }

    /// Cursor position on the screen.
    pub fn screen_cursor(&self) -> Option<(u16, u16)> {
        if self.is_focused() {
            let (cx, cy) = self.value.cursor();
            let (ox, oy) = self.offset();

            if cy < oy {
                None
            } else if cy >= oy + self.inner.height as usize {
                None
            } else {
                let sy = cy - oy;
                if cx < ox {
                    None
                } else if cx > ox + self.inner.width as usize {
                    None
                } else {
                    let sx = self.to_screen_col((cx, cy)).expect("valid_cursor");

                    Some((self.inner.x + sx, self.inner.y + sy as u16))
                }
            }
        } else {
            None
        }
    }

    /// Set the cursor position from screen coordinates.
    ///
    /// The cursor positions are relative to the inner rect.
    /// They may be negative too, this allows setting the cursor
    /// to a position that is currently scrolled away.
    pub fn set_screen_cursor(&mut self, cursor: (i16, i16), extend_selection: bool) -> bool {
        let (scx, scy) = (cursor.0 as isize, cursor.1 as isize);
        let (ox, oy) = self.offset();

        let cy = min(max(oy as isize + scy, 0) as usize, self.line_len() - 1);
        let cx = if scx < 0 {
            max(ox as isize + scx, 0) as usize
        } else {
            if let Some(c) = self.from_screen_col(cy, scx as usize) {
                c
            } else {
                self.line_width(cy).expect("valid_line")
            }
        };

        let c = self.set_cursor((cx, cy), extend_selection);
        let s = self.scroll_cursor_to_visible();
        c || s
    }
}

impl TextAreaState {
    /// Maximum offset that is accessible with scrolling.
    ///
    /// This is shorter than the length of the content by whatever fills the last page.
    /// This is the base for the scrollbar content_length.
    pub fn vertical_max_offset(&self) -> usize {
        self.vscroll.max_offset()
    }

    /// Current vertical offset.
    pub fn vertical_offset(&self) -> usize {
        self.vscroll.offset()
    }

    /// Vertical page-size at the current offset.
    pub fn vertical_page(&self) -> usize {
        self.vscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn vertical_scroll(&self) -> usize {
        self.vscroll.scroll_by()
    }

    /// Maximum offset that is accessible with scrolling.
    ///
    /// This is currently set to usize::MAX.
    pub fn horizontal_max_offset(&self) -> usize {
        self.hscroll.max_offset()
    }

    /// Current horizontal offset.
    pub fn horizontal_offset(&self) -> usize {
        self.hscroll.offset()
    }

    /// Horizontal page-size at the current offset.
    pub fn horizontal_page(&self) -> usize {
        self.hscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn horizontal_scroll(&self) -> usize {
        self.hscroll.scroll_by()
    }

    /// Change the vertical offset.
    ///
    /// Due to overscroll it's possible that this is an invalid offset for the widget.
    /// The widget must deal with this situation.
    ///
    /// The widget returns true if the offset changed at all.
    #[allow(unused_assignments)]
    pub fn set_vertical_offset(&mut self, row_offset: usize) -> bool {
        self.vscroll.set_offset(row_offset)
    }

    /// Change the horizontal offset.
    ///
    /// Due to overscroll it's possible that this is an invalid offset for the widget.
    /// The widget must deal with this situation.
    ///
    /// The widget returns true if the offset changed at all.
    #[allow(unused_assignments)]
    pub fn set_horizontal_offset(&mut self, col_offset: usize) -> bool {
        self.hscroll.set_offset(col_offset)
    }

    /// Scroll to position.
    pub fn scroll_to_row(&mut self, pos: usize) -> bool {
        self.vscroll.set_offset(pos)
    }

    /// Scroll to position.
    pub fn scroll_to_col(&mut self, pos: usize) -> bool {
        self.hscroll.set_offset(pos)
    }

    /// Scrolling
    pub fn scroll_up(&mut self, delta: usize) -> bool {
        self.vscroll.scroll_up(delta)
    }

    /// Scrolling
    pub fn scroll_down(&mut self, delta: usize) -> bool {
        self.vscroll.scroll_down(delta)
    }

    /// Scrolling
    pub fn scroll_left(&mut self, delta: usize) -> bool {
        self.hscroll.scroll_left(delta)
    }

    /// Scrolling
    pub fn scroll_right(&mut self, delta: usize) -> bool {
        self.hscroll.scroll_right(delta)
    }
}

impl TextAreaState {
    /// Scroll that the cursor is visible.
    /// All move-fn do this automatically.
    fn scroll_cursor_to_visible(&mut self) -> bool {
        let old_offset = self.offset();

        let (cx, cy) = self.value.cursor();
        let (ox, oy) = self.offset();

        let noy = if cy < oy {
            cy
        } else if cy >= oy + self.inner.height as usize {
            cy.saturating_sub(self.inner.height as usize - 1)
        } else {
            oy
        };

        let nox = if cx < ox {
            cx
        } else if cx >= ox + self.inner.width as usize {
            cx.saturating_sub(self.inner.width as usize)
        } else {
            ox
        };

        self.set_offset((nox, noy));

        self.offset() != old_offset
    }
}

impl HandleEvent<crossterm::event::Event, FocusKeys, TextOutcome> for TextAreaState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: FocusKeys) -> TextOutcome {
        let mut r = if self.is_focused() {
            match event {
                ct_event!(key press c)
                | ct_event!(key press SHIFT-c)
                | ct_event!(key press CONTROL_ALT-c) => self.insert_char(*c).into(),
                ct_event!(keycode press Enter) => self.insert_newline().into(),
                ct_event!(keycode press Backspace) => self.delete_prev_char().into(),
                ct_event!(keycode press Delete) => self.delete_next_char().into(),
                ct_event!(keycode press CONTROL-Backspace) => self.delete_prev_word().into(),
                ct_event!(keycode press CONTROL-Delete) => self.delete_next_word().into(),

                ct_event!(key release _)
                | ct_event!(key release SHIFT-_)
                | ct_event!(key release CONTROL_ALT-_)
                | ct_event!(keycode release Enter)
                | ct_event!(keycode release Backspace)
                | ct_event!(keycode release Delete)
                | ct_event!(keycode release CONTROL-Backspace)
                | ct_event!(keycode release CONTROL-Delete) => TextOutcome::Unchanged,
                _ => TextOutcome::NotUsed,
            }
        } else {
            TextOutcome::NotUsed
        };
        // remap to TextChanged
        if r == TextOutcome::Changed {
            r = TextOutcome::TextChanged;
        }

        if r == TextOutcome::NotUsed {
            r = self.handle(event, ReadOnly);
        }
        r
    }
}

impl HandleEvent<crossterm::event::Event, ReadOnly, TextOutcome> for TextAreaState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: ReadOnly) -> TextOutcome {
        let mut r = if self.is_focused() {
            match event {
                ct_event!(keycode press Left) => self.move_left(1, false).into(),
                ct_event!(keycode press Right) => self.move_right(1, false).into(),
                ct_event!(keycode press Up) => self.move_up(1, false).into(),
                ct_event!(keycode press Down) => self.move_down(1, false).into(),
                ct_event!(keycode press PageUp) => self.move_up(self.vertical_page(), false).into(),
                ct_event!(keycode press PageDown) => {
                    self.move_down(self.vertical_page(), false).into()
                }
                ct_event!(keycode press Home) => self.move_to_line_start(false).into(),
                ct_event!(keycode press End) => self.move_to_line_end(false).into(),
                ct_event!(keycode press CONTROL-Left) => self.move_to_prev_word(false).into(),
                ct_event!(keycode press CONTROL-Right) => self.move_to_next_word(false).into(),
                ct_event!(keycode press CONTROL-Up) => false.into(),
                ct_event!(keycode press CONTROL-Down) => false.into(),
                ct_event!(keycode press CONTROL-PageUp) => self.move_to_screen_start(false).into(),
                ct_event!(keycode press CONTROL-PageDown) => self.move_to_screen_end(false).into(),
                ct_event!(keycode press CONTROL-Home) => self.move_to_start(false).into(),
                ct_event!(keycode press CONTROL-End) => self.move_to_end(false).into(),

                ct_event!(keycode press ALT-Left) => self.scroll_left(1).into(),
                ct_event!(keycode press ALT-Right) => self.scroll_right(1).into(),
                ct_event!(keycode press ALT-Up) => self.scroll_up(1).into(),
                ct_event!(keycode press ALT-Down) => self.scroll_down(1).into(),
                ct_event!(keycode press ALT-PageUp) => {
                    self.scroll_up(max(self.vertical_page() / 2, 1)).into()
                }
                ct_event!(keycode press ALT-PageDown) => {
                    self.scroll_down(max(self.vertical_page() / 2, 1)).into()
                }
                ct_event!(keycode press ALT_SHIFT-PageUp) => {
                    self.scroll_left(max(self.horizontal_page() / 5, 1)).into()
                }
                ct_event!(keycode press ALT_SHIFT-PageDown) => {
                    self.scroll_right(max(self.horizontal_page() / 5, 1)).into()
                }

                ct_event!(keycode press SHIFT-Left) => self.move_left(1, true).into(),
                ct_event!(keycode press SHIFT-Right) => self.move_right(1, true).into(),
                ct_event!(keycode press SHIFT-Up) => self.move_up(1, true).into(),
                ct_event!(keycode press SHIFT-Down) => self.move_down(1, true).into(),
                ct_event!(keycode press SHIFT-PageUp) => {
                    self.move_up(self.vertical_page(), true).into()
                }
                ct_event!(keycode press SHIFT-PageDown) => {
                    self.move_down(self.vertical_page(), true).into()
                }
                ct_event!(keycode press SHIFT-Home) => self.move_to_line_start(true).into(),
                ct_event!(keycode press SHIFT-End) => self.move_to_line_end(true).into(),
                ct_event!(keycode press CONTROL_SHIFT-Left) => self.move_to_prev_word(true).into(),
                ct_event!(keycode press CONTROL_SHIFT-Right) => self.move_to_next_word(true).into(),
                ct_event!(key press CONTROL-'a') => self.select_all().into(),

                ct_event!(keycode release Left)
                | ct_event!(keycode release Right)
                | ct_event!(keycode release Up)
                | ct_event!(keycode release Down)
                | ct_event!(keycode release PageUp)
                | ct_event!(keycode release PageDown)
                | ct_event!(keycode release Home)
                | ct_event!(keycode release End)
                | ct_event!(keycode release CONTROL-Left)
                | ct_event!(keycode release CONTROL-Right)
                | ct_event!(keycode release CONTROL-Up)
                | ct_event!(keycode release CONTROL-Down)
                | ct_event!(keycode release CONTROL-PageUp)
                | ct_event!(keycode release CONTROL-PageDown)
                | ct_event!(keycode release CONTROL-Home)
                | ct_event!(keycode release CONTROL-End)
                | ct_event!(keycode release ALT-Left)
                | ct_event!(keycode release ALT-Right)
                | ct_event!(keycode release ALT-Up)
                | ct_event!(keycode release ALT-Down)
                | ct_event!(keycode release ALT-PageUp)
                | ct_event!(keycode release ALT-PageDown)
                | ct_event!(keycode release ALT_SHIFT-PageUp)
                | ct_event!(keycode release ALT_SHIFT-PageDown)
                | ct_event!(keycode release SHIFT-Left)
                | ct_event!(keycode release SHIFT-Right)
                | ct_event!(keycode release SHIFT-Up)
                | ct_event!(keycode release SHIFT-Down)
                | ct_event!(keycode release SHIFT-PageUp)
                | ct_event!(keycode release SHIFT-PageDown)
                | ct_event!(keycode release SHIFT-Home)
                | ct_event!(keycode release SHIFT-End)
                | ct_event!(keycode release CONTROL_SHIFT-Left)
                | ct_event!(keycode release CONTROL_SHIFT-Right)
                | ct_event!(key release CONTROL-'a') => TextOutcome::Unchanged,
                _ => TextOutcome::NotUsed,
            }
        } else {
            TextOutcome::NotUsed
        };

        if r == TextOutcome::NotUsed {
            r = self.handle(event, MouseOnly);
        }
        r
    }
}

impl HandleEvent<crossterm::event::Event, MouseOnly, TextOutcome> for TextAreaState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: MouseOnly) -> TextOutcome {
        flow!(match event {
            ct_event!(mouse any for m)
                if self.mouse.drag(self.inner, m)
                    || self.mouse.drag2(self.inner, m, KeyModifiers::ALT) =>
            {
                let cx = m.column as i16 - self.inner.x as i16;
                let cy = m.row as i16 - self.inner.y as i16;
                self.set_screen_cursor((cx, cy), true).into()
            }
            // TODO: not happy with this one. Think again.
            // ct_event!(mouse any for m) if self.mouse.doubleclick(self.inner, m) => {
            //     let ty = self.offset().1 + m.row as usize - self.inner.y as usize;
            //     if let Some(tx) =
            //         self.from_screen_col(ty, m.column as usize - self.inner.x as usize)
            //     {
            //         let b0 = self.value.prev_word_boundary((tx, ty)).expect("position");
            //         let b1 = self.value.next_word_boundary((tx, ty)).expect("position");
            //         self.set_selection(TextRange::new(b0, b1)).into()
            //     } else {
            //         TextOutcome::Unchanged
            //     }
            // }
            ct_event!(mouse down Left for column,row) => {
                if self.inner.contains((*column, *row).into()) {
                    let cx = (column - self.inner.x) as i16;
                    let cy = (row - self.inner.y) as i16;
                    self.set_screen_cursor((cx, cy), false).into()
                } else {
                    TextOutcome::NotUsed
                }
            }
            ct_event!(mouse down ALT-Left for column,row) => {
                if self.inner.contains((*column, *row).into()) {
                    let cx = (column - self.inner.x) as i16;
                    let cy = (row - self.inner.y) as i16;
                    self.set_screen_cursor((cx, cy), true).into()
                } else {
                    TextOutcome::NotUsed
                }
            }
            _ => TextOutcome::NotUsed,
        });

        let r = match ScrollArea(self.inner, Some(&mut self.hscroll), Some(&mut self.vscroll))
            .handle(event, MouseOnly)
        {
            ScrollOutcome::Up(v) => self.scroll_up(v),
            ScrollOutcome::Down(v) => self.scroll_down(v),
            ScrollOutcome::Left(v) => self.scroll_left(v),
            ScrollOutcome::Right(v) => self.scroll_right(v),
            ScrollOutcome::VPos(v) => self.set_vertical_offset(v),
            ScrollOutcome::HPos(v) => self.set_horizontal_offset(v),
            _ => false,
        };
        if r {
            return TextOutcome::Changed;
        }

        TextOutcome::NotUsed
    }
}

/// Handle all events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_events(
    state: &mut TextAreaState,
    focus: bool,
    event: &crossterm::event::Event,
) -> TextOutcome {
    state.focus.set(focus);
    state.handle(event, FocusKeys)
}

/// Handle only navigation events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_readonly_events(
    state: &mut TextAreaState,
    focus: bool,
    event: &crossterm::event::Event,
) -> TextOutcome {
    state.focus.set(focus);
    state.handle(event, ReadOnly)
}

/// Handle only mouse-events.
pub fn handle_mouse_events(
    state: &mut TextAreaState,
    event: &crossterm::event::Event,
) -> TextOutcome {
    state.handle(event, MouseOnly)
}

pub mod graphemes {
    use ropey::iter::Chunks;
    use ropey::RopeSlice;
    use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};

    /// Length as grapheme count.
    pub fn rope_len(r: RopeSlice<'_>) -> usize {
        let it = RopeGraphemes::new(r);
        it.filter(|c| c != "\n").count()
    }

    /// An implementation of a graphemes iterator, for iterating over
    /// the graphemes of a RopeSlice.
    #[derive(Debug)]
    pub struct RopeGraphemes<'a> {
        text: RopeSlice<'a>,
        chunks: Chunks<'a>,
        cur_chunk: &'a str,
        cur_chunk_start: usize,
        cursor: GraphemeCursor,
    }

    impl<'a> RopeGraphemes<'a> {
        pub fn new(slice: RopeSlice<'a>) -> RopeGraphemes<'a> {
            let mut chunks = slice.chunks();
            let first_chunk = chunks.next().unwrap_or("");
            RopeGraphemes {
                text: slice,
                chunks,
                cur_chunk: first_chunk,
                cur_chunk_start: 0,
                cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
            }
        }
    }

    impl<'a> Iterator for RopeGraphemes<'a> {
        type Item = RopeSlice<'a>;

        fn next(&mut self) -> Option<RopeSlice<'a>> {
            let a = self.cursor.cur_cursor();
            let b;
            loop {
                match self
                    .cursor
                    .next_boundary(self.cur_chunk, self.cur_chunk_start)
                {
                    Ok(None) => {
                        return None;
                    }
                    Ok(Some(n)) => {
                        b = n;
                        break;
                    }
                    Err(GraphemeIncomplete::NextChunk) => {
                        self.cur_chunk_start += self.cur_chunk.len();
                        self.cur_chunk = self.chunks.next().unwrap_or("");
                    }
                    Err(GraphemeIncomplete::PreContext(idx)) => {
                        let (chunk, byte_idx, _, _) =
                            self.text.chunk_at_byte(idx.saturating_sub(1));
                        self.cursor.provide_context(chunk, byte_idx);
                    }
                    _ => unreachable!(),
                }
            }

            if a < self.cur_chunk_start {
                let a_char = self.text.byte_to_char(a);
                let b_char = self.text.byte_to_char(b);

                Some(self.text.slice(a_char..b_char))
            } else {
                let a2 = a - self.cur_chunk_start;
                let b2 = b - self.cur_chunk_start;
                Some((&self.cur_chunk[a2..b2]).into())
            }
        }
    }

    /// An implementation of a graphemes iterator, for iterating over
    /// the graphemes of a RopeSlice.
    #[derive(Debug)]
    pub struct RopeGraphemesIdx<'a> {
        text: RopeSlice<'a>,
        chunks: Chunks<'a>,
        cur_chunk: &'a str,
        cur_chunk_start: usize,
        cursor: GraphemeCursor,
    }

    impl<'a> RopeGraphemesIdx<'a> {
        pub fn new(slice: RopeSlice<'a>) -> RopeGraphemesIdx<'a> {
            let mut chunks = slice.chunks();
            let first_chunk = chunks.next().unwrap_or("");
            RopeGraphemesIdx {
                text: slice,
                chunks,
                cur_chunk: first_chunk,
                cur_chunk_start: 0,
                cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
            }
        }
    }

    impl<'a> Iterator for RopeGraphemesIdx<'a> {
        type Item = ((usize, usize), RopeSlice<'a>);

        fn next(&mut self) -> Option<((usize, usize), RopeSlice<'a>)> {
            let a = self.cursor.cur_cursor();
            let b;
            loop {
                match self
                    .cursor
                    .next_boundary(self.cur_chunk, self.cur_chunk_start)
                {
                    Ok(None) => {
                        return None;
                    }
                    Ok(Some(n)) => {
                        b = n;
                        break;
                    }
                    Err(GraphemeIncomplete::NextChunk) => {
                        self.cur_chunk_start += self.cur_chunk.len();
                        self.cur_chunk = self.chunks.next().unwrap_or("");
                    }
                    Err(GraphemeIncomplete::PreContext(idx)) => {
                        let (chunk, byte_idx, _, _) =
                            self.text.chunk_at_byte(idx.saturating_sub(1));
                        self.cursor.provide_context(chunk, byte_idx);
                    }
                    _ => unreachable!(),
                }
            }

            if a < self.cur_chunk_start {
                let a_char = self.text.byte_to_char(a);
                let b_char = self.text.byte_to_char(b);

                Some(((a, b), self.text.slice(a_char..b_char)))
            } else {
                let a2 = a - self.cur_chunk_start;
                let b2 = b - self.cur_chunk_start;
                Some(((a, b), (&self.cur_chunk[a2..b2]).into()))
            }
        }
    }
}

pub mod core {
    use crate::textarea::graphemes::{rope_len, RopeGraphemesIdx};
    #[allow(unused_imports)]
    use log::debug;
    use ropey::iter::Lines;
    use ropey::{Rope, RopeSlice};
    use std::cmp::{min, Ordering};
    use std::fmt::{Debug, Formatter};
    use std::iter::Skip;
    use std::mem;
    use std::slice::IterMut;

    pub use crate::textarea::graphemes::RopeGraphemes;

    /// Core for text editing.
    #[derive(Debug, Default, Clone)]
    pub struct InputCore {
        value: Rope,

        styles: StyleMap,

        /// Scroll offset
        // offset: (usize, usize),

        /// Secondary column, remembered for moving up/down.
        move_col: Option<usize>,
        /// Cursor
        cursor: (usize, usize),
        /// Anchor for the selection.
        anchor: (usize, usize),
    }

    /// Range for text ranges.
    #[derive(Default, PartialEq, Eq, Clone, Copy)]
    pub struct TextRange {
        pub start: (usize, usize),
        pub end: (usize, usize),
    }

    #[derive(Debug, Default, Clone)]
    struct StyleMap {
        /// Vec of (range, style-idx)
        styles: Vec<(TextRange, usize)>,
    }

    #[derive(Debug)]
    pub struct ScrolledIter<'a> {
        lines: Lines<'a>,
        offset: usize,
    }

    impl Debug for TextRange {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "TextRange  {}|{}-{}|{}",
                self.start.0, self.start.1, self.end.0, self.end.1
            )
        }
    }

    impl TextRange {
        /// New text range.
        ///
        /// Panic
        /// Panics if start > end.
        pub fn new(start: (usize, usize), end: (usize, usize)) -> Self {
            // reverse the args, then it works.
            if (start.1, start.0) > (end.1, end.0) {
                panic!("start {:?} > end {:?}", start, end);
            }
            TextRange { start, end }
        }

        /// Start position
        #[inline]
        pub fn start(&self) -> (usize, usize) {
            self.start
        }

        /// End position
        #[inline]
        pub fn end(&self) -> (usize, usize) {
            self.end
        }

        /// Empty range
        #[inline]
        pub fn is_empty(&self) -> bool {
            self.start == self.end
        }

        /// Range contains the given position.
        #[inline]
        pub fn contains(&self, pos: (usize, usize)) -> bool {
            self.ordering(pos) == Ordering::Equal
        }

        /// Range contains the other range.
        #[inline(always)]
        pub fn contains_range(&self, range: TextRange) -> bool {
            self.ordering(range.start) == Ordering::Equal
                && self.ordering_inclusive(range.end) == Ordering::Equal
        }

        /// What place is the range respective to the given position.
        #[inline(always)]
        #[allow(clippy::comparison_chain)]
        pub fn ordering(&self, pos: (usize, usize)) -> Ordering {
            if pos.1 < self.start.1 {
                return Ordering::Greater;
            } else if pos.1 == self.start.1 {
                if pos.0 < self.start.0 {
                    return Ordering::Greater;
                }
            }

            if pos.1 < self.end.1 {
                return Ordering::Equal;
            } else if pos.1 == self.end.1 {
                if pos.0 < self.end.0 {
                    return Ordering::Equal;
                }
            }

            Ordering::Less

            // SURPRISE: contrary to ordering_inclusive the below
            //           takes the same time as the above in debug mode.

            // // reverse the args, then tuple cmp it works.
            // if (pos.1, pos.0) < (self.start.1, self.start.0) {
            //     Ordering::Greater
            // } else if (pos.1, pos.0) < (self.end.1, self.end.0) {
            //     Ordering::Equal
            // } else {
            //     Ordering::Less
            // }
        }

        /// What place is the range respective to the given position.
        /// This one includes the `range.end`.
        #[inline(always)]
        #[allow(clippy::comparison_chain)]
        pub fn ordering_inclusive(&self, pos: (usize, usize)) -> Ordering {
            if pos.1 < self.start.1 {
                return Ordering::Greater;
            } else if pos.1 == self.start.1 {
                if pos.0 < self.start.0 {
                    return Ordering::Greater;
                }
            }

            if pos.1 < self.end.1 {
                return Ordering::Equal;
            } else if pos.1 == self.end.1 {
                if pos.0 <= self.end.0 {
                    return Ordering::Equal;
                }
            }

            Ordering::Less

            // SURPRISE: above is pretty much faster than that: ???
            //           at least in debug mode...

            // // reverse the args, then tuple cmp it works.
            // if (pos.1, pos.0) < (self.start.1, self.start.0) {
            //     Ordering::Greater
            // } else if (pos.1, pos.0) <= (self.end.1, self.end.0) {
            //     Ordering::Equal
            // } else {
            //     Ordering::Less
            // }
        }

        /// Modify all positions in place.
        #[inline]
        pub fn expand_all(&self, it: Skip<IterMut<'_, (TextRange, usize)>>) {
            for (r, _s) in it {
                self._expand(&mut r.start);
                self._expand(&mut r.end);
            }
        }

        /// Modify all positions in place.
        #[inline]
        pub fn shrink_all(&self, it: Skip<IterMut<'_, (TextRange, usize)>>) {
            for (r, _s) in it {
                self._shrink(&mut r.start);
                self._shrink(&mut r.end);
            }
        }

        /// Return the modified position, as if this range expanded from its
        /// start to its full expansion.
        #[inline]
        pub fn expand(&self, pos: (usize, usize)) -> (usize, usize) {
            let mut tmp = pos;
            self._expand(&mut tmp);
            tmp
        }

        /// Return the modified position, if this range would shrink to nothing.
        #[inline]
        pub fn shrink(&self, pos: (usize, usize)) -> (usize, usize) {
            let mut tmp = pos;
            self._shrink(&mut tmp);
            tmp
        }

        #[inline(always)]
        #[allow(clippy::comparison_chain)]
        fn _expand(&self, pos: &mut (usize, usize)) {
            let delta_lines = self.end.1 - self.start.1;

            // comparing only the starting position.
            // the range doesn't exist yet.
            // have to flip the positions for tuple comparison
            match (self.start.1, self.start.0).cmp(&(pos.1, pos.0)) {
                Ordering::Greater => {
                    // noop
                }
                Ordering::Equal => {
                    *pos = self.end;
                }
                Ordering::Less => {
                    if pos.1 > self.start.1 {
                        pos.1 += delta_lines;
                    } else if pos.1 == self.start.1 {
                        if pos.0 >= self.start.0 {
                            pos.0 = pos.0 - self.start.0 + self.end.0;
                            pos.1 += delta_lines;
                        }
                    }
                }
            }
        }

        /// Return the modified position, if this range would shrink to nothing.
        #[inline(always)]
        #[allow(clippy::comparison_chain)]
        fn _shrink(&self, pos: &mut (usize, usize)) {
            let delta_lines = self.end.1 - self.start.1;
            match self.ordering_inclusive(*pos) {
                Ordering::Greater => {
                    // noop
                }
                Ordering::Equal => {
                    *pos = self.start;
                }
                Ordering::Less => {
                    if pos.1 > self.end.1 {
                        pos.1 -= delta_lines;
                    } else if pos.1 == self.end.1 {
                        if pos.0 >= self.end.0 {
                            pos.0 = pos.0 - self.end.0 + self.start.0;
                            pos.1 -= delta_lines;
                        }
                    }
                }
            }
        }
    }

    // This needs its own impl, because the order is exactly wrong.
    // For any sane range I'd need (row,col) but what I got is (col,row).
    // Need this to conform with the rest of ratatui ...
    impl PartialOrd for TextRange {
        #[allow(clippy::comparison_chain)]
        #[allow(clippy::non_canonical_partial_ord_impl)]
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            // reverse the args, then it works.
            let start = (self.start.1, self.start.0);
            let end = (self.end.1, self.end.0);
            let ostart = (other.start.1, other.start.0);
            let oend = (other.end.1, other.end.0);

            if start < ostart {
                Some(Ordering::Less)
            } else if start > ostart {
                Some(Ordering::Greater)
            } else {
                if end < oend {
                    Some(Ordering::Less)
                } else if end > oend {
                    Some(Ordering::Greater)
                } else {
                    Some(Ordering::Equal)
                }
            }
        }
    }

    impl Ord for TextRange {
        fn cmp(&self, other: &Self) -> Ordering {
            self.partial_cmp(other).expect("order")
        }
    }

    impl StyleMap {
        /// Remove all styles.
        pub(crate) fn clear_styles(&mut self) {
            self.styles.clear();
        }

        /// Add a text-style for a range.
        ///
        /// The same range can be added again with a different style.
        /// Overlapping regions get the merged style.
        pub(crate) fn add_style(&mut self, range: TextRange, style: usize) {
            let stylemap = (range, style);
            match self.styles.binary_search(&stylemap) {
                Ok(_) => {
                    // noop
                }
                Err(idx) => {
                    self.styles.insert(idx, stylemap);
                }
            }
        }

        /// Find all styles
        pub(crate) fn styles_after_mut(
            &mut self,
            pos: (usize, usize),
        ) -> Skip<IterMut<'_, (TextRange, usize)>> {
            let first = match self.styles.binary_search_by(|v| v.0.ordering(pos)) {
                Ok(mut i) => {
                    // binary-search found *some* matching style, we need all of them.
                    // this finds the first one.
                    loop {
                        if i == 0 {
                            break;
                        }
                        if !self.styles[i - 1].0.contains(pos) {
                            break;
                        }
                        i -= 1;
                    }
                    i
                }
                Err(i) => i,
            };

            self.styles.iter_mut().skip(first)
        }

        /// Find all styles for the given position.
        ///
        pub(crate) fn styles_at(&self, pos: (usize, usize), result: &mut Vec<usize>) {
            match self.styles.binary_search_by(|v| v.0.ordering(pos)) {
                Ok(mut i) => {
                    // binary-search found *some* matching style, we need all of them.
                    // this finds the first one.
                    loop {
                        if i == 0 {
                            break;
                        }
                        if !self.styles[i - 1].0.contains(pos) {
                            break;
                        }
                        i -= 1;
                    }

                    // collect all matching styles.
                    result.clear();
                    for i in i..self.styles.len() {
                        if self.styles[i].0.contains(pos) {
                            result.push(self.styles[i].1);
                        } else {
                            break;
                        }
                    }
                }
                Err(_) => result.clear(),
            }
        }
    }

    impl<'a> Iterator for ScrolledIter<'a> {
        type Item = Skip<RopeGraphemes<'a>>;

        fn next(&mut self) -> Option<Self::Item> {
            let s = self.lines.next()?;
            Some(RopeGraphemes::new(s).skip(self.offset))
        }
    }

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

        // /// Set the text offset as (col,row).
        // pub fn set_offset(&mut self, mut offset: (usize, usize)) -> bool {
        //     let old_offset = self.offset;
        //
        //     let (ox, oy) = offset;
        //     let oy = min(oy, self.len_lines() - 1);
        //     offset = (ox, oy);
        //
        //     self.offset = offset;
        //
        //     self.offset != old_offset
        // }
        //
        // /// Text offset as (col,row)
        // #[inline]
        // pub fn offset(&self) -> (usize, usize) {
        //     self.offset
        // }

        /// Extra column information for cursor movement.
        /// The cursor position is capped to the current line length, so if you
        /// move up one row, you might end at a position left of the current column.
        /// If you move up once more you want to return to the original position.
        /// That's what is stored here.
        #[inline]
        pub fn set_move_col(&mut self, col: Option<usize>) {
            self.move_col = col;
        }

        /// Extra column information for cursor movement.
        #[inline]
        pub fn move_col(&mut self) -> Option<usize> {
            self.move_col
        }

        /// Set the cursor position.
        /// The value is capped to the number of text lines and the line-width.
        /// Returns true, if the cursor actually changed.
        pub fn set_cursor(&mut self, mut cursor: (usize, usize), extend_selection: bool) -> bool {
            let old_cursor = self.cursor;
            let old_anchor = self.anchor;

            let (mut cx, mut cy) = cursor;
            cy = min(cy, self.len_lines() - 1);
            cx = min(cx, self.line_width(cy).expect("valid_line"));

            cursor = (cx, cy);

            self.cursor = cursor;

            if !extend_selection {
                self.anchor = cursor;
            }

            old_cursor != self.cursor || old_anchor != self.anchor
        }

        /// Cursor position.
        #[inline]
        pub fn cursor(&self) -> (usize, usize) {
            self.cursor
        }

        /// Selection anchor.
        #[inline]
        pub fn anchor(&self) -> (usize, usize) {
            self.anchor
        }

        /// Set the text.
        /// Resets the selection and any styles.
        pub fn set_value<S: AsRef<str>>(&mut self, s: S) {
            self.value = Rope::from_str(s.as_ref());
            self.cursor = (0, 0);
            self.anchor = (0, 0);
            self.move_col = None;
            self.styles.clear_styles();
        }

        /// Set the text value as a Rope.
        /// Resets all internal state.
        #[inline]
        pub fn set_value_rope(&mut self, s: Rope) {
            self.value = s;
            self.cursor = (0, 0);
            self.anchor = (0, 0);
            self.move_col = None;
            self.styles.clear_styles();
        }

        /// Text value.
        #[inline]
        pub fn value(&self) -> String {
            String::from(&self.value)
        }

        /// A range of the text as RopeSlice.
        pub fn value_range(&self, range: TextRange) -> Option<RopeSlice<'_>> {
            let s = self.char_at(range.start)?;
            let e = self.char_at(range.end)?;
            Some(self.value.slice(s..e))
        }

        /// Value as Bytes iterator.
        pub fn value_as_bytes(&self) -> ropey::iter::Bytes<'_> {
            self.value.bytes()
        }

        /// Value as Chars iterator.
        pub fn value_as_chars(&self) -> ropey::iter::Chars<'_> {
            self.value.chars()
        }

        /// Clear styles.
        #[inline]
        pub fn clear_styles(&mut self) {
            self.styles.clear_styles();
        }

        /// Add a style for the given range.
        ///
        /// What is given here is the index into the Vec with the actual Styles.
        /// Those are set at the widget.
        #[inline]
        pub fn add_style(&mut self, range: TextRange, style: usize) {
            self.styles.add_style(range, style);
        }

        /// Style map.
        #[inline]
        pub fn styles(&self) -> &[(TextRange, usize)] {
            &self.styles.styles
        }

        /// Finds all styles for the given position.
        ///
        /// Returns the indexes into the style vec.
        #[inline]
        pub fn styles_at(&self, pos: (usize, usize), result: &mut Vec<usize>) {
            self.styles.styles_at(pos, result)
        }

        /// Returns a line as an iterator over the graphemes for the line.
        /// This contains the \n at the end.
        pub fn line(&self, n: usize) -> Option<RopeGraphemes<'_>> {
            let mut lines = self.value.get_lines_at(n)?;
            let line = lines.next();
            if let Some(line) = line {
                Some(RopeGraphemes::new(line))
            } else {
                Some(RopeGraphemes::new(RopeSlice::from("")))
            }
        }

        /// Returns a line as an iterator over the graphemes for the line.
        /// This contains the \n at the end.
        pub fn line_idx(&self, n: usize) -> Option<RopeGraphemesIdx<'_>> {
            let mut lines = self.value.get_lines_at(n)?;
            let line = lines.next();
            if let Some(line) = line {
                Some(RopeGraphemesIdx::new(line))
            } else {
                Some(RopeGraphemesIdx::new(RopeSlice::from("")))
            }
        }

        /// Line width as grapheme count.
        pub fn line_width(&self, n: usize) -> Option<usize> {
            let mut lines = self.value.get_lines_at(n)?;
            let line = lines.next();
            if let Some(line) = line {
                Some(rope_len(line))
            } else {
                Some(0)
            }
        }

        /// Number of lines.
        #[inline]
        pub fn len_lines(&self) -> usize {
            self.value.len_lines()
        }

        /// Reset.
        #[inline]
        pub fn clear(&mut self) -> bool {
            if self.is_empty() {
                false
            } else {
                self.set_value("");
                true
            }
        }

        /// Empty.
        #[inline]
        pub fn is_empty(&self) -> bool {
            self.value.len_bytes() == 0
        }

        /// Any text selection.
        #[inline]
        pub fn has_selection(&self) -> bool {
            self.anchor != self.cursor
        }

        #[inline]
        pub fn set_selection(&mut self, range: TextRange) -> bool {
            let old_selection = self.selection();

            self.set_cursor(range.start, false);
            self.set_cursor(range.end, true);

            old_selection != self.selection()
        }

        #[inline]
        pub fn select_all(&mut self) -> bool {
            let old_selection = self.selection();

            self.set_cursor((0, 0), false);
            let last = self.len_lines() - 1;
            let last_width = self.line_width(last).expect("valid_last_line");
            self.set_cursor((last_width, last), true);

            old_selection != self.selection()
        }

        /// Returns the selection as TextRange.
        pub fn selection(&self) -> TextRange {
            #[allow(clippy::comparison_chain)]
            if self.cursor.1 < self.anchor.1 {
                TextRange {
                    start: self.cursor,
                    end: self.anchor,
                }
            } else if self.cursor.1 > self.anchor.1 {
                TextRange {
                    start: self.anchor,
                    end: self.cursor,
                }
            } else {
                if self.cursor.0 < self.anchor.0 {
                    TextRange {
                        start: self.cursor,
                        end: self.anchor,
                    }
                } else {
                    TextRange {
                        start: self.anchor,
                        end: self.cursor,
                    }
                }
            }
        }

        /// Iterate over the text, shifted by the offset.
        #[inline]
        pub fn iter_scrolled(&self, offset: (usize, usize)) -> ScrolledIter<'_> {
            let Some(l) = self.value.get_lines_at(offset.1) else {
                panic!("invalid offset {:?} value {:?}", offset, self.value);
            };
            ScrolledIter {
                lines: l,
                offset: offset.0,
            }
        }

        /// Find next word.
        pub fn next_word_boundary(&self, pos: (usize, usize)) -> Option<(usize, usize)> {
            let mut char_pos = self.char_at(pos)?;

            let chars_after = self.value.slice(char_pos..);
            let mut it = chars_after.chars_at(0);
            let mut init = true;
            loop {
                let Some(c) = it.next() else {
                    break;
                };

                if init {
                    if !c.is_whitespace() {
                        init = false;
                    }
                } else {
                    if c.is_whitespace() {
                        break;
                    }
                }

                char_pos += 1;
            }

            self.char_pos(char_pos)
        }

        /// Find prev word.
        pub fn prev_word_boundary(&self, pos: (usize, usize)) -> Option<(usize, usize)> {
            let mut char_pos = self.char_at(pos)?;

            let chars_before = self.value.slice(..char_pos);
            let mut it = chars_before.chars_at(chars_before.len_chars());
            let mut init = true;
            loop {
                let Some(c) = it.prev() else {
                    break;
                };

                if init {
                    if !c.is_whitespace() {
                        init = false;
                    }
                } else {
                    if c.is_whitespace() {
                        break;
                    }
                }

                char_pos -= 1;
            }

            self.char_pos(char_pos)
        }

        /// Len in chars
        pub fn len_chars(&self) -> usize {
            self.value.len_chars()
        }

        /// Len in bytes
        pub fn len_bytes(&self) -> usize {
            self.value.len_bytes()
        }

        /// Char position to grapheme position.
        pub fn char_pos(&self, char_pos: usize) -> Option<(usize, usize)> {
            let Ok(byte_pos) = self.value.try_char_to_byte(char_pos) else {
                return None;
            };
            self.byte_pos(byte_pos)
        }

        /// Byte position to grapheme position.
        pub fn byte_pos(&self, byte: usize) -> Option<(usize, usize)> {
            let Ok(y) = self.value.try_byte_to_line(byte) else {
                return None;
            };
            let mut x = 0;
            let byte_y = self.value.try_line_to_byte(y).expect("valid_y");

            let mut it_line = self.line_idx(y).expect("valid_y");
            loop {
                let Some(((sb, _eb), _cc)) = it_line.next() else {
                    break;
                };
                if byte_y + sb >= byte {
                    break;
                }
                x += 1;
            }

            Some((x, y))
        }

        /// Grapheme position to byte position.
        /// This is the (start,end) position of the single grapheme after pos.
        pub fn byte_at(&self, pos: (usize, usize)) -> Option<(usize, usize)> {
            let Ok(line_byte) = self.value.try_line_to_byte(pos.1) else {
                return None;
            };

            let len_bytes = self.value.len_bytes();
            let mut it_line = self.line_idx(pos.1).expect("valid_line");
            let mut x = -1isize;
            let mut last_eb = 0;
            loop {
                let (sb, eb, last) = if let Some((v, _)) = it_line.next() {
                    x += 1;
                    last_eb = v.1;
                    (v.0, v.1, false)
                } else {
                    (last_eb, last_eb, true)
                };

                if pos.0 == x as usize {
                    return Some((line_byte + sb, line_byte + eb));
                }
                // one past the end is ok.
                if pos.0 == (x + 1) as usize && line_byte + eb == len_bytes {
                    return Some((line_byte + eb, line_byte + eb));
                }
                if last {
                    return None;
                }
            }
        }

        /// Returns the first char position for the grapheme position.
        pub fn char_at(&self, pos: (usize, usize)) -> Option<usize> {
            let (byte_pos, _) = self.byte_at(pos)?;
            Some(
                self.value
                    .try_byte_to_char(byte_pos)
                    .expect("valid_byte_pos"),
            )
        }

        /// Insert a character.
        pub fn insert_char(&mut self, pos: (usize, usize), c: char) {
            if c == '\n' {
                self.insert_newline(pos);
                return;
            }

            let Some(char_pos) = self.char_at(pos) else {
                panic!("invalid pos {:?} value {:?}", pos, self.value);
            };

            // no way to know if the new char combines with a surrounding char.
            // the difference of the graphem len seems safe though.
            let old_len = self.line_width(pos.1).expect("valid_pos");
            self.value.insert_char(char_pos, c);
            let new_len = self.line_width(pos.1).expect("valid_pos");

            let insert = TextRange::new((pos.0, pos.1), (pos.0 + new_len - old_len, pos.1));
            insert.expand_all(self.styles.styles_after_mut(pos));
            self.anchor = insert.expand(self.anchor);
            self.cursor = insert.expand(self.cursor);
        }

        /// Insert a line break.
        pub fn insert_newline(&mut self, pos: (usize, usize)) {
            let Some(char_pos) = self.char_at(pos) else {
                panic!("invalid pos {:?} value {:?}", pos, self.value);
            };

            self.value.insert_char(char_pos, '\n');

            let insert = TextRange::new((pos.0, pos.1), (0, pos.1 + 1));

            insert.expand_all(self.styles.styles_after_mut(pos));
            self.anchor = insert.expand(self.anchor);
            self.cursor = insert.expand(self.cursor);
        }

        pub fn remove(&mut self, range: TextRange) {
            let Some(start_pos) = self.char_at(range.start) else {
                panic!("invalid range {:?} value {:?}", range, self.value);
            };
            let Some(end_pos) = self.char_at(range.end) else {
                panic!("invalid range {:?} value {:?}", range, self.value);
            };

            self.value.remove(start_pos..end_pos);

            // remove deleted styles.
            // this is not a simple range, so filter+collect seems ok.
            let styles = mem::take(&mut self.styles.styles);
            self.styles.styles = styles
                .into_iter()
                .filter(|(r, _)| !range.contains_range(*r))
                .collect();

            range.shrink_all(self.styles.styles_after_mut(range.start));
            self.anchor = range.shrink(self.anchor);
            self.cursor = range.shrink(self.anchor);
        }
    }
}