teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Keyboard dispatch for the rich text editor.
//!
//! This module owns the full `KeyDown` / `ImeComposition` / `ImeCommit` dispatch: navigation
//! (arrows, Home/End, PageUp/Down), editing (Backspace, Delete, Enter,
//! `Ctrl+Backspace` / `Ctrl+Delete` for word‑level deletion), format
//! toggles (`Ctrl+B` / `Ctrl+I` / `Ctrl+U`), undo/redo
//! (`Ctrl+Z` / `Ctrl+Y` / `Ctrl+Shift+Z`), clipboard commands
//! (`Ctrl+C` / `Ctrl+X` / `Ctrl+V`), and `Ctrl+A` with the table‑aware
//! escalation ladder.
//!
//! All functions take `&SharedState` so they can be called from inside
//! `HandlerSet` closures without borrowing the widget struct.

use teksilo_core::event::{EventResponse, Key, ScrollMotion, WidgetEvent};
use teksilo_core::widget::EventContext;
use teksilo_text::text_document::{
    BlockFormat, ListFormat, MoveMode, MoveOperation, SelectionType, TableCellRef, TextFormat,
};
use teksilo_text::{CursorAffinity, TextDirection};

use crate::common::text_nav::{self, CaretStep, LineStep};

use super::clipboard;
use super::policy::EditCommandKind;
use super::state::{EditorState, SharedState};
use super::sync_cursor_signals;

/// Kind of key action taken by `handle_key`, used to decide whether to
/// clear the sticky preferred-X afterwards and how to update the
/// cursor's [`CursorAffinity`] at soft-wrap boundaries.
#[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum KeyAction {
    /// The key caused horizontal motion, a selection change, an edit,
    /// or anything else where the resulting caret position is not on
    /// a wrap boundary or, if it is, should render at the downstream
    /// (end-of-previous-line) placement. Clears the sticky column AND
    /// resets `cursor_affinity` to `Downstream`. Covers Left/Right,
    /// Ctrl+Home/Ctrl+End, Backspace/Delete/Enter/typing, paste, etc.
    ClearPreferredX,
    /// Visual-line edge motion that went through
    /// [`move_cursor_to_line_edge`], or horizontal motion that had to
    /// choose a side of a direction seam. The handler already set
    /// `cursor_affinity` itself, so the post-processing must NOT
    /// clobber it. Clears the sticky column. Covers non-Ctrl Home/End
    /// and the Left/Right arrows.
    LineEdgeMotion,
    /// Vertical motion (Up/Down): the sticky column must be preserved
    /// so repeated vertical presses land on the same visual column.
    /// The helpers also set `cursor_affinity` from hit-test, so
    /// post-processing must NOT clobber it. Ctrl+A also lives here
    /// since it leaves the caret position unchanged and any current
    /// affinity is still valid. PageUp/PageDown want the same
    /// treatment but carry [`KeyAction::PageMotion`], which says so
    /// separately.
    KeepPreferredX,
    /// PageUp/PageDown. Behaves exactly like [`KeyAction::KeepPreferredX`] —
    /// the helper set affinity, the sticky column must survive — but is kept
    /// distinct so the typewriter pin can *glide* to the new position instead
    /// of snapping. A page jump is a deliberate, screen-sized move where the
    /// animation helps the reader keep their bearings, unlike the per-keystroke
    /// re-pin, which must be instant.
    PageMotion,
    /// The key was not handled.
    Unhandled,
}

/// Under a filter that forbids taking text away, move the caret to the end of
/// the selection instead of letting the imminent insertion replace it.
///
/// Every insertion path in text-document removes the selected range first
/// (`TextCursor::insert_text` / `insert_fragment` do it internally, below any
/// command vocabulary), so a filter that accepts `InsertChar` while rejecting
/// `DeletePrev` would still let a writer select three paragraphs and type over
/// them. Collapsing first turns that into an append at the end of the
/// selection: nothing is lost, and the keystroke still lands — dropping it
/// instead would make the mode feel like a broken keyboard.
///
/// A no-op under every other filter, so insert sites can call it
/// unconditionally.
pub(super) fn collapse_selection_before_insert(state: &EditorState) {
    if !state
        .policy
        .command_filter
        .collapses_selection_before_insert()
    {
        return;
    }
    if !state.cursor.has_selection() {
        return;
    }
    let end = state.cursor.position().max(state.cursor.anchor());
    state.cursor.set_position(end, MoveMode::MoveAnchor);
}

pub(super) fn handle_key(
    state: &SharedState,
    event: &WidgetEvent,
    ctx: &mut EventContext,
) -> EventResponse {
    // IME composition — ongoing preedit (squiggly-underline preview
    // while the user is still choosing a candidate). Render the
    // preedit as a tentative insert so the caret position and visible
    // text match what the input method is showing. Replaced by the
    // next composition event, or finalised by the matching `ImeCommit`.
    if let WidgetEvent::ImeComposition { text, .. } = event {
        return handle_ime_composition(state, ctx, text);
    }

    // IME commit — the user picked a candidate or typed a printable
    // key that finalises the sequence. Clear any active preedit and
    // insert the committed text via the normal `pending_chars` batch.
    if let WidgetEvent::ImeCommit { text } = event {
        clear_ime_preedit(state);
        return push_pending_chars(state, ctx, text);
    }

    let WidgetEvent::KeyDown {
        key,
        modifiers,
        text,
        ..
    } = event
    else {
        return EventResponse::Ignored;
    };

    let shift = modifiers.shift();
    // The platform accelerator, not physical Control: ⌘ on macOS, Ctrl
    // elsewhere. Testing both would make the Win key act as Ctrl on Linux and
    // leave ⌃C doing Copy on macOS, where Control belongs to the text system.
    let ctrl = modifiers.command();
    // Which motion the arrow keys mean here. Not derivable from `ctrl`: on
    // macOS word-jump is ⌥←/→ while ⌘←/→ reaches the line edge and ⌘↑/↓ the
    // document, a three-way split no single accelerator flag can express.
    // See `common::text_nav`.
    let caret_motion = text_nav::caret_step(*modifiers);
    let line_motion = text_nav::line_step(*modifiers);
    // Tab's escape hatch is the exception, and it needs physical Control too.
    // Ctrl+Tab hands focus to the next widget on every platform, macOS
    // included (⌘⇥ is the application switcher and never arrives), so the Tab
    // arms below must decline a ⌃-modified Tab even where ⌃ is not the
    // accelerator — otherwise the editor swallows the one chord that gets a
    // keyboard user out of a table.
    let tab_escape = ctrl || modifiers.ctrl();
    let mode = if shift {
        MoveMode::KeepAnchor
    } else {
        MoveMode::MoveAnchor
    };

    // `TextCursor::clone()` creates an **independent** cursor with
    // its own position/anchor data (see the Clone impl in
    // text-document/.../cursor.rs). Cloning and mutating the clone
    // leaves `state.cursor` untouched. We must therefore operate on
    // `state.cursor` directly through a short-lived borrow and drop
    // the state before calling `sync_cursor_signals` so the signal
    // observers see the post-move value.
    // Ctrl+A is the only key that preserves `select_all_level`; every
    // other key resets it so a follow-up Ctrl+A starts at level 1.
    // Matches the godot reference's own `select_all_level` reset.
    let is_select_all = matches!(key, Key::A) && ctrl;
    let action: KeyAction = {
        let mut st = state.borrow_mut();
        if !is_select_all {
            st.select_all_level = 0;
            st.select_all_anchor_cell = None;
        }
        let filter = st.policy.command_filter;
        match key {
            Key::ArrowLeft if filter.accepts(EditCommandKind::MoveLeft) => {
                // Shift+Arrow at a cell boundary activates / extends a
                // rectangular cell selection (godot parity). Only
                // claims the event when we're actually at a cell
                // boundary; otherwise fall through to text-range
                // selection.
                if shift && try_extend_cell_selection(&mut st, -1, 0) {
                    KeyAction::ClearPreferredX
                } else if caret_motion == CaretStep::LineEdge {
                    let edge = visual_line_edge(&st, VisualDirection::Left);
                    move_cursor_to_line_edge(&mut st, edge, mode);
                    KeyAction::LineEdgeMotion
                } else {
                    let op = visual_move(&st, VisualDirection::Left, caret_motion);
                    st.cursor.move_position(op, mode, 1);
                    settle_affinity_at_seam(&mut st, VisualDirection::Left);
                    KeyAction::LineEdgeMotion
                }
            }
            Key::ArrowRight if filter.accepts(EditCommandKind::MoveRight) => {
                if shift && try_extend_cell_selection(&mut st, 1, 0) {
                    KeyAction::ClearPreferredX
                } else if caret_motion == CaretStep::LineEdge {
                    let edge = visual_line_edge(&st, VisualDirection::Right);
                    move_cursor_to_line_edge(&mut st, edge, mode);
                    KeyAction::LineEdgeMotion
                } else {
                    let op = visual_move(&st, VisualDirection::Right, caret_motion);
                    st.cursor.move_position(op, mode, 1);
                    settle_affinity_at_seam(&mut st, VisualDirection::Right);
                    KeyAction::LineEdgeMotion
                }
            }
            Key::ArrowUp if filter.accepts(EditCommandKind::MoveUp) => {
                if shift && try_extend_cell_selection(&mut st, 0, -1) {
                    KeyAction::ClearPreferredX
                } else {
                    match vertical_op(line_motion, false) {
                        Some(op) => {
                            st.cursor.move_position(op, mode, 1);
                            KeyAction::ClearPreferredX
                        }
                        None => {
                            move_cursor_vertical(&mut st, -1, mode);
                            KeyAction::KeepPreferredX
                        }
                    }
                }
            }
            Key::ArrowDown if filter.accepts(EditCommandKind::MoveDown) => {
                if shift && try_extend_cell_selection(&mut st, 0, 1) {
                    KeyAction::ClearPreferredX
                } else {
                    match vertical_op(line_motion, true) {
                        Some(op) => {
                            st.cursor.move_position(op, mode, 1);
                            KeyAction::ClearPreferredX
                        }
                        None => {
                            move_cursor_vertical(&mut st, 1, mode);
                            KeyAction::KeepPreferredX
                        }
                    }
                }
            }
            Key::PageUp if filter.accepts(EditCommandKind::PageUp) => {
                move_cursor_page(&mut st, -1, mode);
                KeyAction::PageMotion
            }
            Key::PageDown if filter.accepts(EditCommandKind::PageDown) => {
                move_cursor_page(&mut st, 1, mode);
                KeyAction::PageMotion
            }
            Key::Home if filter.accepts(EditCommandKind::MoveHome) => {
                if ctrl {
                    st.cursor.move_position(MoveOperation::Start, mode, 1);
                    KeyAction::ClearPreferredX
                } else {
                    // `move_cursor_to_line_edge` sets `cursor_affinity`
                    // from the hit-test, so this path returns
                    // `LineEdgeMotion` (skips the post-processing
                    // affinity reset).
                    move_cursor_to_line_edge(&mut st, LineEdge::Start, mode);
                    KeyAction::LineEdgeMotion
                }
            }
            Key::End if filter.accepts(EditCommandKind::MoveEnd) => {
                if ctrl {
                    st.cursor.move_position(MoveOperation::End, mode, 1);
                    KeyAction::ClearPreferredX
                } else {
                    // Use the typesetter to find end-of-visual-line
                    // rather than text-document's EndOfBlock. Two
                    // wins: (a) a second End press from an already-
                    // at-end cursor is a no-op, avoiding the
                    // block-advance bug where `get_block_at_position`
                    // returns the *next* block when queried at a
                    // boundary; (b) wrapped blocks stop at the wrap
                    // point, which is the standard editor behaviour.
                    // The helper sets `cursor_affinity` from
                    // hit_test → returns `LineEdgeMotion`.
                    move_cursor_to_line_edge(&mut st, LineEdge::End, mode);
                    KeyAction::LineEdgeMotion
                }
            }
            Key::A if ctrl && filter.accepts(EditCommandKind::SelectAll) => {
                apply_select_all_ladder(&mut st);
                // Horizontal motion is invalidated regardless.
                st.preferred_x = None;
                // KeepPreferredX skips the preferred_x reset in
                // post-processing — we already nulled it inline, and
                // crucially we must not clobber the `select_all_level`
                // which was just incremented.
                KeyAction::KeepPreferredX
            }
            Key::C if ctrl && filter.accepts(EditCommandKind::Copy) => {
                clipboard::copy(&mut st, ctx);
                KeyAction::ClearPreferredX
            }
            Key::X if ctrl && filter.accepts(EditCommandKind::Cut) => {
                clipboard::cut(&mut st, ctx);
                KeyAction::ClearPreferredX
            }
            Key::V if ctrl && shift && filter.accepts(EditCommandKind::PasteUnformatted) => {
                // Ctrl+Shift+V (⌘⇧V on macOS) — paste as plain text.
                // Matched before the plain Ctrl+V arm so the shift
                // modifier isn't absorbed by the regular paste.
                clipboard::paste_unformatted(&mut st, ctx);
                KeyAction::ClearPreferredX
            }
            Key::V if ctrl && !shift && filter.accepts(EditCommandKind::Paste) => {
                clipboard::paste(&mut st, ctx);
                KeyAction::ClearPreferredX
            }
            // --- Editor-preset mutating commands ---
            Key::Backspace if filter.accepts(EditCommandKind::DeletePrev) => {
                if text_nav::deletes_word(*modifiers) {
                    // Delete the word to the left — Ctrl+⌫, ⌥⌫ on macOS.
                    // Select the word, then delete the selection —
                    // matches the godot reference's delete-word (there is
                    // no dedicated delete-word API on TextCursor).
                    if !st.cursor.has_selection() {
                        st.cursor
                            .move_position(MoveOperation::WordLeft, MoveMode::KeepAnchor, 1);
                    }
                    let _ = st.cursor.remove_selected_text();
                } else if st.cursor.has_selection() {
                    let _ = st.cursor.remove_selected_text();
                } else if st.cursor.at_block_start()
                    && is_cursor_in_list(&st)
                    && filter.accepts(EditCommandKind::ExitList)
                {
                    // Backspace at start of a list item:
                    //  * Indented → decrement the block's indent level
                    //    (visually pulls the item leftward; standard
                    //    word-processor behaviour for Backspace-at-
                    //    indent).
                    //  * Indent 0 → remove the block from the list
                    //    entirely (converts it back to a regular
                    //    paragraph). Matches the godot reference's
                    //    backspace-in-a-list rule.
                    if let Ok(fmt) = st.cursor.block_format() {
                        let level = fmt.indent.unwrap_or(0);
                        if level > 0 {
                            let new_fmt = BlockFormat {
                                indent: Some(level - 1),
                                ..Default::default()
                            };
                            let _ = st.cursor.set_block_format(&new_fmt);
                        } else {
                            let _ = st.cursor.remove_current_block_from_list();
                        }
                    }
                } else if st.cursor.at_block_start()
                    && st.cursor.is_in_blockquote()
                    && st.cursor.is_first_block_in_current_frame()
                    && filter.accepts(EditCommandKind::ExitFrame)
                {
                    // Backspace at the very start of the first block of
                    // a blockquote — unwrap one level so the block lifts
                    // out of the quote. Without this, fallthrough would
                    // delete the boundary `\n` and silently drag the
                    // quoted paragraph into the preceding block (the
                    // crash class A1/A2/A3 closed at the data layer;
                    // here we make the UX intent explicit).
                    let _ = st.cursor.unwrap_current_block_from_blockquote();
                } else {
                    let _ = st.cursor.delete_previous_char();
                }
                KeyAction::ClearPreferredX
            }
            Key::Delete if filter.accepts(EditCommandKind::DeleteNext) => {
                if text_nav::deletes_word(*modifiers) {
                    if !st.cursor.has_selection() {
                        st.cursor
                            .move_position(MoveOperation::WordRight, MoveMode::KeepAnchor, 1);
                    }
                    let _ = st.cursor.remove_selected_text();
                } else if st.cursor.has_selection() {
                    let _ = st.cursor.remove_selected_text();
                } else if st.cursor.at_block_end()
                    && st.cursor.is_in_blockquote()
                    && st.cursor.is_last_block_in_current_frame()
                    && filter.accepts(EditCommandKind::ExitFrame)
                {
                    // Delete at the very end of the last block of a
                    // blockquote — unwrap one level instead of merging
                    // across the frame boundary into the following
                    // block (symmetric with Backspace at-block-start).
                    let _ = st.cursor.unwrap_current_block_from_blockquote();
                } else {
                    let _ = st.cursor.delete_char();
                }
                KeyAction::ClearPreferredX
            }
            Key::Enter if ctrl && filter.accepts(EditCommandKind::InsertBlockForced) => {
                // Ctrl+Enter: always insert a new block, bypassing
                // table-cell navigation. Matches the godot reference's
                // forced-block-insert branch.
                collapse_selection_before_insert(&st);
                let _ = st.cursor.insert_block();
                KeyAction::ClearPreferredX
            }
            Key::Enter if !ctrl && filter.accepts(EditCommandKind::InsertBlock) => {
                // Enter (without Ctrl) inside a table cell: move to
                // the cell in the same column one row down, or (on
                // the last row) step out of the table to the block
                // that follows. Outside a table, fall through to
                // `insert_block`. Shift+Enter falls through to the
                // normal insert_block path — matches godot's
                // behaviour where Shift+Enter is treated like Enter.
                let cell_info = st
                    .cursor
                    .current_table_cell()
                    .map(|c| (c.table.id(), c.row, c.column, c.table.rows()));
                if let Some((table_id, row, col, rows)) = cell_info
                    && filter.accepts(EditCommandKind::NavigateTableCellDown)
                {
                    navigate_table_cell_down(&mut st, table_id, row, col, rows);
                } else if st.cursor.is_in_blockquote()
                    && st.cursor.current_block_is_empty()
                    && filter.accepts(EditCommandKind::ExitFrame)
                {
                    // Enter on an empty paragraph inside a blockquote
                    // unwraps one nesting level (user-confirmed
                    // semantics). Inserting another empty block here
                    // would trap the cursor inside the quote with no
                    // intuitive way out.
                    let _ = st.cursor.unwrap_current_block_from_blockquote();
                } else {
                    collapse_selection_before_insert(&st);
                    let _ = st.cursor.insert_block();
                }
                KeyAction::ClearPreferredX
            }
            Key::Tab
                if !tab_escape && shift && filter.accepts(EditCommandKind::NavigateTableCell) =>
            {
                // Shift+Tab (no Ctrl): previous table cell when
                // inside a table; dedent the current list item when
                // the caret sits anywhere inside it (matches standard
                // word-processor behaviour — the user doesn't need to
                // move to the exact block start first). Otherwise
                // swallow (prevents focus-navigation bleed).
                // Ctrl+Shift+Tab is left unhandled so the OS /
                // app-level focus navigation can claim it.
                let cell_info = st.cursor.current_table_cell().map(|c| {
                    (
                        c.table.id(),
                        c.row,
                        c.column,
                        c.table.rows(),
                        c.table.columns(),
                    )
                });
                if let Some((table_id, row, col, rows, cols)) = cell_info {
                    navigate_table_cell(&mut st, table_id, row, col, rows, cols, -1);
                } else if is_cursor_in_list(&st) {
                    dedent_current_block(&mut st);
                } else if st.cursor.is_in_blockquote()
                    && filter.accepts(EditCommandKind::DecreaseBlockquoteDepth)
                {
                    // Shift+Tab inside a blockquote (no list active):
                    // pop one nesting level. At depth 1 this unwraps to
                    // a plain paragraph.
                    let _ = st.cursor.decrease_blockquote_depth();
                }
                KeyAction::ClearPreferredX
            }
            Key::Tab
                if !tab_escape && !shift && filter.accepts(EditCommandKind::NavigateTableCell) =>
            {
                // Tab (no Ctrl, no Shift):
                //  * Inside a table cell → next cell (wraps to next row;
                //    at last cell, insert a new row below).
                //  * Inside a list item → increase indent. Works from
                //    any caret position within the block so the user
                //    doesn't have to Home first.
                //  * Otherwise → insert a literal `\t`.
                // Ctrl+Tab is left unhandled (OS focus navigation).
                let cell_info = st.cursor.current_table_cell().map(|c| {
                    (
                        c.table.id(),
                        c.row,
                        c.column,
                        c.table.rows(),
                        c.table.columns(),
                    )
                });
                if let Some((table_id, row, col, rows, cols)) = cell_info {
                    navigate_table_cell(&mut st, table_id, row, col, rows, cols, 1);
                } else if is_cursor_in_list(&st) {
                    indent_current_block(&mut st);
                } else if st.cursor.is_in_blockquote()
                    && filter.accepts(EditCommandKind::IncreaseBlockquoteDepth)
                {
                    // Tab inside a blockquote (no list active): wrap the
                    // current block in a deeper nested quote. Order
                    // matters — the list check above takes priority for
                    // a list-inside-quote scenario.
                    let _ = st.cursor.increase_blockquote_depth();
                } else if filter.accepts(EditCommandKind::InsertTab) {
                    collapse_selection_before_insert(&st);
                    let _ = st.cursor.insert_text("\t");
                }
                KeyAction::ClearPreferredX
            }
            Key::B if ctrl && filter.accepts(EditCommandKind::ToggleBold) => {
                toggle_char_format(&mut st, FormatBit::Bold);
                KeyAction::ClearPreferredX
            }
            Key::I if ctrl && filter.accepts(EditCommandKind::ToggleItalic) => {
                toggle_char_format(&mut st, FormatBit::Italic);
                KeyAction::ClearPreferredX
            }
            Key::U if ctrl && filter.accepts(EditCommandKind::ToggleUnderline) => {
                toggle_char_format(&mut st, FormatBit::Underline);
                KeyAction::ClearPreferredX
            }
            Key::Z if ctrl && !shift && filter.accepts(EditCommandKind::Undo) => {
                let _ = st.document.undo();
                KeyAction::ClearPreferredX
            }
            Key::Y if ctrl && filter.accepts(EditCommandKind::Redo) => {
                let _ = st.document.redo();
                KeyAction::ClearPreferredX
            }
            Key::Z if ctrl && shift && filter.accepts(EditCommandKind::Redo) => {
                let _ = st.document.redo();
                KeyAction::ClearPreferredX
            }
            _ => {
                // Printable character fallback: winit populates
                // `KeyDown::text` with the character produced by the
                // key (post-layout mapping, so Shift / dead keys /
                // layout translations are already applied). Guard
                // against Ctrl / Super (Cmd) being held — some
                // layouts populate `text` with a control character
                // even for Ctrl+letter, and we don't want
                // unhandled Ctrl combos (Ctrl+F, Ctrl+W, …) to
                // accidentally insert the letter. Alt / AltGr are
                // NOT rejected because they produce legitimate
                // diacritic input on European layouts
                // (e.g. macOS Option+E → ´).
                if ctrl {
                    KeyAction::Unhandled
                } else if let Some(t) = text.as_deref() {
                    if filter.accepts(EditCommandKind::InsertChar) {
                        let clean: String = t.chars().filter(|c| !c.is_control()).collect();
                        if !clean.is_empty() {
                            st.pending_typed_chars += clean.chars().count();
                            st.pending_chars.push_str(&clean);
                            KeyAction::ClearPreferredX
                        } else {
                            KeyAction::Unhandled
                        }
                    } else {
                        KeyAction::Unhandled
                    }
                } else {
                    KeyAction::Unhandled
                }
            }
        }
    };

    match action {
        KeyAction::Unhandled => EventResponse::Ignored,
        KeyAction::ClearPreferredX => {
            {
                let mut st = state.borrow_mut();
                st.preferred_x = None;
                // Horizontal motion / edit / Ctrl+Home / Ctrl+End:
                // any sticky affinity from a previous click or
                // vertical move is no longer meaningful. The caret
                // moved logically; render at the default downstream
                // placement.
                st.cursor_affinity = CursorAffinity::Downstream;
            }
            caret_moved_epilogue(state, ctx)
        }
        KeyAction::LineEdgeMotion => {
            // Home/End went through `move_cursor_to_line_edge`, which
            // already set `cursor_affinity` from the typesetter's
            // hit-test. Just clear the sticky column.
            {
                let mut st = state.borrow_mut();
                st.preferred_x = None;
            }
            caret_moved_epilogue(state, ctx)
        }
        KeyAction::KeepPreferredX => {
            // Up/Down's helper already set affinity from hit-test; Ctrl+A
            // didn't move the caret. Preserve both `preferred_x` and
            // `cursor_affinity` unchanged.
            caret_moved_epilogue(state, ctx)
        }
        KeyAction::PageMotion => {
            // As `KeepPreferredX`, but the typewriter pin glides — see the
            // variant's docs.
            caret_moved_epilogue_with(state, ctx, ScrollMotion::Smooth)
        }
    }
}

/// Shared tail for the caret-moving key actions. Keeps the caret inside the
/// editor's own viewport ([`ensure_caret_visible`]), publishes the new cursor
/// position to observers, updates the OS-IME candidate area, chases the caret
/// into any enclosing scroll area ([`chase_caret_into_view`]), and requests a
/// frame. Always returns [`EventResponse::Handled`].
fn caret_moved_epilogue(state: &SharedState, ctx: &mut EventContext) -> EventResponse {
    caret_moved_epilogue_with(state, ctx, ScrollMotion::Instant)
}

/// [`caret_moved_epilogue`] with an explicit typewriter-pin motion — see
/// [`chase_caret_into_view_with`]. Used by the page-sized jumps, which glide.
fn caret_moved_epilogue_with(
    state: &SharedState,
    ctx: &mut EventContext,
    motion: ScrollMotion,
) -> EventResponse {
    // Any keyboard-driven caret move hands control back to the typewriter pin
    // after a click or drag stood it down.
    state.borrow_mut().mouse_anchored = false;
    ensure_caret_visible(state);
    sync_cursor_signals(state);
    report_ime_cursor_area(state, ctx);
    chase_caret_into_view_with(state, ctx, motion);
    ctx.request_frame();
    EventResponse::Handled
}

/// The caret's rectangle in **absolute window (tree) coordinates**, or `None`
/// when the editor is unfocused or the engine has not been laid out yet.
///
/// [`RichTextEngine::caret_rect`](teksilo_text::RichTextEngine::caret_rect)
/// answers in two spaces at once: `y` already has the engine's scroll offset
/// subtracted — it is where the caret paints — while `x` does not, because the
/// engine has no horizontal scroll to apply. So the window rect adds the body's
/// window origin to both and subtracts the horizontal scroll from `x` alone.
/// Taking the vertical offset off a second time, which is what this did, put
/// the rect a whole viewport out of place in any scrolled editor — and this
/// rect steers the OS-IME candidate window, the enclosing-scroll-area follow
/// and the typewriter pin.
///
/// See [`vertical_scroll_slip`] for the one thing `y` still needs.
pub(super) fn caret_window_rect(st: &EditorState) -> Option<teksilo_canvas::Rect> {
    if !st.has_focus || !st.engine.has_full_layout() {
        return None;
    }
    let caret = st
        .engine
        .caret_rect(st.cursor.position(), st.cursor_affinity);
    Some(teksilo_canvas::Rect::new(
        st.viewport_origin.x + caret[0] - st.scroll_x.get(),
        st.viewport_origin.y + caret[1] + vertical_scroll_slip(st),
        caret[2].max(1.0),
        caret[3],
    ))
}

/// How far the engine's idea of the scroll offset lags the widget's.
///
/// The engine subtracts the offset it was last *given*, which the widget hands
/// it at paint. A scroll that has happened since — a wheel event this frame, a
/// programmatic `scroll_y.set` before the next render — has not reached it, so
/// a screen-space `y` straight out of the engine is stale by exactly this much.
/// Zero on any settled frame, which is why it went unnoticed until a query ran
/// between a scroll and a repaint.
fn vertical_scroll_slip(st: &EditorState) -> f32 {
    (st.engine.scroll_offset() - st.scroll_y.get()) * st.engine.zoom()
}

/// The **content-space** rectangle enclosing `[start, end)` — y = 0 at the top of
/// the laid-out text, unaffected by scrolling and by where the editor sits in the
/// window.
///
/// The scroll-free half of [`range_window_rect`]. A decoration drawn *beside* the
/// text (a comment's leader, a bracket) wants window space, because it has to line
/// itself up with a rect the arena also stores. Anything that maps a document onto
/// a **proportion** of itself — an overview lane, a scrollbar annotation — wants
/// this instead: window space answers "where is this on screen right now", which
/// changes with every scroll tick and is meaningless for an offset the writer has
/// scrolled past.
pub(super) fn range_content_rect(
    st: &EditorState,
    start: usize,
    end: usize,
) -> Option<teksilo_canvas::Rect> {
    if !st.engine.has_full_layout() {
        return None;
    }
    // The same fixed Downstream affinity `range_window_rect` uses, and for the same
    // reason: these are arbitrary offsets unrelated to the caret, so reading the live
    // `cursor_affinity` would put the rect on the wrong side of a soft-wrap boundary
    // depending on where the caret happens to sit.
    //
    // `caret_rect_content`, not `caret_rect`: the plain form answers in screen
    // space, so building this rect from it made the "scroll-free" half of the
    // pair move with every scroll tick — and an overview lane dividing it by
    // `content_height` drew its mark somewhere else on every frame.
    let a = st
        .engine
        .caret_rect_content(start, CursorAffinity::Downstream);
    let b = st
        .engine
        .caret_rect_content(end, CursorAffinity::Downstream);
    let (ay, ah) = (a[1], a[3].max(1.0));
    let (by, bh) = (b[1], b[3].max(1.0));

    let x0 = a[0].min(b[0]);
    let x1 = a[0].max(b[0]);
    let y0 = ay.min(by);
    let y1 = (ay + ah).max(by + bh);
    Some(teksilo_canvas::Rect::new(
        x0,
        y0,
        (x1 - x0).max(1.0),
        (y1 - y0).max(ah.max(bh)),
    ))
}

/// The **window-space** rectangle enclosing an arbitrary character range
/// `[start, end)` — the union of the caret rects at its two ends, in the same
/// absolute space [`caret_window_rect`] answers in.
///
/// (This paragraph used to sit above [`range_content_rect`], which has its own:
/// two doc comments in a row, the first one describing the function below the
/// second.)
///
/// Unlike [`caret_window_rect`], this takes explicit offsets (not the live cursor) and does
/// **not** require focus — it exists so a search match can be scrolled into view whether or
/// not the editor is focused. `None` before the first full layout.
pub(super) fn range_window_rect(
    st: &EditorState,
    start: usize,
    end: usize,
) -> Option<teksilo_canvas::Rect> {
    if !st.engine.has_full_layout() {
        return None;
    }
    // As in `caret_window_rect`: the engine's `y` is already screen-space and
    // its `x` is not, so only `x` takes a scroll subtraction here.
    let slip = vertical_scroll_slip(st);
    let to_window = |c: [f32; 4]| {
        (
            st.viewport_origin.x + c[0] - st.scroll_x.get(),
            st.viewport_origin.y + c[1] + slip,
            c[3].max(1.0),
        )
    };
    // A **fixed** affinity, not the live cursor's: these are arbitrary offsets unrelated to
    // the caret, and reveal only needs a stable line — using `st.cursor_affinity` would place
    // the rect on the wrong side of a soft-wrap boundary depending on where the caret happens
    // to sit.
    let (ax, ay, ah) = to_window(st.engine.caret_rect(start, CursorAffinity::Downstream));
    let (bx, by, bh) = to_window(st.engine.caret_rect(end, CursorAffinity::Downstream));

    let x0 = ax.min(bx);
    let y0 = ay.min(by);
    let x1 = ax.max(bx);
    let y1 = (ay + ah).max(by + bh);
    Some(teksilo_canvas::Rect::new(
        x0,
        y0,
        (x1 - x0).max(1.0),
        (y1 - y0).max(ah.max(bh)),
    ))
}

/// Report the caret's window-space rectangle to the platform so the OS IME
/// candidate window tracks the insertion point. No-op when unfocused or the
/// engine has not been laid out yet. Called whenever the caret moves.
pub(super) fn report_ime_cursor_area(state: &SharedState, ctx: &mut EventContext) {
    let area = {
        let st = state.borrow();
        match caret_window_rect(&st) {
            Some(a) => a,
            None => return,
        }
    };
    // Dedup against the last reported area. The platform-side
    // `WindowOps::set_ime_cursor_area` does *not* dedup (it assumes text
    // widgets only report on caret moves); re-forwarding an unchanged area is
    // wasted work and, on some winit IME backends (ibus / fcitx), echoes back
    // a fresh empty `Ime::Preedit`, sustaining a feedback loop. Only forward a
    // genuinely new position.
    {
        let mut st = state.borrow_mut();
        if st.last_ime_area == Some(area) {
            return;
        }
        st.last_ime_area = Some(area);
    }
    ctx.set_ime_cursor_area(area);
}

/// After the caret moves, ask any enclosing scroll area (a form/page the
/// editor is embedded in) to reveal the caret. The editor already keeps the
/// caret inside its *own* viewport via [`ensure_caret_visible`]; this adds the
/// outer chaining so that when the editor **grows** inside a scrolling page
/// (its own scroll suppressed) the page follows the caret. Framework-side,
/// `ctx.ensure_visible` walks only the editor's ancestors (never the editor
/// itself), so this never fights the internal follow.
///
/// Fires only on a caret *move* — a plain wheel / scrollbar scroll never
/// triggers it, so the reader can scroll away from the caret and the view
/// stays put until the caret next moves. A zero margin means it scrolls only
/// when the caret is genuinely off-screen (no nudging when it is already
/// visible). Off entirely when [`follow_caret_in_page`](EditorState::follow_caret_in_page)
/// is disabled, unfocused, not yet laid out, or with no enclosing scroll area.
///
/// The revealed rect is the caret line **plus one line below it**. Beyond a
/// mild always-a-line-of-context-under-the-caret scroll-off, this proactively
/// reveals the line a wrapping character lands on: typed input is applied to
/// the document a frame later by `frame_loop::tick` (which has no
/// `EventContext` to re-chase), so this chase sees the caret's *pre-insert*
/// line — the look-ahead keeps the post-wrap line on screen without waiting for
/// the next keystroke. Structural edits (Enter/Backspace/Delete) mutate the
/// cursor synchronously and are exact.
pub(super) fn chase_caret_into_view(state: &SharedState, ctx: &mut EventContext) {
    chase_caret_into_view_with(state, ctx, ScrollMotion::Instant);
}

/// [`chase_caret_into_view`] with an explicit scroll motion for the typewriter
/// pin.
///
/// Only the pin reads it — a minimal reveal is always instant, because it fires
/// on ordinary caret movement where an animation would just add lag. The pin,
/// by contrast, re-asserts on **every** keystroke, so animating it is what
/// produces the "screen bouncing" complaint typewriter modes attract in other
/// editors: hence [`ScrollMotion::Instant`] for typing and character-level
/// navigation, and [`ScrollMotion::Smooth`] reserved for the deliberate jumps
/// (page up/down, a search hit) where a glide reads as orientation rather than
/// noise.
pub(super) fn chase_caret_into_view_with(
    state: &SharedState,
    ctx: &mut EventContext,
    motion: ScrollMotion,
) {
    let (area, pin) = {
        let mut st = state.borrow_mut();
        if !st.follow_caret_in_page {
            return;
        }
        // The pin stands down while the pointer owns the caret: a click just
        // places the caret and *becomes* the new resting position, and a
        // drag-selection is never interrupted by a scroll (which would make
        // precise selection nearly impossible — a real, filed bug in editors
        // that re-centre on pointer input).
        let pin = match st.typewriter {
            Some(f)
                if !st.mouse_anchored
                    && !matches!(st.drag_state, super::state::DragState::Selecting { .. }) =>
            {
                Some(f)
            }
            _ => None,
        };

        let pos = st.cursor.position();
        let rect = match caret_window_rect(&st) {
            Some(a) => a,
            None => return,
        };

        // Reveal the caret only when it actually MOVES. A repeat call at the
        // same document position — IME preedit churn (Linux ibus/fcitx floods
        // empty `Ime::Preedit` events), a no-op nav key, a redundant click —
        // must not scroll: once the user has deliberately scrolled the caret
        // off-screen, a same-position chase would yank the page straight back,
        // fighting the scroll. `frame_loop::tick` applies typed input a frame
        // later, so within a fast burst several keystrokes share one pre-insert
        // position; the one-line look-ahead below covers that batch, and the
        // next real move re-chases.
        //
        // A pin additionally compares the caret's window `y`, because it must
        // survive a reflow that moves the caret's *rect* without moving its
        // offset — a soft-wrap change, a typography or zoom change, a resize.
        // Deduping a pin on position alone lets it drift off its line and stay
        // there, which is the shape of the zoom-dependent jitter bugs that
        // dog other implementations.
        let same_pos = st.last_chase_pos == Some(pos);
        if pin.is_some() {
            let same_y = st
                .last_chase_y
                .is_some_and(|y| (y - rect.y).abs() <= f32::EPSILON);
            if same_pos && same_y {
                return;
            }
            st.last_chase_y = Some(rect.y);
        } else {
            if same_pos {
                return;
            }
            st.last_chase_y = None;
        }
        st.last_chase_pos = Some(pos);
        (rect, pin)
    };

    match pin {
        // The bare caret rect, with no look-ahead: alignment is computed from
        // the target's height, so padding it by a line would shift the pin by
        // half a line and put the text permanently off the mark.
        Some(fraction) => ctx.ensure_visible_aligned(area, fraction, motion),
        None => {
            // Extend downward by one line so the line a wrapping character would
            // land on is revealed together with the current caret line.
            let line = area.height.max(1.0);
            let area = teksilo_canvas::Rect::new(area.x, area.y, area.width, area.height + line);
            ctx.ensure_visible(area);
        }
    }
}

/// Ctrl+A escalation ladder. Mirrors the godot reference's `select_all`.
/// When the caret sits inside a table cell, four consecutive presses
/// widen the selection: paragraph → cell → table → document, then
/// wrap back to paragraph on the fifth. Outside a table Ctrl+A is
/// single-shot `SelectionType::Document` with `select_all_level = 0`.
///
/// **Mid-ladder boundary stability**: after level 1 applies
/// `select(BlockUnderCursor)`, the cursor's `position` lands at the
/// end of the selected block, which for a single-block cell's last
/// block is the boundary between the cell and whatever follows —
/// `current_table_cell()` may then return `None` and the ladder
/// would skip cell/table levels and jump straight to document. To
/// prevent that we cache the cell reference on the first ladder
/// call (`select_all_anchor_cell`) and reuse it for levels 2 and 3.
/// The cache is cleared whenever `select_all_level` resets.
pub(super) fn apply_select_all_ladder(st: &mut EditorState) {
    use super::state::SelectAllAnchorCell;
    let next_level = st.select_all_level + 1;

    // Resolve the cell snapshot for this ladder step. At level 1 we
    // read everything fresh from the cursor and cache it. At levels
    // 2 and 3 we reuse the cached snapshot so a boundary-adjacent
    // cursor (produced by level 1's `select(BlockUnderCursor)`)
    // doesn't short-circuit the ladder via a stale
    // `current_table_cell() == None` result.
    let cell_info: Option<SelectAllAnchorCell> = if next_level == 1 {
        st.cursor.current_table_cell().map(|c| SelectAllAnchorCell {
            table_id: c.table.id(),
            row: c.row,
            column: c.column,
            table_rows: c.table.rows(),
            table_columns: c.table.columns(),
        })
    } else {
        st.select_all_anchor_cell
    };

    let Some(cell) = cell_info else {
        st.cursor.select(SelectionType::Document);
        st.select_all_level = 0;
        st.select_all_anchor_cell = None;
        return;
    };

    if next_level == 1 {
        st.select_all_anchor_cell = Some(cell);
    }

    match next_level {
        1 => st.cursor.select(SelectionType::BlockUnderCursor),
        2 => st
            .cursor
            .select_table_cell(cell.table_id, cell.row, cell.column),
        3 => {
            st.cursor.select_cell_range(
                cell.table_id,
                0,
                0,
                cell.table_rows.saturating_sub(1),
                cell.table_columns.saturating_sub(1),
            );
        }
        _ => {
            st.cursor.select(SelectionType::Document);
        }
    }
    st.select_all_level = if next_level >= 4 { 0 } else { next_level };
    if st.select_all_level == 0 {
        st.select_all_anchor_cell = None;
    }
}

/// Which `TextFormat` bit a Ctrl+B/I/U toggle flips.
#[derive(Copy, Clone)]
enum FormatBit {
    Bold,
    Italic,
    Underline,
}

/// Toggle a single character-format bit at the caret, mirroring the
/// godot reference's `toggle_bold` / `toggle_italic` / `toggle_underline`:
/// the decision to turn a format on or off is read from the current caret
/// format (`char_format()`), not from a selection-wide consensus.
///
/// **Read-position subtlety**: `TextCursor::char_format()` reads
/// the inline element at `position()`. After a select-all the
/// caret sits at the *end* of the selection, which may be past the
/// last character (an empty "virtual" element with default format).
/// To get a meaningful read for the toggle decision we use
/// `selection_start()` when a selection is active — that position
/// is always the actual first character of the selected range.
fn toggle_char_format(st: &mut EditorState, bit: FormatBit) {
    let probe = st.document.cursor();
    if st.cursor.has_selection() {
        let start = st.cursor.selection_start();
        probe.set_position(start, MoveMode::MoveAnchor);
    } else {
        probe.set_position(st.cursor.position(), MoveMode::MoveAnchor);
    }
    let current = probe.char_format().unwrap_or_default();
    let new_value = !match bit {
        FormatBit::Bold => current.font_bold.unwrap_or(false),
        FormatBit::Italic => current.font_italic.unwrap_or(false),
        FormatBit::Underline => current.font_underline.unwrap_or(false),
    };
    let fmt = match bit {
        FormatBit::Bold => TextFormat {
            font_bold: Some(new_value),
            ..Default::default()
        },
        FormatBit::Italic => TextFormat {
            font_italic: Some(new_value),
            ..Default::default()
        },
        FormatBit::Underline => TextFormat {
            font_underline: Some(new_value),
            ..Default::default()
        },
    };
    let _ = st.cursor.merge_char_format(&fmt);
    st.pending_format_changed = true;
}

/// Apply an `ImeComposition` event. Removes the previous preedit
/// range from the document (if any), inserts the new preedit text,
/// and records the resulting range so the next composition event can
/// replace it. An empty composition string cancels the preedit and
/// clears the range without inserting anything.
fn handle_ime_composition(
    state: &SharedState,
    ctx: &mut EventContext,
    text: &str,
) -> EventResponse {
    let filter = state.borrow().policy.command_filter;
    if !filter.accepts(EditCommandKind::InsertChar) {
        return EventResponse::Ignored;
    }
    let clean: String = text.chars().filter(|c| !c.is_control()).collect();
    // A composition event carrying no text while there is no active preedit is
    // a genuine no-op. Some Linux IME backends (ibus / fcitx via winit) emit a
    // continuous stream of empty `Ime::Preedit("")` events while the field is
    // focused; processing each one — an empty undo block, an IME-cursor-area
    // report, a caret chase — is pure waste. Worse, the report re-arms the very
    // loop that produced the event (see `report_ime_cursor_area`), and the
    // chase fights the user's scroll. Bail before touching the document, the
    // platform, or the scroll.
    if clean.is_empty() && state.borrow().ime_preedit_range.is_none() {
        return EventResponse::Ignored;
    }
    {
        let mut st = state.borrow_mut();
        // Group the remove+reinsert as a single undo step so a user
        // undo after composition pops the entire preedit, not each
        // intermediate candidate.
        st.cursor.begin_edit_block();
        if let Some(range) = st.ime_preedit_range.take() {
            let doc_end = st.document.character_count();
            let start = range.start.min(doc_end);
            let end = range.end.min(doc_end);
            if start < end {
                st.cursor.set_position(start, MoveMode::MoveAnchor);
                st.cursor.set_position(end, MoveMode::KeepAnchor);
                let _ = st.cursor.remove_selected_text();
            }
        }
        if !clean.is_empty() {
            // A composition starting while a selection is live would replace it.
            // (A no-op when a preedit range was just removed above: that path
            // leaves the cursor collapsed at the range start.)
            collapse_selection_before_insert(&st);
            let start = st.cursor.position();
            let _ = st.cursor.insert_text(&clean);
            let end = st.cursor.position();
            st.ime_preedit = Some(clean);
            st.ime_preedit_range = Some(start..end);
        } else {
            st.ime_preedit = None;
        }
        st.cursor.end_edit_block();
        st.preferred_x = None;
        // Editing always lands the caret at a logical position; any
        // sticky upstream affinity from a previous click is invalid
        // now. Render at the default downstream placement.
        st.cursor_affinity = CursorAffinity::Downstream;
        st.pending_text_changed = true;
    }
    report_ime_cursor_area(state, ctx);
    chase_caret_into_view(state, ctx);
    ctx.request_frame();
    EventResponse::Handled
}

/// Drop any active preedit, removing its tentative text from the document.
/// Called on commit (before the finalised insert) and on focus loss.
pub(super) fn clear_ime_preedit(state: &SharedState) {
    let mut st = state.borrow_mut();
    // On commit, the input method typically sends one final
    // composition with empty text followed by a commit with the final
    // string — but some backends skip the empty composition. If the
    // preedit range is still live, remove it so the commit insert
    // doesn't duplicate content.
    if let Some(range) = st.ime_preedit_range.take() {
        let doc_end = st.document.character_count();
        let start = range.start.min(doc_end);
        let end = range.end.min(doc_end);
        if start < end {
            st.cursor.set_position(start, MoveMode::MoveAnchor);
            st.cursor.set_position(end, MoveMode::KeepAnchor);
            let _ = st.cursor.remove_selected_text();
        }
    }
    st.ime_preedit = None;
}

/// Shared helper for printable-character ingestion: push the text
/// into `pending_chars`, clear sticky `preferred_x`, request a frame.
/// Reused by the IME commit path.
fn push_pending_chars(state: &SharedState, ctx: &mut EventContext, text: &str) -> EventResponse {
    if text.is_empty() {
        return EventResponse::Ignored;
    }
    let filter = state.borrow().policy.command_filter;
    if !filter.accepts(EditCommandKind::InsertChar) {
        return EventResponse::Ignored;
    }
    let clean: String = text.chars().filter(|c| !c.is_control()).collect();
    if clean.is_empty() {
        return EventResponse::Ignored;
    }
    {
        let mut st = state.borrow_mut();
        // The **only** caller is the `ImeCommit` arm above, so what lands here
        // is a settled composition rather than a keystroke: the characters that
        // arrive are not the keys that were pressed, and counting them as typed
        // would be wrong about every writer of a language with an input method.
        st.pending_ime_chars += clean.chars().count();
        st.pending_chars.push_str(&clean);
        st.preferred_x = None;
        // Typing always lands the caret at a logical position; any
        // sticky upstream affinity from a previous click is invalid.
        st.cursor_affinity = CursorAffinity::Downstream;
    }
    report_ime_cursor_area(state, ctx);
    // Printable input is batched into `pending_chars` and applied by
    // `frame_loop::tick` next frame, so this chase sees the caret at its
    // PRE-insert position; `chase_caret_into_view`'s one-line look-ahead
    // reveals the line a wrap would land on so the page keeps up without
    // waiting for the next keystroke.
    chase_caret_into_view(state, ctx);
    ctx.request_frame();
    EventResponse::Handled
}

/// Ask the typesetter to compute a scroll offset that keeps the
/// current caret inside the viewport, and write that offset into
/// the widget's `scroll_y` signal. Called only from keyboard
/// handlers (after arrow/page nav), never from the frame loop —
/// otherwise wheel scrolls that move the viewport away from the
/// caret would be undone on the next tick.
fn ensure_caret_visible(state: &SharedState) {
    let mut st = state.borrow_mut();
    if !st.engine.has_full_layout() {
        return;
    }
    // Forward the current wheel-driven scroll so ensure_caret_visible
    // computes the correction relative to where the viewport actually
    // is, not where it was at last paint.
    let current = st.scroll_y.get();
    st.engine.set_scroll_offset(current);
    // Name the position rather than letting the engine read its own cached
    // cursor: that cache is refreshed at paint, so inside a key handler it still
    // holds the caret from *before* the keystroke. Correcting against it revealed
    // the old caret and left the new one outside the viewport until the next key
    // press — which is what made walking with the arrows lurch a line behind.
    let pos = st.cursor.position();
    let affinity = st.cursor_affinity;
    if let Some(new_off) = st.engine.ensure_position_visible(pos, affinity) {
        st.scroll_y.set(new_off);
    }
    // Horizontal caret visibility — matches godot's `ensure_caret_h_visible`.
    // Margin is 20 logical pixels on each side so the caret doesn't sit flush
    // against the viewport edge.
    ensure_caret_h_visible_locked(&mut st);
}

/// Horizontal caret-visibility. Factored out so code paths that
/// need it without the vertical adjustment (e.g. after `Home` on a
/// very long wrapped block) can call it directly.
///
/// Takes `&mut EditorState` (caller holds the borrow) rather than
/// `&SharedState` because the current call sites are inside the
/// `ensure_caret_visible` borrow.
fn ensure_caret_h_visible_locked(st: &mut EditorState) {
    if !st.engine.has_full_layout() {
        return;
    }
    // When wrap mode is Word, there is no horizontal overflow: the
    // engine wraps content to the viewport width and `max_scroll_x`
    // is pinned at 0. Nothing to adjust.
    let max_x = st.max_scroll_x.get();
    if max_x <= 0.0 {
        return;
    }
    let viewport_w = st.viewport_width;
    if viewport_w <= 0.0 {
        return;
    }

    let pos = st.cursor.position();
    let caret = st.engine.caret_rect(pos, st.cursor_affinity);
    // The engine's `x` is content-space — it applies no horizontal scroll of its
    // own — so the viewport-relative position is this minus the widget's own
    // `scroll_x`. (Its `y`, confusingly, *is* screen-space; see
    // `RichTextEngine::caret_rect`.)
    let caret_x = caret[0];
    let current_x = st.scroll_x.get();
    // Margin: 20 px on each side, matching godot's
    // `ensure_caret_h_visible`.
    let margin = 20.0_f32;
    let screen_x = caret_x - current_x;

    let new_x = if screen_x < margin {
        (caret_x - margin).max(0.0)
    } else if screen_x > viewport_w - margin {
        (caret_x - viewport_w + margin).clamp(0.0, max_x)
    } else {
        return;
    };
    st.scroll_x.set(new_x.clamp(0.0, max_x));
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum LineEdge {
    Start,
    End,
}

/// The way the user pressed, in screen terms.
#[derive(Clone, Copy, PartialEq, Eq)]
enum VisualDirection {
    Left,
    Right,
}

/// The logical move that carries the caret one step in the direction the
/// user actually pressed.
///
/// text-document's `MoveOperation::Left`/`Right` are *logical* aliases —
/// `Left` is "previous character", `Right` is "next character" — which
/// is correct for left-to-right text and backwards for right-to-left,
/// where the next character is drawn further left. Pressing → inside an
/// Arabic word therefore walked the caret leftward across the screen.
///
/// The direction is taken at the caret rather than from the paragraph,
/// so an English quotation inside Arabic prose steps the way it reads.
/// `resolve_move` stays pure logical stepping; choosing *which* logical
/// primitive to invoke is the widget layer's job, because only it knows
/// how the text was laid out.
fn visual_move(st: &EditorState, pressed: VisualDirection, step: CaretStep) -> MoveOperation {
    horizontal_op(moves_forward(st, pressed), step)
}

/// The stepping primitive for a horizontal motion already resolved to a
/// direction. Split from [`visual_move`] so the table is testable without an
/// `EditorState` — and, more to the point, on a host whose platform never
/// produces `CaretStep::LineEdge`.
fn horizontal_op(forward: bool, step: CaretStep) -> MoveOperation {
    match (forward, step) {
        (true, CaretStep::Word) => MoveOperation::WordRight,
        (false, CaretStep::Word) => MoveOperation::WordLeft,
        // `LineEdge` never reaches here — the caller routes it to
        // `move_cursor_to_line_edge`, which needs the line's extent rather
        // than a stepping primitive. Treat it as a character step so a future
        // caller that forgets still moves the caret somewhere sane.
        (true, _) => MoveOperation::Right,
        (false, _) => MoveOperation::Left,
    }
}

/// The whole-document / whole-block move a vertical arrow resolves to, or
/// `None` when it is the ordinary one-visual-line step (which needs the
/// typesetter, not a logical primitive).
fn vertical_op(step: LineStep, downward: bool) -> Option<MoveOperation> {
    match (step, downward) {
        (LineStep::Document, false) => Some(MoveOperation::Start),
        (LineStep::Document, true) => Some(MoveOperation::End),
        (LineStep::Paragraph, false) => Some(MoveOperation::StartOfBlock),
        (LineStep::Paragraph, true) => Some(MoveOperation::EndOfBlock),
        (LineStep::Line, _) => None,
    }
}

/// Which *logical* line edge the user pressed towards.
///
/// `move_cursor_to_line_edge` speaks in logical edges, deliberately, so Home
/// and End land on their own ends in right-to-left text. macOS's ⌘←/⌘→ are
/// visual (`moveToLeftEndOfLine:`), so the pressed direction has to be folded
/// through the caret's direction the same way [`visual_move`] folds character
/// and word steps — otherwise ⌘← and the ← next to it would disagree about
/// which way "left" is inside an Arabic paragraph.
fn visual_line_edge(st: &EditorState, pressed: VisualDirection) -> LineEdge {
    line_edge_op(moves_forward(st, pressed))
}

/// The logical line edge reached by a horizontal motion already resolved to a
/// direction. Split for the same reason as [`horizontal_op`].
fn line_edge_op(forward: bool) -> LineEdge {
    if forward {
        LineEdge::End
    } else {
        LineEdge::Start
    }
}

/// Whether a press in `pressed` walks *forward* through the text, given the
/// direction of the run the caret sits in.
///
/// Taken at the caret rather than from the paragraph, so an English quotation
/// inside Arabic prose steps the way it reads.
fn moves_forward(st: &EditorState, pressed: VisualDirection) -> bool {
    let rtl = st.engine.direction_at(st.cursor.position()) == TextDirection::RightToLeft;
    match pressed {
        VisualDirection::Right => !rtl,
        VisualDirection::Left => rtl,
    }
}

/// Pick which side of a direction seam the caret belongs to after a
/// horizontal move.
///
/// Where an LTR run meets an RTL one, a single character position has
/// two visual homes on the same line — often at opposite ends of it —
/// and only affinity says which. Landing on a seam without choosing
/// leaves the caret wherever the previous keystroke's affinity happened
/// to put it, which reads as the caret teleporting across the line.
///
/// The rule is that the caret stays on the side the user came *from*:
/// arriving from the left it attaches to the text before the offset
/// (downstream), arriving from the right to the text after it
/// (upstream). Away from a seam affinity is a no-op, so this leaves the
/// existing value alone rather than resetting it and disturbing the
/// soft-wrap placement the other handlers maintain.
fn settle_affinity_at_seam(st: &mut EditorState, pressed: VisualDirection) {
    let pos = st.cursor.position();
    if !st.engine.is_direction_boundary_at(pos) {
        // Not a seam: match what ClearPreferredX would have done.
        st.cursor_affinity = CursorAffinity::Downstream;
        return;
    }
    st.cursor_affinity = match pressed {
        VisualDirection::Right => CursorAffinity::Downstream,
        VisualDirection::Left => CursorAffinity::Upstream,
    };
}

/// Move the cursor to the start or end of the current visual line,
/// asking the typesetter for the line's logical extent. Solves two bugs
/// at once:
///  * A second End press after landing at line end is a no-op,
///    avoiding text-document's block-boundary ambiguity where
///    `get_block_at_position(block_end_pos)` returns the next block.
///  * Wrapped blocks stop at the wrap point (the standard editor
///    Home/End semantics).
///
/// Affinity handling: read the current `st.cursor_affinity` so the
/// range query picks the line the user is visually on (matters at
/// soft-wrap boundaries), then set it to match the edge just moved to —
/// Upstream when Home lands on a wrap continuation, Downstream
/// otherwise.
fn move_cursor_to_line_edge(st: &mut EditorState, edge: LineEdge, mode: MoveMode) {
    if !st.engine.has_full_layout() {
        return;
    }
    let pos = st.cursor.position();

    // Ask the typesetter for the line's logical extent rather than
    // hit-testing a far-off-screen x. The probe used to be purely
    // visual — leftmost for Home, rightmost for End — which is only the
    // same thing in left-to-right text; in an RTL paragraph the logical
    // start is drawn on the right, so Home and End landed on each
    // other's ends. Asking for the range directly sidesteps both that
    // and the question of how a hit-test clamps coordinates far outside
    // the text.
    let Some((line_start, line_end)) = st.engine.visual_line_range_at(pos, st.cursor_affinity)
    else {
        return;
    };

    let target = match edge {
        LineEdge::Start => line_start,
        LineEdge::End => line_end,
    };
    if target != pos {
        st.cursor.set_position(target, mode);
    }

    // Keep the caret drawn on the line it was sent to. Only a soft-wrap
    // boundary — a position that both ends one line and starts the next
    // — has two placements to choose between; anywhere else affinity is
    // a no-op and the convention is the `Downstream` default.
    //
    // End always wants Downstream (the end of the line it just moved
    // to). Home wants Upstream, but only where that means something: at
    // a block's first line, position 0 starts a line without ending one,
    // and claiming Upstream there would report a wrap continuation that
    // does not exist.
    let starts_a_wrap_continuation = |st: &EditorState, at: usize| {
        matches!(
            st.engine.visual_line_range_at(at, CursorAffinity::Downstream),
            Some((_, end)) if end == at
        )
    };
    st.cursor_affinity = match edge {
        LineEdge::Start if starts_a_wrap_continuation(st, target) => CursorAffinity::Upstream,
        LineEdge::Start | LineEdge::End => CursorAffinity::Downstream,
    };
}

/// Move the cursor up or down by one visual line, using the
/// typesetter's layout and `caret_rect` for the source position and
/// `hit_test` at the target Y to find the position on the next line.
/// Uses a sticky `preferred_x` so repeated vertical presses stay on
/// the same visual column even across short lines.
///
/// Called from `handle_key` with `state.borrow_mut()` already held.
///
/// Affinity: source `caret_rect` is queried with the current affinity
/// so vertical motion starts from the visually-correct line; the new
/// position's affinity is read off the hit-test (which sets Upstream
/// when the matched line's start coincides with the previous line's
/// end).
/// The vertical midpoint of the visual line one step `direction` from the one holding `pos`, in
/// document space — the y a hit test should probe to land on the neighbouring line.
///
/// **Not the caret's own height.** `caret_rect`'s height is the caret: ascent plus descent of
/// the text it sits in. The distance to the next line is the line's *advance*, which is larger
/// whenever the paragraph sets any line spacing above 1.0 — as prose typically does. Stepping by
/// the caret height then lands inside the line you started on, and the hit test hands back the
/// position you already had.
///
/// That failed asymmetrically, which is what made it easy to miss: moving **up** from the lower
/// part of a tall line still crosses into the previous line, so Up kept working while Down, from
/// the top of a line, never reached the next one and did nothing at all.
///
/// Derived from the real line geometry instead: the neighbouring line is found through the
/// character just past (or before) the current visual line, and its caret rect gives that line's
/// band. Falls back to the caret-height step only when the engine cannot name the line — better
/// an approximate move than none.
fn neighbour_line_center_y(
    st: &EditorState,
    pos: usize,
    direction: i32,
    caret: [f32; 4],
) -> Option<f32> {
    let fallback = || {
        let center_y = caret[1] + caret[3] * 0.5;
        Some(center_y + (direction as f32) * caret[3].max(16.0))
    };
    let Some((start, end)) = st.engine.visual_line_range_at(pos, st.cursor_affinity) else {
        return fallback();
    };

    // A position just outside the current visual line sits on the neighbouring one — but where
    // "just outside" is depends on how the line ended. `end` is exclusive: after a **soft wrap**
    // it is already the next line's first character, while after a **hard break** it is the
    // block's own end, which still maps back to the line being left. So going down, try both and
    // take the first that is genuinely lower; going up, the character before the line's start is
    // on the previous line either way.
    let candidates: [usize; 2] = if direction > 0 {
        [end, end.saturating_add(1)]
    } else if start == 0 {
        // Nothing above the first line.
        return None;
    } else {
        [start - 1, start.saturating_sub(2)]
    };

    // Ask with the affinity that binds a wrap boundary to the line being moved *to*.
    let affinity = if direction > 0 {
        CursorAffinity::Upstream
    } else {
        CursorAffinity::Downstream
    };
    for probe in candidates {
        let neighbour = st.engine.caret_rect(probe, affinity);
        // A degenerate rect names no line; and a rect on the wrong side of the caret is the
        // same line answering again, which is exactly the failure this function exists to fix.
        if neighbour[3] <= 0.0 {
            continue;
        }
        let crossed = if direction > 0 {
            neighbour[1] > caret[1]
        } else {
            neighbour[1] < caret[1]
        };
        if crossed {
            return Some(neighbour[1] + neighbour[3] * 0.5);
        }
    }
    fallback()
}

fn move_cursor_vertical(st: &mut EditorState, direction: i32, mode: MoveMode) {
    if !st.engine.has_full_layout() {
        return;
    }
    let pos = st.cursor.position();
    let caret = st.engine.caret_rect(pos, st.cursor_affinity);

    let x = st.preferred_x.unwrap_or(caret[0]);
    if st.preferred_x.is_none() {
        st.preferred_x = Some(caret[0]);
    }

    let Some(target_y) = neighbour_line_center_y(st, pos, direction, caret) else {
        return;
    };
    // Both ends of this comparison have to be in the space `caret_rect` and
    // `hit_test` speak — which is screen space, scroll already subtracted.
    // `content_height()` is the document's own height, measured from the top of
    // the text with no scrolling, so testing against it directly held only
    // while the editor was scrolled to the top: below that, the line above the
    // caret has a negative screen y and the guard threw away an ordinary
    // ArrowUp, and a caret the reader had scrolled off the top could not be
    // brought back with ArrowDown at all.
    let (content_top, content_bottom) = st.engine.content_band_screen();
    if target_y < content_top || target_y > content_bottom {
        return;
    }

    if let Some(hit) = st.engine.hit_test(x, target_y) {
        if hit.position != pos {
            st.cursor.set_position(hit.position, mode);
        }
        st.cursor_affinity = hit.affinity;
    }
}

/// Move the cursor up or down by roughly one viewport page, and
/// scroll so the caret stays visible. Like `move_cursor_vertical`,
/// uses a sticky preferred X.
fn move_cursor_page(st: &mut EditorState, direction: i32, mode: MoveMode) {
    if !st.engine.has_full_layout() {
        return;
    }
    let viewport_h = st.viewport_height;
    if viewport_h <= 0.0 {
        return;
    }
    let pos = st.cursor.position();
    let caret = st.engine.caret_rect(pos, st.cursor_affinity);
    let line_height = caret[3].max(16.0);
    let center_y = caret[1] + caret[3] * 0.5;

    let x = st.preferred_x.unwrap_or(caret[0]);
    if st.preferred_x.is_none() {
        st.preferred_x = Some(caret[0]);
    }

    // Move by one viewport minus one line so the reader keeps a
    // line of visual context across the page jump.
    let page_step = (viewport_h - line_height).max(line_height);
    let target_y =
        (center_y + (direction as f32) * page_step).clamp(0.0, st.engine.content_height());

    if let Some(hit) = st.engine.hit_test(x, target_y) {
        if hit.position != pos {
            st.cursor.set_position(hit.position, mode);
        }
        st.cursor_affinity = hit.affinity;
    }

    // Scroll so the new caret position is visible. We do a simple
    // viewport-height step on the scroll signal and let the frame
    // loop's `ensure_caret_visible` path clamp it.
    let new_scroll =
        (st.scroll_y.get() + (direction as f32) * page_step).clamp(0.0, st.max_scroll_y.get());
    st.scroll_y.set(new_scroll);
}

// ---------------------------------------------------------------------------
// Table / list helpers
// ---------------------------------------------------------------------------

/// Whether the caret's current block belongs to a list.
fn is_cursor_in_list(st: &EditorState) -> bool {
    let pos = st.cursor.position();
    st.document
        .block_at_position(pos)
        .and_then(|b| b.list())
        .is_some()
}

/// Move the current list item into its own list at `target_indent`,
/// preserving the parent list's style. Returns silently if the cursor
/// isn't in a list.
///
/// Why split instead of just updating the current list's indent:
/// `ListFormat::indent` applies to the whole list (all items share
/// one indent), so bumping it would shift every sibling. To indent
/// just the current item — the Tab/Shift-Tab behaviour users expect
/// from Word / Google Docs / Notion — we take the item out of its
/// current list and put it in a fresh list at the target depth.
///
/// Why `ListFormat::indent` and not `BlockFormat::indent`: the
/// typesetter reads list-item indentation from the **list's** format
/// (`text-typeset/src/bridge.rs`: `block.list_info.indent`), so
/// writing `BlockFormat::indent` on a list block has no visual effect.
///
/// Caveat: consecutive items Tabbed to the same depth each land in
/// their own list rather than sharing one. For bullet styles this is
/// visually indistinguishable; for ordered styles numbering restarts
/// per sublist. A future pass could merge with an adjacent sibling
/// list at the same `(style, indent)`.
fn nest_current_list_item(st: &mut EditorState, target_indent: u8) {
    let Some(list) = st.cursor.current_list() else {
        return;
    };
    let style = list.style();
    st.cursor.begin_edit_block();
    let _ = st.cursor.remove_current_block_from_list();
    let _ = st.cursor.create_list(style);
    let _ = st.cursor.set_current_list_format(&ListFormat {
        indent: Some(target_indent),
        ..Default::default()
    });
    st.cursor.end_edit_block();
}

/// Increase the current item's nesting depth by 1. Used by Tab
/// inside a list item. See [`nest_current_list_item`] for the split
/// rationale.
///
/// Exposed `pub(super)` so the parent `rich_text` module can wire it
/// into `RichTextEditor::indent` / `EditorHandle::indent` — toolbar
/// buttons need the same behaviour as Tab without going through key
/// dispatch.
pub(super) fn indent_current_block(st: &mut EditorState) {
    let Some(list) = st.cursor.current_list() else {
        return;
    };
    let level = list.indent();
    let target = level.saturating_add(1);
    if target == level {
        return;
    }
    nest_current_list_item(st, target);
}

/// Decrease the current item's nesting depth by 1. Used by Shift+Tab
/// inside a list item. At depth 0 this is a no-op (the user can press
/// Backspace at block-start to exit the list entirely).
///
/// Exposed `pub(super)` for the same reason as
/// [`indent_current_block`].
pub(super) fn dedent_current_block(st: &mut EditorState) {
    let Some(list) = st.cursor.current_list() else {
        return;
    };
    let level = list.indent();
    if level == 0 {
        return;
    }
    nest_current_list_item(st, level - 1);
}

/// Navigate to the next / previous table cell by `direction` (+1 or
/// -1). Wraps from end-of-row to start-of-next-row; at the last cell
/// of the last row with `direction = +1`, inserts a new row below
/// and moves into its first cell. Matches the godot reference's
/// `navigate_table_cell`.
fn navigate_table_cell(
    st: &mut EditorState,
    table_id: usize,
    row: usize,
    col: usize,
    rows: usize,
    cols: usize,
    direction: i32,
) {
    let (target_row, target_col) = if direction > 0 {
        if col + 1 < cols {
            (row, col + 1)
        } else if row + 1 < rows {
            (row + 1, 0)
        } else {
            // Last cell of last row → insert a new row and move
            // into its first cell.
            let _ = st.cursor.insert_row_below();
            (row + 1, 0)
        }
    } else if col > 0 {
        (row, col - 1)
    } else if row > 0 {
        (row - 1, cols.saturating_sub(1))
    } else {
        return; // already at the first cell
    };

    move_cursor_to_cell_first_block(st, table_id, target_row, target_col);
}

/// Enter inside a table cell: move to the cell in the same column one
/// row down; on the last row, step out of the table to the first
/// block that follows. Matches the godot reference's `navigate_table_cell_down`.
fn navigate_table_cell_down(
    st: &mut EditorState,
    table_id: usize,
    row: usize,
    col: usize,
    rows: usize,
) {
    if row + 1 < rows {
        move_cursor_to_cell_first_block(st, table_id, row + 1, col);
    } else {
        move_cursor_after_table(st, table_id);
    }
}

/// Move the caret to the first block of `(table_id, row, col)`. Uses
/// `table_cell_blocks_first_position` via the table handle obtained
/// through the current cursor's snapshot. No-op if the cell doesn't
/// exist.
fn move_cursor_to_cell_first_block(st: &mut EditorState, table_id: usize, row: usize, col: usize) {
    // Re-resolve the table via `current_table_cell` is insufficient
    // because after `insert_row_below` the cursor may still be in
    // the old cell. Walk the document's flow to find the table by
    // id, then ask the table for (row, col). This keeps the helper
    // free of assumptions about where the cursor currently sits.
    if let Some(table) = find_table_by_id(st, table_id)
        && let Some(cell) = table.cell(row, col)
        && let Some(block) = cell.blocks().first()
    {
        st.cursor
            .set_position(block.position(), MoveMode::MoveAnchor);
    }
}

/// Step the caret to the first block immediately following the given
/// table. If the table is the last element in the document, no-op.
fn move_cursor_after_table(st: &mut EditorState, table_id: usize) {
    use teksilo_text::text_document::FlowElement;
    let flow = st.document.flow();
    let mut found = false;
    for element in &flow {
        if found {
            match element {
                FlowElement::Block(block) => {
                    st.cursor
                        .set_position(block.position(), MoveMode::MoveAnchor);
                    return;
                }
                FlowElement::Table(t) => {
                    if let Some(cell) = t.cell(0, 0)
                        && let Some(block) = cell.blocks().first()
                    {
                        st.cursor
                            .set_position(block.position(), MoveMode::MoveAnchor);
                        return;
                    }
                }
                _ => {}
            }
        }
        if let FlowElement::Table(t) = element
            && t.id() == table_id
        {
            found = true;
        }
    }
}

/// Look up a table by id via the document's flow. Returns `None` if
/// the id isn't in the current flow.
fn find_table_by_id(
    st: &EditorState,
    table_id: usize,
) -> Option<teksilo_text::text_document::TextTable> {
    use teksilo_text::text_document::FlowElement;
    for element in st.document.flow() {
        if let FlowElement::Table(t) = element
            && t.id() == table_id
        {
            return Some(t);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Cell-range selection (Shift+Arrow when at a cell boundary)
// ---------------------------------------------------------------------------

/// Try to extend (or start) a rectangular cell selection in the
/// direction `(dcol, drow)`. Returns `true` when the event was
/// consumed (the caller must skip the normal text-range selection
/// path); returns `false` when the caret isn't at a cell boundary
/// eligible to start/extend a cell selection.
///
/// Mirrors the godot reference's IME preedit handling. The widget's
/// `selected_cell_range` state survives across calls so repeated
/// Shift+Arrow presses keep extending the rectangle.
pub(super) fn try_extend_cell_selection(st: &mut EditorState, dcol: i32, drow: i32) -> bool {
    use teksilo_text::text_document::SelectionKind;

    // If already in cell-selection mode, extend the existing range.
    if let SelectionKind::Cells(range)
    | SelectionKind::Mixed {
        cell_range: range, ..
    } = st.cursor.selection_kind()
    {
        // Use the cached table dimensions from the first selected
        // cell. If the range is degenerate we can't know the table
        // bounds reliably, so bail.
        let cells = st.cursor.selected_cells();
        let Some(first) = cells.first() else {
            return false;
        };
        let rows = first.table.rows();
        let cols = first.table.columns();
        if rows == 0 || cols == 0 {
            return false;
        }

        let new_end_row = (range.end_row as i32 + drow).clamp(0, rows as i32 - 1) as usize;
        let new_end_col = (range.end_col as i32 + dcol).clamp(0, cols as i32 - 1) as usize;

        st.cursor.select_cell_range(
            range.table_id,
            range.start_row,
            range.start_col,
            new_end_row,
            new_end_col,
        );
        return true;
    }

    // Not yet in cell-selection mode: check if the caret is at a cell
    // boundary that an arrow press would cross.
    let Some(cell_ref) = st.cursor.current_table_cell() else {
        return false;
    };
    let TableCellRef { table, row, column } = cell_ref;
    let at_start = st.cursor.at_block_start();
    let at_end = st.cursor.at_block_end();

    let should_activate = match (dcol, drow) {
        (-1, 0) => at_start && column > 0,
        (1, 0) => at_end && column + 1 < table.columns(),
        (0, -1) => at_start && row > 0,
        (0, 1) => at_end && row + 1 < table.rows(),
        _ => false,
    };
    if !should_activate {
        return false;
    }

    let table_id = table.id();
    let target_row = (row as i32 + drow).max(0) as usize;
    let target_col = (column as i32 + dcol).max(0) as usize;
    st.cursor.select_cell_range(
        table_id,
        row.min(target_row),
        column.min(target_col),
        row.max(target_row),
        column.max(target_col),
    );
    true
}

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

    // The chord → motion reading lives in `common::text_nav` and is tested
    // there against both conventions. These cover the other half: that each
    // motion, once resolved, reaches the right primitive — including the two
    // (`LineEdge`, `Document`, `Paragraph`) that no chord on a Linux host can
    // produce, and that a macOS run would otherwise be the first to exercise.

    #[test]
    fn a_word_step_walks_words_and_a_character_step_walks_characters() {
        assert_eq!(
            horizontal_op(true, CaretStep::Word),
            MoveOperation::WordRight
        );
        assert_eq!(
            horizontal_op(false, CaretStep::Word),
            MoveOperation::WordLeft
        );
        assert_eq!(
            horizontal_op(true, CaretStep::Character),
            MoveOperation::Right
        );
        assert_eq!(
            horizontal_op(false, CaretStep::Character),
            MoveOperation::Left
        );
    }

    #[test]
    fn the_line_edge_follows_the_direction_pressed() {
        // ⌘← is visual on macOS, so in right-to-left text — where `forward` is
        // false for a press to the *right* — it must reach the logical end.
        assert_eq!(line_edge_op(false), LineEdge::Start);
        assert_eq!(line_edge_op(true), LineEdge::End);
    }

    #[test]
    fn a_line_edge_step_never_becomes_a_stepping_primitive() {
        // The caller routes `LineEdge` away before `horizontal_op` sees it.
        // If that ever changes, the caret must still move by one character
        // rather than silently jumping a word.
        assert_eq!(
            horizontal_op(true, CaretStep::LineEdge),
            MoveOperation::Right
        );
        assert_eq!(
            horizontal_op(false, CaretStep::LineEdge),
            MoveOperation::Left
        );
    }

    #[test]
    fn vertical_document_and_paragraph_steps_reach_their_edges() {
        assert_eq!(
            vertical_op(LineStep::Document, false),
            Some(MoveOperation::Start)
        );
        assert_eq!(
            vertical_op(LineStep::Document, true),
            Some(MoveOperation::End)
        );
        assert_eq!(
            vertical_op(LineStep::Paragraph, false),
            Some(MoveOperation::StartOfBlock)
        );
        assert_eq!(
            vertical_op(LineStep::Paragraph, true),
            Some(MoveOperation::EndOfBlock)
        );
    }

    #[test]
    fn an_ordinary_line_step_is_left_to_the_typesetter() {
        // One visual line is not a logical primitive — a wrapped paragraph has
        // many, and only the typesetter knows where. `None` says "not mine".
        assert_eq!(vertical_op(LineStep::Line, false), None);
        assert_eq!(vertical_op(LineStep::Line, true), None);
    }
}