gpui-kit-markdown-editor 0.1.0

A block-based WYSIWYG Markdown editor for GPUI, built on gpui-kit's editor host API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
//! `BlockEditorState`: the entity around [`BlockEditorModel`] (design §6).

use super::input_rule::RuleKind;
use std::sync::Arc;
use std::{cell::RefCell, ops::Range, rc::Rc};

use gpui::{
    App, AppContext, Bounds, ClipboardItem, Context, Entity, EntityInputHandler, EventEmitter,
    FocusHandle, Focusable, KeyBinding, Pixels, Point, SharedString, Subscription, UTF16Selection,
    Window, actions,
};

use super::{
    command::{CommandError, EditorCommand},
    editor::BlockEditorModel,
    frame::FrameLayout,
    id::BlockId,
    kind::BlockKind,
    marks::MarkKind,
    position::BlockPosition,
    projection::{ProjectionCache, Snapshot},
    selection::BlockSelection,
    style::BlockEditorStyle,
    transaction::EditOrigin,
};
use crate::support::BlinkCursor;
use gpui_kit::base::text::MarkdownExtensions;

pub(crate) const CONTEXT: &str = "BlockEditor";

actions!(
    block_editor,
    [
        Backspace,
        Delete,
        Enter,
        StructuralEnter,
        MoveLeft,
        MoveRight,
        MoveUp,
        MoveDown,
        MoveHome,
        MoveEnd,
        SelectLeft,
        SelectRight,
        SelectUp,
        SelectDown,
        SelectHome,
        SelectEnd,
        MoveDocStart,
        MoveDocEnd,
        SelectDocStart,
        SelectDocEnd,
        SelectAll,
        MoveWordLeft,
        MoveWordRight,
        SelectWordLeft,
        SelectWordRight,
        Undo,
        Redo,
        ToggleBold,
        ToggleItalic,
        EditLink,
        SoftBreak,
        ExitBlock,
        ToggleCode,
        NormalText,
        TableInsertColumnLeft,
        TableInsertColumnRight,
        TableInsertRowAbove,
        TableInsertRowBelow,
        TableDeleteLine,
        CloseTableMenu,
        Indent,
        Outdent,
        Copy,
        Cut,
        Paste,
        PastePlain,
        DeleteWordLeft,
        DeleteWordRight,
        DeleteToLineStart,
        DeleteToLineEnd,
        MoveParagraphStart,
        MoveParagraphEnd,
        SelectParagraphStart,
        SelectParagraphEnd,
    ]
);

pub(crate) fn init(cx: &mut App) {
    let ctx = Some(CONTEXT);
    #[cfg(target_os = "macos")]
    let m = "cmd";
    #[cfg(not(target_os = "macos"))]
    let m = "ctrl";
    // Word motion: Option on macOS, Ctrl elsewhere.
    #[cfg(target_os = "macos")]
    let w = "alt";
    #[cfg(not(target_os = "macos"))]
    let w = "ctrl";
    // Document start/end: Ctrl+Home/End (Cmd+Home/End also work on macOS,
    // next to Cmd+Up/Down).
    let doc = m;
    cx.bind_keys(vec![
        KeyBinding::new("backspace", Backspace, ctx),
        KeyBinding::new("delete", Delete, ctx),
        KeyBinding::new("enter", Enter, ctx),
        KeyBinding::new("left", MoveLeft, ctx),
        KeyBinding::new("right", MoveRight, ctx),
        KeyBinding::new("up", MoveUp, ctx),
        KeyBinding::new("down", MoveDown, ctx),
        KeyBinding::new("home", MoveHome, ctx),
        KeyBinding::new("end", MoveEnd, ctx),
        KeyBinding::new(&format!("{w}-left"), MoveWordLeft, ctx),
        KeyBinding::new(&format!("{w}-right"), MoveWordRight, ctx),
        KeyBinding::new(&format!("{w}-shift-left"), SelectWordLeft, ctx),
        KeyBinding::new(&format!("{w}-shift-right"), SelectWordRight, ctx),
        KeyBinding::new("shift-left", SelectLeft, ctx),
        KeyBinding::new("shift-right", SelectRight, ctx),
        KeyBinding::new("shift-up", SelectUp, ctx),
        KeyBinding::new("shift-down", SelectDown, ctx),
        KeyBinding::new("shift-home", SelectHome, ctx),
        KeyBinding::new("shift-end", SelectEnd, ctx),
        KeyBinding::new(&format!("{doc}-home"), MoveDocStart, ctx),
        KeyBinding::new(&format!("{doc}-end"), MoveDocEnd, ctx),
        KeyBinding::new(&format!("{doc}-shift-home"), SelectDocStart, ctx),
        KeyBinding::new(&format!("{doc}-shift-end"), SelectDocEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-up", MoveDocStart, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-down", MoveDocEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-shift-up", SelectDocStart, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-shift-down", SelectDocEnd, ctx),
        // D21: word deletes (Option on macOS, Ctrl elsewhere).
        KeyBinding::new(&format!("{w}-backspace"), DeleteWordLeft, ctx),
        KeyBinding::new(&format!("{w}-delete"), DeleteWordRight, ctx),
        // D21: macOS line keys and the emacs bindings of Cocoa text fields.
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-backspace", DeleteToLineStart, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-delete", DeleteToLineEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-k", DeleteToLineEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-a", MoveHome, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-e", MoveEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-shift-a", SelectHome, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-shift-e", SelectEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-d", Delete, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("ctrl-h", Backspace, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-left", MoveHome, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-right", MoveEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-shift-left", SelectHome, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-shift-right", SelectEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("alt-up", MoveParagraphStart, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("alt-down", MoveParagraphEnd, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("alt-shift-up", SelectParagraphStart, ctx),
        #[cfg(target_os = "macos")]
        KeyBinding::new("alt-shift-down", SelectParagraphEnd, ctx),
        // Elsewhere paragraph motion is Ctrl+Up/Down (Ctrl+Alt+arrows stay
        // the table keys, Ctrl+Home/End the document edges).
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-up", MoveParagraphStart, ctx),
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-down", MoveParagraphEnd, ctx),
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-shift-up", SelectParagraphStart, ctx),
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-shift-down", SelectParagraphEnd, ctx),
        KeyBinding::new("tab", Indent, ctx),
        KeyBinding::new("shift-tab", Outdent, ctx),
        KeyBinding::new(&format!("{m}-a"), SelectAll, ctx),
        KeyBinding::new(&format!("{m}-z"), Undo, ctx),
        KeyBinding::new(&format!("{m}-shift-z"), Redo, ctx),
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-y", Redo, ctx),
        KeyBinding::new(&format!("{m}-b"), ToggleBold, ctx),
        KeyBinding::new(&format!("{m}-i"), ToggleItalic, ctx),
        KeyBinding::new(&format!("{m}-e"), ToggleCode, ctx),
        KeyBinding::new(&format!("{m}-k"), EditLink, ctx),
        // "Normal text": the block (or each selected block) becomes a paragraph.
        KeyBinding::new(&format!("{m}-alt-0"), NormalText, ctx),
        // Tables (D20): only act with the caret or a cell selection in a
        // table; elsewhere the keystroke propagates.
        KeyBinding::new(&format!("{m}-alt-left"), TableInsertColumnLeft, ctx),
        KeyBinding::new(&format!("{m}-alt-right"), TableInsertColumnRight, ctx),
        KeyBinding::new(&format!("{m}-alt-up"), TableInsertRowAbove, ctx),
        KeyBinding::new(&format!("{m}-alt-down"), TableInsertRowBelow, ctx),
        KeyBinding::new(&format!("{m}-alt-backspace"), TableDeleteLine, ctx),
        KeyBinding::new("escape", CloseTableMenu, Some("BlockEditor && table_menu")),
        KeyBinding::new("shift-enter", SoftBreak, ctx),
        KeyBinding::new(&format!("{m}-enter"), ExitBlock, ctx),
        KeyBinding::new(&format!("{m}-c"), Copy, ctx),
        KeyBinding::new(&format!("{m}-x"), Cut, ctx),
        KeyBinding::new(&format!("{m}-v"), Paste, ctx),
        KeyBinding::new(&format!("{m}-shift-v"), PastePlain, ctx),
        // Composer overrides only; standalone Newline/ModifiedEnter keep
        // Shift+Enter soft breaks and the platform secondary-Enter command.
        KeyBinding::new(
            "shift-enter",
            StructuralEnter,
            Some("BlockEditor && submit == enter"),
        ),
        KeyBinding::new(
            "ctrl-enter",
            SoftBreak,
            Some("BlockEditor && submit == enter"),
        ),
    ]);
}

/// Clipboard metadata that marks a copy as the editor's own inline Markdown
/// (D17). Paste parses tagged text as inline Markdown; untagged text keeps
/// the conservative import.
pub(crate) const COPY_TAG: &str = "gpui-kit/block-editor/inline-markdown/v1";

/// Clipboard metadata for a copy of several blocks, written as Markdown
/// (headings, lists, quotes, code, tables, tasks and marks). Paste parses it
/// back into blocks.
pub(crate) const BLOCKS_COPY_TAG: &str = "gpui-kit/block-editor/blocks-markdown/v1";

/// What the clipboard item says about where it came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CopyKind {
    /// Text from elsewhere: the conservative import.
    External,
    /// The editor's own copy inside one block: inline Markdown (D17).
    Inline,
    /// The editor's own copy of whole or partial blocks: block Markdown.
    Blocks,
}

impl CopyKind {
    fn of(item: &ClipboardItem) -> Self {
        match item.metadata() {
            Some(m) if m == COPY_TAG => Self::Inline,
            Some(m) if m == BLOCKS_COPY_TAG => Self::Blocks,
            _ => Self::External,
        }
    }

    fn tag(self) -> Option<&'static str> {
        match self {
            Self::External => None,
            Self::Inline => Some(COPY_TAG),
            Self::Blocks => Some(BLOCKS_COPY_TAG),
        }
    }
}

/// Events emitted by [`BlockEditorState`].
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum BlockEditorEvent {
    /// Once per committed transaction, including undo and redo.
    Changed {
        revision: u64,
        origin: EditOrigin,
    },
    SelectionChanged,
    /// Cmd/Ctrl+K: the host should show its link popover (D14) for the
    /// selection or the link at the caret, then call
    /// [`BlockEditorState::set_link`]. `url` is the current link, if any.
    EditLinkRequested {
        url: Option<SharedString>,
    },
    /// Cmd/Ctrl+click on a link. The editor never opens a browser.
    LinkClicked {
        url: SharedString,
    },
    /// The link under the mouse changed (`None` when it left a link).
    LinkHovered {
        url: Option<SharedString>,
    },
    Focus,
    Blur,
    /// Enter requested submission; emitted only outside IME composition. The
    /// owner applies completion/picker and domain-send policy, in that order.
    SubmitRequested,
    /// Semantic paste interception, shared by keyboard and native actions.
    /// The owner must resolve this request with `apply_paste`; stale requests
    /// are rejected instead of pasting into a later selection/document.
    PasteRequested {
        request: PasteRequest,
        item: ClipboardItem,
    },
}

/// Which Enter action requests submission. Newline is the document-editor default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SubmitPolicy {
    #[default]
    Newline,
    /// Enter submits; Shift+Enter edits structurally and Ctrl+Enter inserts
    /// a cell soft break. On macOS Cmd+Enter also submits.
    Enter,
    ModifiedEnter,
}

/// Whether paste uses editor defaults or is first offered to the host.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClipboardPolicy {
    #[default]
    Editor,
    Host,
}

type InputRuleFilter = Arc<dyn Fn(super::InputRule, &str) -> bool + Send + Sync>;

/// An intercepted semantic paste tied to the editor's current document and
/// selection. Resolve once; no synthetic key events or OS clipboard access is
/// needed when delivering an explicit `ClipboardItem`.
#[derive(Clone, Debug)]
pub struct PasteRequest {
    range: super::CapturedRange,
    plain: bool,
    /// Where the item came from (the editor's own tagged copies, D17).
    copy: CopyKind,
    sequence: u64,
}

/// D22: a press on a top-level block's handle. It becomes a reorder drag
/// once the pointer moves past a small threshold; until then the press is
/// an ordinary click.
#[derive(Clone, Copy, Debug)]
pub(crate) struct BlockDrag {
    pub(crate) block: BlockId,
    pub(crate) start: Point<Pixels>,
    pub(crate) active: bool,
    /// The gap between top-level blocks the block would drop into.
    pub(crate) drop: Option<usize>,
}

/// IME composition in progress: the marked byte range in one leaf.
#[derive(Clone, Debug)]
struct Marked {
    block: BlockId,
    range: Range<usize>,
}

pub struct BlockEditorState {
    pub(crate) model: BlockEditorModel,
    pub(crate) focus_handle: FocusHandle,
    pub(crate) blink_cursor: Entity<BlinkCursor>,
    pub(crate) style: BlockEditorStyle,
    pub(crate) projection: ProjectionCache,
    /// Last complete frame, written by the element after prepaint.
    pub(crate) frame: Rc<RefCell<FrameLayout>>,
    pub(crate) cull: Rc<RefCell<super::cull::CullState>>,
    /// The accessible value (document text), cached per revision (D8).
    pub(crate) a11y_value: RefCell<Option<(u64, SharedString)>>,
    /// Scroll container to keep the caret in view (see `set_scroll_handle`).
    pub(crate) scroll_handle: Option<gpui::ScrollHandle>,
    /// The caret moved and should be scrolled into view after layout.
    pub(crate) reveal: std::cell::Cell<bool>,
    marked: Option<Marked>,
    /// An IME composition opened an undo group that is not committed yet.
    composition_open: bool,
    /// Remembered x for repeated up/down.
    goal_x: Option<Pixels>,
    pub(crate) dragging: bool,
    /// A press on a block handle, and the drag to reorder it (D22).
    pub(crate) block_drag: Option<BlockDrag>,
    readonly: bool,
    image_policy: super::ImagePolicy,
    submit_policy: SubmitPolicy,
    clipboard_policy: ClipboardPolicy,
    paste_sequence: u64,
    pending_paste: Option<u64>,
    input_rules: Vec<super::input_rule::InputRule>,
    input_rule_filter: Option<InputRuleFilter>,
    hovered_link: Option<SharedString>,
    /// The mouse is over a task checkbox, or a link with Cmd/Ctrl held.
    pub(crate) pointer_hand: bool,
    /// The open table grip menu (D20).
    pub(crate) table_menu: Option<super::table_ui::TableMenu>,
    /// The table grips the pointer shows (to repaint on change).
    pub(crate) table_hover: Vec<(BlockId, crate::TableLine)>,
    /// The pointer is on a table grip (grab cursor).
    pub(crate) grip_hover: bool,
    _subscriptions: Vec<Subscription>,
}

impl EventEmitter<BlockEditorEvent> for BlockEditorState {}

impl Focusable for BlockEditorState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl BlockEditorState {
    /// Create an editor holding one empty paragraph.
    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
        let focus_handle = cx.focus_handle();
        let blink_cursor = cx.new(|_| BlinkCursor::new());
        // Focus and blink wiring as in `InputBaseState::new_in_mode` (§7.1).
        let subscriptions = vec![
            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
            cx.on_focus(&focus_handle, window, |this, _, cx| {
                this.blink_cursor.update(cx, |b, cx| b.start(cx));
                cx.emit(BlockEditorEvent::Focus);
            }),
            cx.on_blur(&focus_handle, window, |this, _, cx| {
                this.blink_cursor.update(cx, |b, cx| b.stop(cx));
                this.model.break_coalescing();
                this.end_composition();
                cx.emit(BlockEditorEvent::Blur);
            }),
            cx.observe_window_activation(window, |this, window, cx| {
                if window.is_window_active() && this.focus_handle.is_focused(window) {
                    this.blink_cursor.update(cx, |b, cx| b.start(cx));
                }
            }),
        ];
        let model = BlockEditorModel::from_markdown("", MarkdownExtensions::default())
            .unwrap_or_else(|_| unreachable!("empty source always parses"));
        Self {
            model,
            focus_handle,
            blink_cursor,
            style: BlockEditorStyle::default(),
            projection: ProjectionCache::default(),
            frame: Rc::default(),
            cull: Rc::default(),
            a11y_value: RefCell::default(),
            scroll_handle: Some(gpui::ScrollHandle::new()),
            reveal: Default::default(),
            marked: None,
            composition_open: false,
            goal_x: None,
            dragging: false,
            block_drag: None,
            readonly: false,
            image_policy: super::ImagePolicy::default(),
            submit_policy: SubmitPolicy::default(),
            clipboard_policy: ClipboardPolicy::default(),
            paste_sequence: 0,
            pending_paste: None,
            input_rules: super::input_rule::InputRule::markdown_defaults(),
            input_rule_filter: None,
            hovered_link: None,
            pointer_hand: false,
            table_menu: None,
            table_hover: Vec::new(),
            grip_hover: false,
            _subscriptions: subscriptions,
        }
    }

    pub fn with_submit_policy(mut self, policy: SubmitPolicy) -> Self {
        self.submit_policy = policy;
        self
    }
    /// Replace the policy; notify the editor after changing it so the
    /// retained view's policy-scoped key context is refreshed.
    pub fn set_submit_policy(&mut self, policy: SubmitPolicy) {
        self.submit_policy = policy;
    }
    pub(crate) fn key_context(&self) -> &'static str {
        match (
            self.submit_policy == SubmitPolicy::Enter,
            self.table_menu.is_some(),
        ) {
            (true, false) => "BlockEditor submit=enter",
            (true, true) => "BlockEditor submit=enter table_menu",
            (false, false) => CONTEXT,
            (false, true) => "BlockEditor table_menu",
        }
    }
    pub fn with_clipboard_policy(mut self, policy: ClipboardPolicy) -> Self {
        self.clipboard_policy = policy;
        self
    }
    pub fn set_clipboard_policy(&mut self, policy: ClipboardPolicy) {
        self.clipboard_policy = policy;
    }
    /// The retained scroll owner; content-sized wrappers share this handle.
    pub fn scroll_handle(&self) -> Option<gpui::ScrollHandle> {
        self.scroll_handle.clone()
    }

    /// Builder: the Markdown input rules to run while typing (D13). The
    /// default is [`InputRule::markdown_defaults`](super::InputRule); pass an
    /// empty list to type Markdown literally.
    pub fn with_input_rules(
        mut self,
        rules: impl IntoIterator<Item = super::input_rule::InputRule>,
    ) -> Self {
        self.input_rules = rules.into_iter().collect();
        self
    }

    /// Pure policy invoked before an enabled input rule rewrites typed content.
    /// Return false when a host workflow (e.g. completion) owns the same sigil.
    /// Receives leaf-native text before the caret, never serialized offsets;
    /// must not perform I/O or re-enter the editor. Defaults to allowing rules.
    pub fn with_input_rule_filter(
        mut self,
        filter: impl Fn(super::InputRule, &str) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.input_rule_filter = Some(Arc::new(filter));
        self
    }

    /// Replace the input rules (see [`Self::with_input_rules`]).
    pub fn set_input_rules(
        &mut self,
        rules: impl IntoIterator<Item = super::input_rule::InputRule>,
    ) {
        self.input_rules = rules.into_iter().collect();
    }

    /// Check or uncheck the task item holding `block` (a list item or its
    /// text leaf); one undo step (D14). The selection is kept.
    pub fn set_task_checked(&mut self, block: BlockId, checked: bool, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        let leaf = if self.model.doc.inline(block).is_some() {
            block
        } else {
            match self.model.doc.children(block).first() {
                Some(child) => *child,
                None => return,
            }
        };
        self.model.break_coalescing();
        self.edit(
            EditOrigin::Command("set_task_checked"),
            |m| m.set_item_checked(leaf, checked).map(|_| ()),
            cx,
        );
        self.model.break_coalescing();
    }

    fn rule_on(&self, kind: super::input_rule::RuleKind) -> bool {
        self.input_rules.iter().any(|rule| rule.0 == kind)
            && self.input_rule_filter.as_ref().is_none_or(|filter| {
                filter(
                    super::InputRule(kind),
                    self.model.caret_prefix().unwrap_or_default(),
                )
            })
    }

    /// Builder: initial Markdown.
    pub fn with_source(mut self, source: &str) -> Self {
        let _ = self.model.set_source(source);
        self.projection.invalidate();
        self
    }

    /// Replace the content. No `Changed` event; clears history.
    pub fn set_source(&mut self, source: &str, cx: &mut Context<Self>) -> Result<(), SharedString> {
        self.model.set_source(source)?;
        self.marked = None;
        self.composition_open = false;
        self.pending_paste = None;
        self.projection.invalidate();
        cx.notify();
        Ok(())
    }

    /// The document as canonical Markdown.
    pub fn source(&self) -> String {
        self.model.source()
    }

    /// Shared canonical source, materialized at most once per revision.
    pub fn source_snapshot(&self) -> super::SourceSnapshot {
        self.model.source_snapshot()
    }

    pub fn capture_caret(&self) -> Result<super::CapturedRange, super::CapturedRangeError> {
        self.model.capture_caret()
    }
    pub fn capture_selection(&self) -> Result<super::CapturedRange, super::CapturedRangeError> {
        self.model.capture_selection()
    }
    pub fn capture_suffix(
        &self,
        len: usize,
    ) -> Result<super::CapturedRange, super::CapturedRangeError> {
        self.model.capture_suffix(len)
    }
    pub fn capture_leaf_range(
        &self,
        range: std::ops::Range<usize>,
    ) -> Result<super::CapturedRange, super::CapturedRangeError> {
        self.model.capture_leaf_range(range)
    }
    /// Configure presentation/resource admission without mutating the document.
    pub fn with_image_policy(mut self, policy: super::ImagePolicy) -> Self {
        self.image_policy = policy;
        self
    }
    pub fn set_image_policy(&mut self, policy: super::ImagePolicy, cx: &mut Context<Self>) {
        self.image_policy = policy;
        self.projection.invalidate();
        cx.notify();
    }
    pub fn image_policy(&self) -> super::ImagePolicy {
        self.image_policy
    }

    pub fn caret_prefix_snapshot(&self) -> Option<SharedString> {
        self.model.caret_prefix_snapshot()
    }
    pub fn caret_prefix(&self) -> Option<&str> {
        self.model.caret_prefix()
    }
    pub fn is_capture_current(&self, range: &super::CapturedRange) -> bool {
        self.model.is_capture_current(range)
    }
    pub fn replace_captured(
        &mut self,
        range: &mut super::CapturedRange,
        text: &str,
        cx: &mut Context<Self>,
    ) -> Result<(), super::CapturedRangeError> {
        if self.readonly || self.marked.is_some() {
            return Err(super::CapturedRangeError::Stale);
        }
        self.model.replace_captured(range, text)?;
        self.after_edit(EditOrigin::Api, cx);
        Ok(())
    }
    pub fn select_end(&mut self, cx: &mut Context<Self>) -> Result<(), super::SelectionError> {
        self.model.select_end()?;
        self.selection_changed(cx);
        Ok(())
    }
    /// Reveal the current caret after viewport/layout changes without moving it.
    pub fn reveal_caret(&mut self, cx: &mut Context<Self>) {
        self.reveal.set(true);
        cx.notify();
    }
    /// Fence host callbacks on external owner changes without reparsing content.
    pub fn invalidate_captures(&mut self) {
        self.model.invalidate_captures();
        self.pending_paste = None;
    }
    pub fn is_composing(&self) -> bool {
        self.marked.is_some()
    }

    /// The headless model (document, selection, history).
    pub fn model(&self) -> &BlockEditorModel {
        &self.model
    }

    /// Document revision; bumped by every committed transaction.
    pub fn revision(&self) -> u64 {
        self.model.revision()
    }

    /// The current selection.
    pub fn selection(&self) -> &BlockSelection {
        self.model.selection()
    }

    /// Kind of the text block holding the caret, if any.
    pub fn block_kind_at_caret(&self) -> Option<BlockKind> {
        self.model.block_kind_at_caret()
    }

    /// Override caret, selection and composition colours (`BlockEditorStyle`).
    pub fn set_editor_style(&mut self, style: BlockEditorStyle, cx: &mut Context<Self>) {
        self.style = style;
        cx.notify();
    }

    /// The editor style overrides in effect.
    pub fn editor_style(&self) -> &BlockEditorStyle {
        &self.style
    }

    /// The scroll container the editor sits in (its `track_scroll` handle).
    /// With one set, the caret is scrolled into view after it moves; blocks
    /// outside the container's visible area are culled either way.
    pub fn set_scroll_handle(&mut self, handle: gpui::ScrollHandle) {
        self.scroll_handle = Some(handle);
    }

    /// Whether edits are blocked (navigation and selection still work).
    pub fn is_readonly(&self) -> bool {
        self.readonly
    }

    /// Block or allow edits.
    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
        self.readonly = readonly;
        cx.notify();
    }

    /// Focus the editor.
    pub fn focus(&self, window: &mut Window, cx: &mut App) {
        window.focus(&self.focus_handle, cx);
    }

    /// Set the selection; emits `SelectionChanged`.
    pub fn set_selection(
        &mut self,
        selection: BlockSelection,
        cx: &mut Context<Self>,
    ) -> Result<(), super::SelectionError> {
        self.model.set_selection(selection)?;
        self.selection_changed(cx);
        Ok(())
    }

    /// Run a model command as one transaction.
    pub fn run(
        &mut self,
        command: EditorCommand,
        cx: &mut Context<Self>,
    ) -> Result<bool, CommandError> {
        if self.readonly {
            return Ok(false);
        }
        let name = command_name(&command);
        self.end_composition();
        let revision = self.model.revision();
        let changed = self.model.run(command)?;
        if self.model.revision() != revision {
            self.after_edit(EditOrigin::Command(name), cx);
        } else {
            // Stored-mark toggles change no text but show in the toolbar.
            cx.notify();
        }
        Ok(changed)
    }

    /// Undo the last transaction (or IME composition) group.
    pub fn undo(&mut self, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        if self.model.undo() {
            self.after_edit(EditOrigin::Undo, cx);
        }
    }

    /// Redo the last undone group.
    pub fn redo(&mut self, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        if self.model.redo() {
            self.after_edit(EditOrigin::Redo, cx);
        }
    }

    /// The document as plain text for assistive technology (D8): leaves in
    /// order, one per line, inline atoms dropped. Built at most once per
    /// revision, and only asked for while accessibility is active.
    pub(crate) fn accessible_value(&self) -> SharedString {
        let revision = self.model.revision();
        if let Some((cached, value)) = &*self.a11y_value.borrow()
            && *cached == revision
        {
            return value.clone();
        }
        let doc = &self.model.doc;
        let value: SharedString = doc
            .leaves()
            .iter()
            .filter_map(|id| doc.leaf_text(*id))
            .map(|text| text.replace(super::inline::ATOM_CHAR, ""))
            .collect::<Vec<_>>()
            .join("\n")
            .into();
        *self.a11y_value.borrow_mut() = Some((revision, value.clone()));
        value
    }

    pub(crate) fn snapshot(&mut self) -> Rc<Snapshot> {
        self.projection
            .set_placeholders(self.image_policy == super::ImagePolicy::Placeholder);
        self.projection.snapshot(&self.model.doc)
    }

    /// Blocks that are always laid out: the selection ends, the IME
    /// composition, and their ancestors.
    pub(crate) fn pinned_blocks(&self) -> Vec<BlockId> {
        let doc = &self.model.doc;
        let mut ids = match self.model.selection() {
            BlockSelection::Text { anchor, head } => vec![anchor.block, head.block],
            BlockSelection::Blocks { anchor, head } | BlockSelection::Cells { anchor, head } => {
                vec![*anchor, *head]
            }
        };
        if let Some((block, _)) = self.marked_range() {
            ids.push(block);
        }
        // Every ancestor, so a chunk of a long list holding the caret's item
        // is pinned too.
        ids.into_iter().flat_map(|id| doc.path(id)).collect()
    }

    /// Per-leaf selected byte ranges, for painting.
    pub(crate) fn selection_ranges(&self) -> Vec<(BlockId, Range<usize>)> {
        if let Some(cells) = self.model.selected_cells() {
            return cells
                .into_iter()
                .flatten()
                .map(|c| (c, 0..self.model.doc.leaf_len(c).unwrap_or(0)))
                .collect();
        }
        let Ok(range) = self.model.doc.resolve_selection(self.model.selection()) else {
            return Vec::new();
        };
        if range.is_collapsed() {
            return Vec::new();
        }
        self.model
            .text_ranges(range)
            .into_iter()
            .map(|(id, lo, hi)| (id, lo..hi))
            .collect()
    }

    pub(crate) fn marked_range(&self) -> Option<(BlockId, Range<usize>)> {
        self.marked.as_ref().map(|m| (m.block, m.range.clone()))
    }

    pub(crate) fn show_caret(&self, window: &Window, cx: &App) -> bool {
        self.focus_handle.is_focused(window) && self.blink_cursor.read(cx).visible()
    }

    // ---- internal edit plumbing -------------------------------------------

    fn after_edit(&mut self, origin: EditOrigin, cx: &mut Context<Self>) {
        self.goal_x = None;
        self.reveal.set(true);
        self.pause_blink(cx);
        cx.emit(BlockEditorEvent::Changed {
            revision: self.model.revision(),
            origin,
        });
        cx.emit(BlockEditorEvent::SelectionChanged);
        cx.notify();
    }

    fn selection_changed(&mut self, cx: &mut Context<Self>) {
        self.reveal.set(true);
        self.pause_blink(cx);
        cx.emit(BlockEditorEvent::SelectionChanged);
        cx.notify();
    }

    fn pause_blink(&mut self, cx: &mut Context<Self>) {
        self.blink_cursor.update(cx, |b, cx| b.pause(cx));
    }

    fn edit(
        &mut self,
        origin: EditOrigin,
        f: impl FnOnce(&mut BlockEditorModel) -> Result<(), CommandError>,
        cx: &mut Context<Self>,
    ) {
        if self.readonly {
            return;
        }
        let revision = self.model.revision();
        // Errors (e.g. typing into a code block, Phase 4) leave the document
        // untouched; the spike ignores them.
        let _ = f(&mut self.model);
        if self.model.revision() != revision {
            self.after_edit(origin, cx);
        } else {
            cx.notify();
        }
    }

    fn end_composition(&mut self) {
        self.marked = None;
        if std::mem::take(&mut self.composition_open) {
            self.model.history.commit_transaction();
        }
    }

    /// Whether an IME undo group is open (tests: it must never leak).
    #[cfg(test)]
    pub(crate) fn composition_open(&self) -> bool {
        self.composition_open
    }

    /// A whole-block selection collapses to its start or end.
    fn collapse_blocks(&mut self, forward: bool, cx: &mut Context<Self>) -> bool {
        if !matches!(
            self.model.selection(),
            BlockSelection::Blocks { .. } | BlockSelection::Cells { .. }
        ) {
            return false;
        }
        if let Ok(range) = self.model.doc.resolve_selection(self.model.selection()) {
            let target = if forward { range.end } else { range.start };
            self.move_to(target, false, cx);
        }
        true
    }

    fn head_anchor(&self) -> Option<(BlockPosition, BlockPosition)> {
        match self.model.selection() {
            BlockSelection::Text { anchor, head } => Some((*anchor, *head)),
            BlockSelection::Blocks { .. } => None,
            BlockSelection::Cells { anchor, head } => {
                Some((BlockPosition::new(*anchor, 0), BlockPosition::new(*head, 0)))
            }
        }
    }

    fn move_to(&mut self, head: BlockPosition, extend: bool, cx: &mut Context<Self>) {
        let anchor = match (extend, self.head_anchor()) {
            (true, Some((anchor, _))) => anchor,
            _ => head,
        };
        self.end_composition();
        // A drag or Shift+arrow from one cell into another of the same table
        // selects cells, not text.
        let doc = &self.model.doc;
        let selection = match (
            super::table::table_of(doc, anchor.block),
            super::table::table_of(doc, head.block),
        ) {
            (Some(a), Some(b)) if a == b && anchor.block != head.block => BlockSelection::Cells {
                anchor: anchor.block,
                head: head.block,
            },
            _ => BlockSelection::Text { anchor, head },
        };
        let _ = self.model.set_selection(selection);
        self.selection_changed(cx);
    }

    /// One grapheme left/right, crossing leaf boundaries in document order.
    pub(crate) fn step_horizontal(&self, pos: BlockPosition, forward: bool) -> BlockPosition {
        let doc = &self.model.doc;
        let len = doc.leaf_len(pos.block).unwrap_or(0);
        if let Some(code) = doc.plain(pos.block) {
            let next = if forward {
                code[pos.offset..]
                    .chars()
                    .next()
                    .map(|c| pos.offset + c.len_utf8())
            } else {
                code[..pos.offset]
                    .chars()
                    .next_back()
                    .map(|c| pos.offset - c.len_utf8())
            };
            if let Some(offset) = next {
                return BlockPosition::new(pos.block, offset);
            }
        } else if let Some(inline) = doc.inline(pos.block) {
            let next = if forward {
                inline.next_grapheme(pos.offset)
            } else {
                inline.prev_grapheme(pos.offset)
            };
            if let Some(offset) = next.filter(|o| *o != pos.offset) {
                return BlockPosition::new(pos.block, offset);
            }
        } else if forward && pos.offset == 0 {
            return BlockPosition::new(pos.block, 1);
        } else if !forward && pos.offset == 1 {
            return BlockPosition::new(pos.block, 0);
        }
        let leaves = doc.leaves();
        let Some(ix) = leaves.iter().position(|id| *id == pos.block) else {
            return pos;
        };
        let neighbour = if forward {
            leaves.get(ix + 1)
        } else {
            ix.checked_sub(1).and_then(|i| leaves.get(i))
        };
        match neighbour {
            Some(id) if forward => BlockPosition::new(*id, 0),
            Some(id) => BlockPosition::new(*id, doc.leaf_len(*id).unwrap_or(0)),
            None => BlockPosition::new(pos.block, if forward { len } else { 0 }),
        }
    }

    /// The next word boundary from `pos` (skip spaces, then a word); at a
    /// leaf edge, one step into the neighbouring leaf.
    fn step_word(&self, pos: BlockPosition, forward: bool) -> BlockPosition {
        let Some(text) = self.model.doc.leaf_text(pos.block) else {
            return self.step_horizontal(pos, forward);
        };
        let is_word = |c: char| c.is_alphanumeric() || c == '_';
        let mut offset = pos.offset;
        if forward {
            let rest = &text[offset..];
            let mut it = rest.char_indices().peekable();
            while let Some((_, c)) = it.peek().copied()
                && !is_word(c)
            {
                it.next();
            }
            while let Some((_, c)) = it.peek().copied()
                && is_word(c)
            {
                it.next();
            }
            offset += it.peek().map(|(i, _)| *i).unwrap_or(rest.len());
        } else {
            let before = &text[..offset];
            let mut it = before.char_indices().rev().peekable();
            while let Some((_, c)) = it.peek().copied()
                && !is_word(c)
            {
                it.next();
            }
            let mut start = it.peek().map(|(i, c)| i + c.len_utf8()).unwrap_or(0);
            while let Some((i, c)) = it.peek().copied()
                && is_word(c)
            {
                start = i;
                it.next();
            }
            offset = if start < offset { start } else { 0 };
        }
        if offset == pos.offset {
            return self.step_horizontal(pos, forward);
        }
        self.model.doc.clamp(BlockPosition::new(pos.block, offset))
    }

    fn word(&mut self, forward: bool, extend: bool, cx: &mut Context<Self>) {
        if self.collapse_blocks(forward, cx) {
            return;
        }
        let Some((_, head)) = self.head_anchor() else {
            return;
        };
        self.goal_x = None;
        let next = self.step_word(head, forward);
        self.move_to(next, extend, cx);
    }

    pub(crate) fn on_move_word_left(
        &mut self,
        _: &MoveWordLeft,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.word(false, false, cx);
    }
    pub(crate) fn on_move_word_right(
        &mut self,
        _: &MoveWordRight,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.word(true, false, cx);
    }
    pub(crate) fn on_select_word_left(
        &mut self,
        _: &SelectWordLeft,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.word(false, true, cx);
    }
    pub(crate) fn on_select_word_right(
        &mut self,
        _: &SelectWordRight,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.word(true, true, cx);
    }

    fn horizontal(&mut self, forward: bool, extend: bool, cx: &mut Context<Self>) {
        if self.collapse_blocks(forward, cx) {
            return;
        }
        let Some((anchor, head)) = self.head_anchor() else {
            return;
        };
        self.goal_x = None;
        // Collapsing a range moves to its edge, like every text field.
        if !extend && anchor != head {
            let ord = self.model.doc.cmp_positions(anchor, head).ok();
            let pick_head = matches!(
                (forward, ord),
                (true, Some(std::cmp::Ordering::Less)) | (false, Some(std::cmp::Ordering::Greater))
            );
            let target = if pick_head { head } else { anchor };
            return self.move_to(target, false, cx);
        }
        let next = self.step_horizontal(head, forward);
        self.move_to(next, extend, cx);
    }

    fn vertical(&mut self, down: bool, extend: bool, cx: &mut Context<Self>) {
        if self.collapse_blocks(down, cx) {
            return;
        }
        let Some((_, head)) = self.head_anchor() else {
            return;
        };
        let leaves = self.snapshot().leaves.clone();
        let Some(ix) = leaves.iter().position(|l| l.block == head.block) else {
            return;
        };
        // The model-adjacent caret leaf, which may be culled (no geometry).
        let adjacent = if down {
            leaves.get(ix + 1)
        } else {
            ix.checked_sub(1).and_then(|i| leaves.get(i))
        };
        let frame = self.frame.clone();
        let frame = frame.borrow();
        let laid_out = frame.caret_bounds(head, self.style.caret_width());
        let x = laid_out.map(|caret| *self.goal_x.get_or_insert(caret.origin.x));
        let visual = x.and_then(|x| frame.vertical(head, x, down));
        let target = match (visual, adjacent) {
            // Within the block, or into the laid-out adjacent leaf.
            (Some(t), _) if t.block == head.block => t,
            // Down past a table's last row leaves the table (D13).
            _ if down && !extend && self.model.in_last_table_row() => {
                drop(frame);
                self.edit(
                    EditOrigin::Command("table_exit"),
                    |m| m.exit_table().map(|_| ()),
                    cx,
                );
                return;
            }
            (Some(t), Some(next)) if t.block == next.block => t,
            // Up/down inside a table goes to the cell above/below (cells of
            // one table are laid out together).
            (Some(t), _)
                if super::table::table_of(&self.model.doc, head.block).is_some_and(|table| {
                    super::table::table_of(&self.model.doc, t.block) == Some(table)
                }) =>
            {
                t
            }
            // Into a culled (or not yet laid-out) leaf: model fallback.
            (_, Some(next)) => {
                let offset = if down { 0 } else { next.len };
                BlockPosition::new(next.block, offset)
            }
            (_, None) if down && self.model.doc.plain(head.block).is_some() && !extend => {
                drop(frame);
                self.edit(
                    EditOrigin::Command("exit_code_block"),
                    |m| m.exit_code_block().map(|_| ()),
                    cx,
                );
                return;
            }
            (_, None) => {
                let doc = &self.model.doc;
                if down {
                    doc.last_caret()
                } else {
                    doc.first_caret()
                }
            }
        };
        drop(frame);
        let goal = self.goal_x;
        self.move_to(self.model.doc.clamp(target), extend, cx);
        self.goal_x = goal;
    }

    /// Home/End: the visual (soft-wrapped) line from the last frame, else
    /// the block edge.
    fn line_edge(&mut self, end: bool, extend: bool, cx: &mut Context<Self>) {
        if self.collapse_blocks(end, cx) {
            return;
        }
        let Some((_, head)) = self.head_anchor() else {
            return;
        };
        let target = self.visual_line_edge(head, end);
        self.goal_x = None;
        self.move_to(target, extend, cx);
    }

    /// Start or end of the visual (soft-wrapped) line holding `head`; the
    /// leaf's edge when it has no geometry.
    fn visual_line_edge(&self, head: BlockPosition, end: bool) -> BlockPosition {
        let visual = self.frame.borrow().line_edge(head, end);
        // End at a soft wrap: the line's end index is also the next line's
        // start, where the caret would draw. Stay before the wrap point.
        let visual = visual.map(|pos| {
            if !end || pos.block != head.block {
                return pos;
            }
            let frame = self.frame.borrow();
            let (Some(leaf), Some(inline)) =
                (frame.leaf(pos.block), self.model.doc.inline(pos.block))
            else {
                return pos;
            };
            let line_y = leaf.caret_point(head.offset).y;
            if pos.offset < inline.len() && leaf.caret_point(pos.offset).y > line_y {
                let prev = inline.prev_grapheme(pos.offset).unwrap_or(pos.offset);
                BlockPosition::new(pos.block, prev)
            } else {
                pos
            }
        });
        let target = visual.unwrap_or_else(|| {
            let offset = if end {
                self.model.doc.leaf_len(head.block).unwrap_or(0)
            } else {
                0
            };
            BlockPosition::new(head.block, offset)
        });
        self.model.doc.clamp(target)
    }

    /// Where a D21 line delete stops: the visual line edge in text, the code
    /// line (between newlines) in a code block; always inside `head`'s leaf.
    fn delete_line_target(&self, head: BlockPosition, end: bool) -> BlockPosition {
        if let Some(code) = self.model.doc.plain(head.block) {
            let offset = if end {
                code[head.offset..]
                    .find('\n')
                    .map_or(code.len(), |i| head.offset + i)
            } else {
                code[..head.offset].rfind('\n').map_or(0, |i| i + 1)
            };
            return BlockPosition::new(head.block, offset);
        }
        let target = self.visual_line_edge(head, end);
        if target.block == head.block {
            target
        } else {
            head
        }
    }

    /// Where a D21 word delete stops: the word motion's boundary, but never
    /// past an inline atom (an adjacent atom is deleted on its own), and
    /// never outside `head`'s leaf.
    fn delete_word_target(&self, head: BlockPosition, forward: bool) -> BlockPosition {
        use super::inline::ATOM_CHAR;
        let Some(text) = self.model.doc.leaf_text(head.block) else {
            return head;
        };
        let adjacent = if forward {
            text[head.offset..].chars().next()
        } else {
            text[..head.offset].chars().next_back()
        };
        let atom = ATOM_CHAR.len_utf8();
        match adjacent {
            None => return head,
            Some(ATOM_CHAR) if forward => {
                return BlockPosition::new(head.block, head.offset + atom);
            }
            Some(ATOM_CHAR) => return BlockPosition::new(head.block, head.offset - atom),
            Some(_) => {}
        }
        let step = self.step_word(head, forward);
        if step.block != head.block {
            return head;
        }
        let offset = if forward {
            text[head.offset..step.offset]
                .find(ATOM_CHAR)
                .map_or(step.offset, |i| head.offset + i)
        } else {
            text[step.offset..head.offset]
                .rfind(ATOM_CHAR)
                .map_or(step.offset, |i| step.offset + i + atom)
        };
        self.model.doc.clamp(BlockPosition::new(head.block, offset))
    }

    /// D21: delete a word or to the line edge. A range (or block / cell
    /// selection) deletes just the selection; at the leaf's edge it is a
    /// plain Backspace / Delete, except in a table cell, where it does
    /// nothing.
    fn delete_by(&mut self, line: bool, forward: bool, cx: &mut Context<Self>) {
        self.end_composition();
        if self.readonly {
            return;
        }
        let origin = if forward {
            EditOrigin::DeleteForward
        } else {
            EditOrigin::Backspace
        };
        let head = match self.model.selection() {
            BlockSelection::Text { anchor, head } if anchor == head => *head,
            _ => return self.edit(origin, |m| m.delete(forward), cx),
        };
        let target = if line {
            self.delete_line_target(head, forward)
        } else {
            self.delete_word_target(head, forward)
        };
        if line {
            self.model.break_coalescing();
        }
        if target == head {
            if super::table::table_of(&self.model.doc, head.block).is_none() {
                self.edit(origin, |m| m.delete(forward), cx);
            }
        } else {
            let origin = if forward {
                EditOrigin::WordDelete
            } else {
                EditOrigin::WordBackspace
            };
            self.edit(origin, |m| m.delete_span(target, head, forward), cx);
        }
        if line {
            self.model.break_coalescing();
        }
    }

    /// D21 Option+Up/Down: the start / end of the block, or of the previous
    /// / next one when already there.
    fn paragraph_edge(&mut self, forward: bool, extend: bool, cx: &mut Context<Self>) {
        if self.collapse_blocks(forward, cx) {
            return;
        }
        let Some((_, head)) = self.head_anchor() else {
            return;
        };
        let doc = &self.model.doc;
        let len = doc.leaf_len(head.block).unwrap_or(0);
        let mut pos = head;
        if (forward && pos.offset >= len) || (!forward && pos.offset == 0) {
            pos = self.step_horizontal(pos, forward);
        }
        let offset = if forward {
            doc.leaf_len(pos.block).unwrap_or(0)
        } else {
            0
        };
        let target = doc.clamp(BlockPosition::new(pos.block, offset));
        self.goal_x = None;
        self.move_to(target, extend, cx);
    }

    pub(crate) fn on_delete_word_left(
        &mut self,
        _: &DeleteWordLeft,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.delete_by(false, false, cx);
    }
    pub(crate) fn on_delete_word_right(
        &mut self,
        _: &DeleteWordRight,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.delete_by(false, true, cx);
    }
    pub(crate) fn on_delete_to_line_start(
        &mut self,
        _: &DeleteToLineStart,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.delete_by(true, false, cx);
    }
    pub(crate) fn on_delete_to_line_end(
        &mut self,
        _: &DeleteToLineEnd,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.delete_by(true, true, cx);
    }
    pub(crate) fn on_move_paragraph_start(
        &mut self,
        _: &MoveParagraphStart,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.paragraph_edge(false, false, cx);
    }
    pub(crate) fn on_move_paragraph_end(
        &mut self,
        _: &MoveParagraphEnd,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.paragraph_edge(true, false, cx);
    }
    pub(crate) fn on_select_paragraph_start(
        &mut self,
        _: &SelectParagraphStart,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.paragraph_edge(false, true, cx);
    }
    pub(crate) fn on_select_paragraph_end(
        &mut self,
        _: &SelectParagraphEnd,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.paragraph_edge(true, true, cx);
    }

    /// The link drawn under the window point `at`: its leaf, byte range
    /// and url.
    pub fn link_at(&self, at: Point<Pixels>) -> Option<(BlockId, Range<usize>, SharedString)> {
        let pos = {
            let frame = self.frame.borrow();
            let pos = frame.hit_test(at)?;
            if !frame.leaf(pos.block)?.bounds().contains(&at) {
                return None;
            }
            pos
        };
        let inline = self.model.doc.inline(pos.block)?;
        let url = inline.mark_after(pos.offset)?.link.as_ref()?.url.clone();
        let range = link_extent(inline, pos.offset, &url)?;
        Some((pos.block, range, url))
    }

    /// The url of the link under the mouse, if any (D14 hover).
    pub fn hovered_link(&self) -> Option<&SharedString> {
        self.hovered_link.as_ref()
    }

    pub(crate) fn hover_at(&mut self, at: Point<Pixels>, secondary: bool, cx: &mut Context<Self>) {
        self.hover_table(at, cx);
        let url = self.link_at(at).map(|(_, _, url)| url);
        let hand = self.task_checkbox_at(at).is_some() || (secondary && url.is_some());
        if hand != self.pointer_hand {
            self.pointer_hand = hand;
            cx.notify();
        }
        if url != self.hovered_link {
            self.hovered_link = url.clone();
            cx.emit(BlockEditorEvent::LinkHovered { url });
            cx.notify();
        }
    }

    /// Cmd/Ctrl+click: emit [`BlockEditorEvent::LinkClicked`] for the link
    /// under `at`. Returns whether there was one.
    pub(crate) fn follow_link_at(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) -> bool {
        match self.link_at(at) {
            Some((_, _, url)) => {
                cx.emit(BlockEditorEvent::LinkClicked { url });
                true
            }
            None => false,
        }
    }

    /// The url of the link at the caret (or the selection start).
    pub fn link_at_caret(&self) -> Option<SharedString> {
        self.link_range_at_caret().map(|(_, _, url)| url)
    }

    fn link_range_at_caret(&self) -> Option<(BlockId, Range<usize>, SharedString)> {
        let head = match &self.model.selection {
            BlockSelection::Text { anchor, head } => {
                if anchor.block == head.block && anchor.offset < head.offset {
                    *anchor
                } else {
                    *head
                }
            }
            _ => return None,
        };
        let inline = self.model.doc.inline(head.block)?;
        let mark = inline
            .mark_after(head.offset)
            .filter(|m| m.link.is_some())
            .or_else(|| inline.mark_before(head.offset))?;
        let url = mark.link.as_ref()?.url.clone();
        let probe = if inline
            .mark_after(head.offset)
            .is_some_and(|m| m.link.is_some())
        {
            head.offset
        } else {
            head.offset.checked_sub(1)?
        };
        let range = link_extent(inline, probe, &url)?;
        Some((head.block, range, url))
    }

    /// Cmd/Ctrl+K: ask the host for its link popover.
    pub fn request_link_edit(&mut self, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        let url = self.link_at_caret();
        cx.emit(BlockEditorEvent::EditLinkRequested { url });
    }

    pub(crate) fn on_edit_link(&mut self, _: &EditLink, _: &mut Window, cx: &mut Context<Self>) {
        self.request_link_edit(cx);
    }

    /// Add, change (`Some(url)`) or remove (`None`) the link on the
    /// selection, or on the whole link at a collapsed caret. One undo step.
    pub fn set_link(&mut self, url: Option<&str>, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        let collapsed = matches!(
            &self.model.selection,
            BlockSelection::Text { anchor, head } if anchor == head
        );
        if collapsed && let Some((block, range, _)) = self.link_range_at_caret() {
            let _ = self.model.set_selection(BlockSelection::Text {
                anchor: BlockPosition::new(block, range.start),
                head: BlockPosition::new(block, range.end),
            });
        } else if collapsed {
            return;
        }
        let change = match url.map(str::trim).filter(|u| !u.is_empty()) {
            Some(url) => super::marks::MarkChange::new().with_link(url.to_string(), None),
            None => super::marks::MarkChange::new().clear(MarkKind::Link),
        };
        self.model.break_coalescing();
        let _ = self.run(EditorCommand::ApplyMark(change), cx);
        self.model.break_coalescing();
    }

    /// The task checkbox drawn left of a task item's first line under
    /// `at`: the item's text leaf and whether it is checked.
    /// Mouse-down on a task checkbox: toggle it, leaving the caret and
    /// selection alone. Returns whether it was one.
    pub(crate) fn click_checkbox(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) -> bool {
        match self.task_checkbox_at(at) {
            Some((leaf, checked)) if !self.readonly => {
                self.end_composition();
                self.dragging = false;
                self.set_task_checked(leaf, !checked, cx);
                true
            }
            _ => false,
        }
    }

    pub(crate) fn task_checkbox_at(&self, at: Point<Pixels>) -> Option<(BlockId, bool)> {
        use super::kind::BlockKindData;
        use gpui::px;
        let frame = self.frame.borrow();
        frame.leaves.iter().find_map(|leaf| {
            let b = leaf.bounds();
            let line = px(28.).min(b.size.height);
            if !(at.y >= b.top()
                && at.y < b.top() + line
                && at.x < b.left()
                && at.x >= b.left() - px(28.))
            {
                return None;
            }
            let block = leaf.info.block;
            let (item, index) = self.model.doc.index_in_parent(block)?;
            match self.model.doc.kind(item) {
                Some(BlockKindData::ListItem {
                    checked: Some(c), ..
                }) if index == 0 => Some((block, *c)),
                _ => None,
            }
        })
    }

    /// Mouse: place or extend the caret at a window point.
    pub(crate) fn mouse_at(&mut self, at: Point<Pixels>, extend: bool, cx: &mut Context<Self>) {
        // Block handle: a click in the left edge beside a table or code
        // block (left of its text) selects the block as a node.
        if !extend && let Some(block) = self.block_handle_at(at) {
            self.goal_x = None;
            self.end_composition();
            let _ = self.model.set_selection(BlockSelection::Blocks {
                anchor: block,
                head: block,
            });
            self.dragging = false;
            self.selection_changed(cx);
            return;
        }
        let hit = self.frame.borrow().hit_test(at);
        // A click on an inline atom selects the whole atom (#3113).
        if !extend && let Some(pos) = hit.and_then(|pos| self.atom_under(pos, at)) {
            self.goal_x = None;
            self.end_composition();
            let _ = self.model.set_selection(BlockSelection::Text {
                anchor: pos,
                head: BlockPosition::new(
                    pos.block,
                    pos.offset + super::inline::ATOM_CHAR.len_utf8(),
                ),
            });
            self.selection_changed(cx);
            return;
        }
        if let Some(pos) = hit {
            self.goal_x = None;
            let pos = self.model.doc.clamp(pos);
            self.move_to(pos, extend, cx);
        }
    }

    /// Double-click: the word at the caret; triple-click: the whole block.
    pub(crate) fn select_unit(&mut self, block: bool, cx: &mut Context<Self>) {
        let Some(caret) = self.model.caret() else {
            return;
        };
        let Some(text) = self.model.doc.leaf_text(caret.block) else {
            return;
        };
        let range = if block {
            0..text.len()
        } else {
            match crate::support::word_range_at(text, caret.offset) {
                Some(r) => r,
                None => return,
            }
        };
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: BlockPosition::new(caret.block, range.start),
            head: BlockPosition::new(caret.block, range.end),
        });
        self.dragging = false;
        self.selection_changed(cx);
    }

    /// Top-level blocks with laid-out geometry, in document order, with the
    /// union of their leaves' bounds (D22).
    pub(crate) fn top_level_bounds(&self) -> Vec<(usize, BlockId, Bounds<Pixels>)> {
        let doc = &self.model.doc;
        let frame = self.frame.borrow();
        let children = doc.children(doc.root);
        let mut out: Vec<(usize, BlockId, Bounds<Pixels>)> = Vec::new();
        for leaf in &frame.leaves {
            let path = doc.path(leaf.info.block);
            let Some(top) = path.get(1).copied() else {
                continue;
            };
            let Some(ix) = children.iter().position(|c| *c == top) else {
                continue;
            };
            let b = leaf.bounds();
            match out.iter_mut().find(|(_, id, _)| *id == top) {
                Some(entry) => entry.2 = entry.2.union(&b),
                None => out.push((ix, top, b)),
            }
        }
        out.sort_by_key(|(ix, _, _)| *ix);
        out
    }

    /// D22: the top-level table or code block whose edge handle
    /// (`block_handle_at`) is under `at`; only those can be dragged.
    pub(crate) fn drag_handle_at(&self, at: Point<Pixels>) -> Option<BlockId> {
        if self.readonly {
            return None;
        }
        let block = self.block_handle_at(at)?;
        let doc = &self.model.doc;
        // A code block's handle is its leaf; tables report the table.
        let top = doc.path(block).get(1).copied()?;
        (top == block).then_some(block)
    }

    /// D22: the gap between top-level blocks nearest the pointer's `y`.
    fn drop_gap_at(&self, y: Pixels) -> Option<usize> {
        let blocks = self.top_level_bounds();
        let len = self.model.doc.children(self.model.doc.root).len();
        if blocks.is_empty() {
            return None;
        }
        Some(
            blocks
                .iter()
                .find(|(_, _, b)| y < b.center().y)
                .map_or_else(
                    || blocks.last().map_or(len, |(ix, _, _)| ix + 1),
                    |(ix, _, _)| *ix,
                ),
        )
    }

    /// D22: mouse-down on a handle arms a drag (the click itself is handled
    /// as before).
    pub(crate) fn arm_block_drag(&mut self, at: Point<Pixels>) {
        self.block_drag = self.drag_handle_at(at).map(|block| BlockDrag {
            block,
            start: at,
            active: false,
            drop: None,
        });
    }

    /// D22: pointer moved with the button down. Returns whether a block
    /// drag owns the move (no text selection then).
    pub(crate) fn block_drag_to(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) -> bool {
        use gpui::px;
        let Some(mut drag) = self.block_drag else {
            return false;
        };
        if !drag.active {
            let d = at - drag.start;
            if d.x.abs().max(d.y.abs()) < px(4.) {
                return false;
            }
            drag.active = true;
            self.dragging = false;
            self.end_composition();
            let _ = self.model.set_selection(BlockSelection::Blocks {
                anchor: drag.block,
                head: drag.block,
            });
            self.selection_changed(cx);
        }
        drag.drop = self.drop_gap_at(at.y);
        self.block_drag = Some(drag);
        cx.notify();
        true
    }

    /// D22: button released. Drops an active drag (one undo step).
    pub(crate) fn finish_block_drag(&mut self, cx: &mut Context<Self>) {
        let Some(drag) = self.block_drag.take() else {
            return;
        };
        if drag.active {
            if let Some(to) = drag.drop {
                self.model.break_coalescing();
                self.edit(
                    EditOrigin::Command("move_block_to"),
                    |m| m.move_block_to(drag.block, to).map(|_| ()),
                    cx,
                );
                self.model.break_coalescing();
            }
            cx.notify();
        }
    }

    /// D22: where to paint the drop indicator of an active drag: a line in
    /// the gap, spanning the blocks' width.
    pub(crate) fn drop_indicator(&self) -> Option<Bounds<Pixels>> {
        use gpui::{point, px, size};
        let drag = self.block_drag.filter(|d| d.active)?;
        let to = drag.drop?;
        let blocks = self.top_level_bounds();
        let left = blocks
            .iter()
            .map(|(_, _, b)| b.left())
            .reduce(Pixels::min)?;
        let right = blocks
            .iter()
            .map(|(_, _, b)| b.right())
            .reduce(Pixels::max)?;
        let prev = blocks.iter().rev().find(|(ix, _, _)| *ix < to);
        let next = blocks.iter().find(|(ix, _, _)| *ix >= to);
        let y = match (prev, next) {
            (Some((_, _, a)), Some((_, _, b))) => (a.bottom() + b.top()) / 2.,
            (None, Some((_, _, b))) => b.top() - px(3.),
            (Some((_, _, a)), None) => a.bottom() + px(3.),
            (None, None) => return None,
        };
        Some(gpui::Bounds::new(
            point(left - px(8.), y - px(1.)),
            size(right - left + px(8.), px(2.)),
        ))
    }

    /// The table or code block whose left edge (the strip left of its
    /// text, inside the block's padding) is under `at`.
    pub(crate) fn block_handle_at(&self, at: Point<Pixels>) -> Option<BlockId> {
        let frame = self.frame.borrow();
        use gpui::px;
        let in_edge = |b: &Bounds<Pixels>| {
            at.y >= b.top() && at.y < b.bottom() && at.x < b.left() && at.x >= b.left() - px(24.)
        };
        if let Some((table, _)) = frame.tables.iter().find(|(_, b)| in_edge(b)) {
            return Some(*table);
        }
        frame
            .leaves
            .iter()
            .find(|leaf| self.model.doc.plain(leaf.info.block).is_some() && in_edge(&leaf.bounds()))
            .map(|leaf| leaf.info.block)
    }

    /// The start of the inline atom drawn under the window point `at` in
    /// the leaf a hit test found.
    fn atom_under(&self, pos: BlockPosition, at: Point<Pixels>) -> Option<BlockPosition> {
        let frame = self.frame.borrow();
        let range = frame.leaf(pos.block)?.atom_at(at)?;
        Some(BlockPosition::new(pos.block, range.start))
    }

    fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) {
        let _ = self.run(EditorCommand::ToggleMark(kind), cx);
    }

    /// The selection as clipboard text, and whether it is the editor's own
    /// inline Markdown (D17): then the copy is tagged with
    /// [`COPY_TAG`] so paste parses it back.
    fn selected_text(&self) -> (String, CopyKind) {
        if let Some(table) = self.model.cells_markdown() {
            return (table, CopyKind::Blocks);
        }
        if let Some((parent, range)) = self.model.selected_blocks() {
            let ids = &self.model.doc.children(parent)[range];
            return (
                super::serialize::join_blocks(&self.model.doc, ids),
                CopyKind::Blocks,
            );
        }
        let Ok(range) = self.model.doc.resolve_selection(self.model.selection()) else {
            return (String::new(), CopyKind::External);
        };
        // Several blocks: Markdown for the whole selection (D18).
        if range.start.block != range.end.block
            && let Some(markdown) = super::slice::selection_markdown(&self.model.doc, range)
        {
            return (markdown, CopyKind::Blocks);
        }
        let mut inline_only = true;
        let text = self
            .model
            .text_ranges(range)
            .into_iter()
            .filter_map(|(id, lo, hi)| {
                // Marks and inline atoms copy as Markdown (an image as
                // `![alt](url)`, never the U+FFFC placeholder, #3113). A
                // partial selection serializes as its own inline, so
                // delimiters are always balanced at the cut edges.
                if let Some(inline) = self.model.doc.inline(id) {
                    return Some(super::serialize::inline_markdown(&inline.slice(lo..hi)));
                }
                inline_only = false;
                let text = self.model.doc.leaf_text(id)?;
                text.get(lo..hi).map(str::to_string)
            })
            .collect::<Vec<_>>()
            .join("\n");
        (
            text,
            if inline_only {
                CopyKind::Inline
            } else {
                CopyKind::External
            },
        )
    }

    // ---- action handlers --------------------------------------------------

    pub(crate) fn on_backspace(&mut self, _: &Backspace, _: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        self.edit(EditOrigin::Backspace, |m| m.delete(false), cx);
    }
    pub(crate) fn on_delete(&mut self, _: &Delete, _: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        self.edit(EditOrigin::DeleteForward, |m| m.delete(true), cx);
    }
    pub(crate) fn on_enter(&mut self, _: &Enter, _: &mut Window, cx: &mut Context<Self>) {
        if self.readonly || self.is_composing() {
            return;
        }
        if self.submit_policy == SubmitPolicy::Enter {
            cx.emit(BlockEditorEvent::SubmitRequested);
            return;
        }
        self.newline(cx);
    }
    pub(crate) fn on_structural_enter(
        &mut self,
        _: &StructuralEnter,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.readonly || self.is_composing() {
            return;
        }
        self.newline(cx);
    }
    fn newline(&mut self, cx: &mut Context<Self>) {
        self.end_composition();
        // "```lang" then Enter: a code block.
        if !self.readonly
            && self.rule_on(RuleKind::CodeFence)
            && let Some(caret) = self.model.caret()
            && self.model.doc.kind(caret.block) == Some(&super::kind::BlockKindData::Paragraph)
            && caret.offset == self.model.doc.leaf_len(caret.block).unwrap_or(0)
            && let Some(lang) = self
                .model
                .doc
                .inline(caret.block)
                .and_then(|i| code_fence(i.text()))
        {
            self.fence_to_code_block(caret.block, lang, cx);
            return;
        }
        // Enter in a table cell (D13).
        if !self.readonly && self.model.current_cell().is_some() {
            self.model.break_coalescing();
            self.edit(
                EditOrigin::Command("table_enter"),
                |m| m.table_enter().map(|_| ()),
                cx,
            );
            self.model.break_coalescing();
            return;
        }
        // "| a | b |" then Enter at the end of a paragraph: a table.
        if !self.readonly
            && self.rule_on(RuleKind::Table)
            && let Some(caret) = self.model.caret()
            && caret.offset == self.model.doc.leaf_len(caret.block).unwrap_or(0)
            && self
                .model
                .doc
                .inline(caret.block)
                .is_some_and(|i| super::table::table_row_cells(i.text()).is_some())
        {
            let block = caret.block;
            self.model.break_coalescing();
            self.edit(
                EditOrigin::InputRule("table"),
                |m| m.paragraph_to_table(block).map(|_| ()),
                cx,
            );
            self.model.break_coalescing();
            return;
        }
        // "---" then Enter in an otherwise empty paragraph: a rule.
        if !self.readonly
            && self.rule_on(RuleKind::HorizontalRule)
            && let Some(caret) = self.model.caret()
            && self.model.doc.kind(caret.block) == Some(&super::kind::BlockKindData::Paragraph)
            && self.model.doc.inline(caret.block).map(|i| i.text()) == Some("---")
        {
            let block = caret.block;
            self.model.break_coalescing();
            self.model.history.begin_transaction();
            let _ = self.model.set_selection(BlockSelection::Text {
                anchor: BlockPosition::new(block, 0),
                head: BlockPosition::new(block, 3),
            });
            let _ = self.model.delete(false);
            let _ = self.model.paragraph_to_rule();
            self.model.history.commit_transaction();
            self.model.break_coalescing();
            self.after_edit(EditOrigin::InputRule("horizontal_rule"), cx);
            return;
        }
        self.edit(EditOrigin::Command("split_block"), |m| m.split_block(), cx);
    }
    /// Shift+Enter (Ctrl+Enter in composer mode): a cell soft break;
    /// structural Enter elsewhere, without submission.
    pub(crate) fn on_soft_break(&mut self, _: &SoftBreak, _: &mut Window, cx: &mut Context<Self>) {
        if self.readonly || self.is_composing() {
            return;
        }
        self.end_composition();
        if self.model.current_cell().is_some() {
            self.model.break_coalescing();
            self.edit(
                EditOrigin::Command("cell_soft_break"),
                |m| m.cell_soft_break().map(|_| ()),
                cx,
            );
            self.model.break_coalescing();
        } else {
            self.newline(cx);
        }
    }

    /// Cmd/Ctrl+Enter: leave a table to the block after it.
    pub(crate) fn on_exit_block(&mut self, _: &ExitBlock, _: &mut Window, cx: &mut Context<Self>) {
        if self.readonly || self.is_composing() {
            return;
        }
        if matches!(
            self.submit_policy,
            SubmitPolicy::Enter | SubmitPolicy::ModifiedEnter
        ) {
            cx.emit(BlockEditorEvent::SubmitRequested);
            return;
        }
        self.end_composition();
        if self.readonly || self.model.current_cell().is_none() {
            cx.propagate();
            return;
        }
        self.model.break_coalescing();
        self.edit(
            EditOrigin::Command("table_exit"),
            |m| m.exit_table().map(|_| ()),
            cx,
        );
        self.model.break_coalescing();
    }

    pub(crate) fn on_move_left(&mut self, _: &MoveLeft, _: &mut Window, cx: &mut Context<Self>) {
        self.horizontal(false, false, cx);
    }
    pub(crate) fn on_move_right(&mut self, _: &MoveRight, _: &mut Window, cx: &mut Context<Self>) {
        self.horizontal(true, false, cx);
    }
    pub(crate) fn on_move_up(&mut self, _: &MoveUp, _: &mut Window, cx: &mut Context<Self>) {
        self.vertical(false, false, cx);
    }
    pub(crate) fn on_move_down(&mut self, _: &MoveDown, _: &mut Window, cx: &mut Context<Self>) {
        self.vertical(true, false, cx);
    }
    pub(crate) fn on_move_home(&mut self, _: &MoveHome, _: &mut Window, cx: &mut Context<Self>) {
        self.line_edge(false, false, cx);
    }
    pub(crate) fn on_move_end(&mut self, _: &MoveEnd, _: &mut Window, cx: &mut Context<Self>) {
        self.line_edge(true, false, cx);
    }
    pub(crate) fn on_select_left(
        &mut self,
        _: &SelectLeft,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.horizontal(false, true, cx);
    }
    pub(crate) fn on_select_right(
        &mut self,
        _: &SelectRight,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.horizontal(true, true, cx);
    }
    pub(crate) fn on_select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
        self.vertical(false, true, cx);
    }
    pub(crate) fn on_select_down(
        &mut self,
        _: &SelectDown,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.vertical(true, true, cx);
    }
    pub(crate) fn on_select_home(
        &mut self,
        _: &SelectHome,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.line_edge(false, true, cx);
    }
    pub(crate) fn on_select_end(&mut self, _: &SelectEnd, _: &mut Window, cx: &mut Context<Self>) {
        self.line_edge(true, true, cx);
    }
    pub(crate) fn on_move_doc_start(
        &mut self,
        _: &MoveDocStart,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.goal_x = None;
        self.move_to(self.model.doc.first_caret(), false, cx);
    }
    pub(crate) fn on_move_doc_end(
        &mut self,
        _: &MoveDocEnd,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.goal_x = None;
        self.move_to(self.model.doc.last_caret(), false, cx);
    }
    pub(crate) fn on_select_doc_start(
        &mut self,
        _: &SelectDocStart,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.goal_x = None;
        self.move_to(self.model.doc.first_caret(), true, cx);
    }
    pub(crate) fn on_select_doc_end(
        &mut self,
        _: &SelectDocEnd,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.goal_x = None;
        self.move_to(self.model.doc.last_caret(), true, cx);
    }
    pub(crate) fn on_select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        let _ = self.model.run(EditorCommand::SelectAll);
        self.selection_changed(cx);
    }
    pub(crate) fn on_undo(&mut self, _: &Undo, _: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        self.undo(cx);
    }
    pub(crate) fn on_redo(&mut self, _: &Redo, _: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        self.redo(cx);
    }
    pub(crate) fn on_normal_text(
        &mut self,
        _: &NormalText,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.readonly {
            return;
        }
        self.end_composition();
        self.model.break_coalescing();
        let _ = self.run(EditorCommand::SetBlockKind(BlockKind::Paragraph), cx);
        self.model.break_coalescing();
    }
    pub(crate) fn on_close_table_menu(
        &mut self,
        _: &CloseTableMenu,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.close_table_menu(cx);
    }
    fn table_key(&mut self, edit: Option<crate::TableEdit>, cx: &mut Context<Self>) {
        if self.readonly || self.model.current_cell().is_none() {
            cx.propagate();
            return;
        }
        self.end_composition();
        self.close_table_menu(cx);
        if let Some(edit) = edit {
            self.model.break_coalescing();
            let _ = self.run(EditorCommand::EditTable(edit), cx);
            self.model.break_coalescing();
        }
    }
    pub(crate) fn on_table_insert_column_left(
        &mut self,
        _: &TableInsertColumnLeft,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.table_key(Some(crate::TableEdit::AddColumnLeft), cx);
    }
    pub(crate) fn on_table_insert_column_right(
        &mut self,
        _: &TableInsertColumnRight,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.table_key(Some(crate::TableEdit::AddColumnRight), cx);
    }
    pub(crate) fn on_table_insert_row_above(
        &mut self,
        _: &TableInsertRowAbove,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.table_key(Some(crate::TableEdit::AddRowAbove), cx);
    }
    pub(crate) fn on_table_insert_row_below(
        &mut self,
        _: &TableInsertRowBelow,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.table_key(Some(crate::TableEdit::AddRowBelow), cx);
    }
    /// Cmd/Ctrl+Alt+Backspace: whole column(s) selected → delete them;
    /// otherwise delete the row(s) of the caret / cell selection, unless
    /// that includes the header row (then nothing happens).
    pub(crate) fn on_table_delete_line(
        &mut self,
        _: &TableDeleteLine,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let edit = self.table_delete_edit();
        self.table_key(edit, cx);
    }
    /// What Cmd/Ctrl+Alt+Backspace does here (`None`: nothing).
    pub fn table_delete_edit(&self) -> Option<crate::TableEdit> {
        if self.model.whole_columns_selected() {
            return Some(crate::TableEdit::RemoveColumn);
        }
        let (_, rows, _) = self.model.table_span()?;
        (*rows.start() > 0).then_some(crate::TableEdit::RemoveRow)
    }
    pub(crate) fn on_toggle_bold(
        &mut self,
        _: &ToggleBold,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.toggle_mark(MarkKind::Bold, cx);
    }
    pub(crate) fn on_toggle_italic(
        &mut self,
        _: &ToggleItalic,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.toggle_mark(MarkKind::Italic, cx);
    }
    pub(crate) fn on_toggle_code(
        &mut self,
        _: &ToggleCode,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.toggle_mark(MarkKind::Code, cx);
    }
    pub(crate) fn on_indent(&mut self, _: &Indent, _: &mut Window, cx: &mut Context<Self>) {
        let _ = self.run(EditorCommand::Indent, cx);
    }
    pub(crate) fn on_outdent(&mut self, _: &Outdent, _: &mut Window, cx: &mut Context<Self>) {
        let _ = self.run(EditorCommand::Outdent, cx);
    }
    pub(crate) fn on_copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
        let (text, kind) = self.selected_text();
        if text.is_empty() {
            return;
        }
        cx.write_to_clipboard(match kind.tag() {
            Some(tag) => ClipboardItem::new_string_with_metadata(text, tag.to_string()),
            None => ClipboardItem::new_string(text),
        });
    }
    pub(crate) fn on_cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
        self.end_composition();
        self.on_copy(&Copy, window, cx);
        self.edit(
            EditOrigin::Cut,
            |m| m.run(EditorCommand::DeleteSelection).map(|_| ()),
            cx,
        );
    }
    pub(crate) fn on_paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        if let Some(item) = cx.read_from_clipboard() {
            self.paste(item, false, cx);
        }
    }
    pub(crate) fn on_native_paste(
        &mut self,
        _: &gpui_kit::base::input::Paste,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.on_paste(&Paste, window, cx);
    }
    pub(crate) fn on_paste_plain(
        &mut self,
        _: &PastePlain,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.readonly {
            return;
        }
        if let Some(item) = cx.read_from_clipboard() {
            self.paste(item, true, cx);
        }
    }

    /// Deliver semantic clipboard content. `plain` bypasses Markdown import.
    /// With Host policy this emits one request; there is no fallback insertion
    /// until the owner resolves it, so mixed image/text entries cannot double
    /// insert. This method itself never reads the system clipboard.
    pub fn paste(&mut self, item: ClipboardItem, plain: bool, cx: &mut Context<Self>) {
        if self.readonly {
            return;
        }
        self.end_composition();
        if self.clipboard_policy == ClipboardPolicy::Host {
            self.paste_sequence += 1;
            self.pending_paste = Some(self.paste_sequence);
            let request = PasteRequest {
                range: self.model.capture(self.model.selection.clone()),
                plain,
                copy: CopyKind::of(&item),
                sequence: self.paste_sequence,
            };
            cx.emit(BlockEditorEvent::PasteRequested { request, item });
        } else if let Some(text) = item.text() {
            self.paste_text(&text, plain, CopyKind::of(&item), cx);
        }
    }

    /// Resolve an intercepted paste with text not consumed by the host's other
    /// admissions (e.g. image attachments). `None` means wholly handled or
    /// rejected. Returns false when navigation/edits made the request stale.
    pub fn is_paste_current(&self, request: &PasteRequest) -> bool {
        !self.readonly
            && self.pending_paste == Some(request.sequence)
            && self.model.is_capture_current(&request.range)
    }
    pub fn apply_paste(
        &mut self,
        request: &PasteRequest,
        text: Option<&str>,
        cx: &mut Context<Self>,
    ) -> bool {
        if !self.is_paste_current(request) {
            return false;
        }
        self.pending_paste = None;
        if let Some(text) = text {
            self.paste_text(text, request.plain, request.copy, cx);
        }
        true
    }
    fn paste_text(&mut self, text: &str, plain: bool, copy: CopyKind, cx: &mut Context<Self>) {
        self.edit(
            EditOrigin::Paste,
            |model| {
                if !plain && copy == CopyKind::Blocks && model.paste_blocks_markdown(text)? {
                    return Ok(());
                }
                if !plain && copy != CopyKind::External && model.paste_inline_markdown(text)? {
                    return Ok(());
                }
                if !plain && model.paste_blocks(text)? {
                    return Ok(());
                }
                model.insert_text(text, EditOrigin::Paste)
            },
            cx,
        );
    }

    /// Markdown input rules (design §5.3): `# `..`###### `, `- `/`* `/`+ `
    /// and `1. ` at the start of a plain paragraph. The conversion is its own
    /// undo group after the typing, so one undo reverts it and keeps the
    /// typed text.
    fn apply_input_rule(&mut self, cx: &mut Context<Self>) {
        use super::kind::BlockKindData;
        let Some(caret) = self.model.caret() else {
            return;
        };
        let doc = &self.model.doc;
        if doc.kind(caret.block) != Some(&BlockKindData::Paragraph) {
            return;
        }
        // "```lang " typed into an otherwise empty paragraph.
        if self.rule_on(RuleKind::CodeFence)
            && let Some(lang) = doc
                .inline(caret.block)
                .and_then(|i| code_fence(i.text().strip_suffix(' ')?))
                .filter(|_| caret.offset == doc.leaf_len(caret.block).unwrap_or(0))
        {
            self.fence_to_code_block(caret.block, lang, cx);
            return;
        }
        let in_list = doc
            .parent(caret.block)
            .and_then(|parent| doc.kind(parent))
            .is_some_and(|kind| matches!(kind, BlockKindData::ListItem { .. }));
        let Some(text) = doc.inline(caret.block).map(|i| i.text().to_string()) else {
            return;
        };
        let prefix = &text[..caret.offset.min(text.len())];
        let Some(marker) = prefix.strip_suffix(' ') else {
            return;
        };
        let task = match marker {
            "[ ]" => Some(false),
            "[x]" | "[X]" => Some(true),
            _ => None,
        };
        let (commands, rule) = if self.rule_on(RuleKind::Heading)
            && !marker.is_empty()
            && marker.len() <= 6
            && marker.bytes().all(|b| b == b'#')
        {
            let level = marker.len() as u8;
            (
                vec![EditorCommand::SetBlockKind(BlockKind::Heading { level })],
                "heading",
            )
        } else if self.rule_on(RuleKind::BulletList)
            && !in_list
            && matches!(marker, "-" | "*" | "+")
        {
            (
                vec![EditorCommand::ToggleList { ordered: false }],
                "bullet_list",
            )
        } else if self.rule_on(RuleKind::OrderedList)
            && !in_list
            && marker.len() >= 2
            && marker.ends_with('.')
            && marker[..marker.len() - 1]
                .bytes()
                .all(|b| b.is_ascii_digit())
        {
            (
                vec![EditorCommand::ToggleList { ordered: true }],
                "ordered_list",
            )
        } else if self.rule_on(RuleKind::TaskItem)
            && let Some(checked) = task
        {
            let mut commands = Vec::new();
            if !in_list {
                commands.push(EditorCommand::ToggleList { ordered: false });
            }
            commands.push(EditorCommand::SetTaskChecked(checked));
            (commands, "task_item")
        } else if self.rule_on(RuleKind::Blockquote) && marker == ">" {
            (Vec::new(), "blockquote")
        } else {
            return;
        };
        let block = caret.block;
        let len = prefix.len();
        self.model.break_coalescing();
        self.model.history.begin_transaction();
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: BlockPosition::new(block, 0),
            head: BlockPosition::new(block, len),
        });
        let _ = self.model.delete(false);
        if commands.is_empty() {
            let _ = self.model.wrap_in_blockquote();
        }
        for command in commands {
            let _ = self.model.run(command);
        }
        self.model.history.commit_transaction();
        self.model.break_coalescing();
        self.after_edit(EditOrigin::InputRule(rule), cx);
    }

    /// Link input rule: `[text](url)` typed, on the closing `)`, becomes
    /// `text` with a link mark. One undo group: undo restores the source.
    fn apply_link_rule(&mut self, cx: &mut Context<Self>) {
        let Some(caret) = self.model.caret() else {
            return;
        };
        let Some(inline) = self.model.doc.inline(caret.block) else {
            return;
        };
        let Some((start, text, url)) = link_rule(inline.text(), caret.offset) else {
            return;
        };
        let block = caret.block;
        let pos = |offset| BlockPosition::new(block, offset);
        let text_end = start + 1 + text.len();
        self.model.break_coalescing();
        self.model.history.begin_transaction();
        // Drop "](url)" then "[".
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(text_end),
            head: pos(caret.offset),
        });
        let _ = self.model.delete(false);
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(start),
            head: pos(start + 1),
        });
        let _ = self.model.delete(false);
        let end = start + text.len();
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(start),
            head: pos(end),
        });
        let _ = self.model.run(EditorCommand::ApplyMark(
            super::marks::MarkChange::new().with_link(url, None),
        ));
        let _ = self.model.set_selection(BlockSelection::caret(pos(end)));
        let after = super::marks::MarkChange::new()
            .clear(super::marks::MarkKind::Link)
            .apply(&self.model.active_marks().0);
        self.model.history.commit_transaction();
        self.model.break_coalescing();
        self.model.stored_marks = Some(after);
        self.after_edit(EditOrigin::InputRule("link"), cx);
    }

    /// Inline-mark input rules: a closing `` ` ``, `*`, `**` or `~~` typed
    /// after an opening one in the same leaf turns the text between into
    /// code, italic, bold or strikethrough and drops the delimiters. One undo
    /// group of its own: undo restores the literal delimiters.
    fn apply_mark_rule(&mut self, cx: &mut Context<Self>) {
        let Some(caret) = self.model.caret() else {
            return;
        };
        let Some(inline) = self.model.doc.inline(caret.block) else {
            return;
        };
        let Some((open, close, kind)) = mark_rule(inline, caret.offset) else {
            return;
        };
        let block = caret.block;
        let d = close.len();
        let pos = |offset| BlockPosition::new(block, offset);
        self.model.break_coalescing();
        self.model.history.begin_transaction();
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(close.start),
            head: pos(close.end),
        });
        let _ = self.model.delete(false);
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(open.start),
            head: pos(open.end),
        });
        let _ = self.model.delete(false);
        let end = close.start - d;
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: pos(open.start),
            head: pos(end),
        });
        let _ = self.model.run(EditorCommand::ApplyMark(
            super::marks::MarkChange::new().set(kind),
        ));
        let _ = self.model.set_selection(BlockSelection::caret(pos(end)));
        // Text typed next is outside the new span.
        let after = super::marks::MarkChange::new()
            .clear(kind)
            .apply(&self.model.active_marks().0);
        self.model.history.commit_transaction();
        self.model.break_coalescing();
        self.model.stored_marks = Some(after);
        self.after_edit(EditOrigin::InputRule("inline_mark"), cx);
    }

    /// Replace a typed code fence with an empty code block, caret inside,
    /// as its own undo group (one undo restores the typed fence).
    fn fence_to_code_block(&mut self, block: BlockId, lang: String, cx: &mut Context<Self>) {
        let len = self.model.doc.leaf_len(block).unwrap_or(0);
        self.model.break_coalescing();
        self.model.history.begin_transaction();
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: BlockPosition::new(block, 0),
            head: BlockPosition::new(block, len),
        });
        let _ = self.model.delete(false);
        let (lang, meta) = lang
            .split_once(char::is_whitespace)
            .map_or((lang.as_str(), None), |(lang, meta)| {
                (lang, Some(meta.trim_start().to_owned()))
            });
        let _ = self.model.set_code_block_info(Some(lang.to_owned()), meta);
        self.model.history.commit_transaction();
        self.model.break_coalescing();
        self.after_edit(EditOrigin::InputRule("code_block"), cx);
    }

    // ---- IME ---------------------------------------------------------------

    /// The IME sees the caret leaf as its document.
    fn ime_block(&self) -> Option<BlockId> {
        if let Some(m) = &self.marked {
            return Some(m.block);
        }
        let (_, head) = self.head_anchor()?;
        Some(head.block)
    }

    fn ime_text(&self) -> &str {
        self.ime_block()
            .and_then(|id| self.model.doc.leaf_text(id))
            .unwrap_or("")
    }

    fn select_utf16(&mut self, block: BlockId, range16: Range<usize>) {
        let text = self.ime_text();
        let range = utf16_to_byte(text, range16.start)..utf16_to_byte(text, range16.end);
        let _ = self.model.set_selection(BlockSelection::Text {
            anchor: BlockPosition::new(block, range.start),
            head: BlockPosition::new(block, range.end),
        });
    }

    fn select_marked_or(&mut self, range16: Option<Range<usize>>) {
        let Some(block) = self.ime_block() else {
            return;
        };
        if let Some(range16) = range16 {
            self.select_utf16(block, range16);
        } else if let Some(m) = self.marked.clone() {
            let _ = self.model.set_selection(BlockSelection::Text {
                anchor: BlockPosition::new(m.block, m.range.start),
                head: BlockPosition::new(m.block, m.range.end),
            });
        }
    }
}

fn command_name(command: &EditorCommand) -> &'static str {
    match command {
        EditorCommand::ToggleMark(_) => "toggle_mark",
        EditorCommand::ApplyMark(_) => "apply_mark",
        EditorCommand::SetBlockKind(_) => "set_block_kind",
        EditorCommand::ToggleList { .. } => "toggle_list",
        EditorCommand::ToggleTask => "toggle_task",
        EditorCommand::SetTaskChecked(_) => "set_task_checked",
        EditorCommand::Indent => "indent",
        EditorCommand::Outdent => "outdent",
        EditorCommand::MoveBlocks { .. } => "move_blocks",
        EditorCommand::InsertBlock(_) => "insert_block",
        EditorCommand::SelectAll => "select_all",
        EditorCommand::DeleteSelection => "delete_selection",
        EditorCommand::SetCodeBlock { .. } => "code_block",
        EditorCommand::InsertTable { .. } => "insert_table",
        EditorCommand::EditTable(_) => "edit_table",
    }
}

pub(crate) fn utf16_to_byte(text: &str, utf16: usize) -> usize {
    let mut count = 0;
    for (ix, ch) in text.char_indices() {
        if count >= utf16 {
            return ix;
        }
        count += ch.len_utf16();
    }
    text.len()
}

pub(crate) fn byte_to_utf16(text: &str, byte: usize) -> usize {
    text.get(..byte.min(text.len()))
        .map(|s| s.encode_utf16().count())
        .unwrap_or(0)
}

impl EntityInputHandler for BlockEditorState {
    fn text_for_range(
        &mut self,
        range16: Range<usize>,
        adjusted: &mut Option<Range<usize>>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<String> {
        let text = self.ime_text();
        let range = utf16_to_byte(text, range16.start)..utf16_to_byte(text, range16.end);
        adjusted.replace(byte_to_utf16(text, range.start)..byte_to_utf16(text, range.end));
        text.get(range).map(str::to_string)
    }

    fn selected_text_range(
        &mut self,
        _: bool,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<UTF16Selection> {
        let (anchor, head) = self.head_anchor()?;
        let text = self.ime_text();
        // Cross-block selections are reported as the caret leaf's part.
        let in_leaf = |p: BlockPosition| {
            if p.block == head.block {
                p.offset
            } else if self.model.doc.cmp_positions(p, head).ok() == Some(std::cmp::Ordering::Less) {
                0
            } else {
                text.len()
            }
        };
        let (a, h) = (in_leaf(anchor), head.offset);
        Some(UTF16Selection {
            range: byte_to_utf16(text, a.min(h))..byte_to_utf16(text, a.max(h)),
            reversed: h < a,
        })
    }

    fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
        let m = self.marked.as_ref()?;
        let text = self.model.doc.leaf_text(m.block)?;
        Some(byte_to_utf16(text, m.range.start)..byte_to_utf16(text, m.range.end))
    }

    fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {
        self.end_composition();
    }

    fn paste(&mut self, item: ClipboardItem, _: &mut Window, cx: &mut Context<Self>) {
        BlockEditorState::paste(self, item, false, cx);
    }

    fn replace_text_in_range(
        &mut self,
        range16: Option<Range<usize>>,
        text: &str,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.readonly {
            return;
        }
        let composing = self.marked.is_some();
        self.select_marked_or(range16);
        let origin = if composing {
            EditOrigin::Ime
        } else {
            EditOrigin::Typing
        };
        self.edit(origin, |m| m.insert_text(text, origin), cx);
        self.end_composition();
        if text == " " {
            self.apply_input_rule(cx);
        } else if text.ends_with(['`', '*', '~']) && self.rule_on(RuleKind::InlineMarks) {
            self.apply_mark_rule(cx);
        } else if text.ends_with(')') && self.rule_on(RuleKind::Link) {
            self.apply_link_rule(cx);
        }
    }

    fn replace_and_mark_text_in_range(
        &mut self,
        range16: Option<Range<usize>>,
        new_text: &str,
        new_selected16: Option<Range<usize>>,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.readonly {
            return;
        }
        if new_text.is_empty() {
            // Cancelled composition: remove the marked text, close the group.
            if let Some(marked) = self.marked.clone() {
                self.select_marked_or(None);
                if !marked.range.is_empty() {
                    self.edit(EditOrigin::Ime, |m| m.delete(false), cx);
                }
            }
            self.end_composition();
            return;
        }
        self.select_marked_or(range16);
        let start = match self.model.doc.resolve_selection(self.model.selection()) {
            Ok(range) => range.start,
            Err(_) => return,
        };
        if !self.composition_open {
            // The whole composition is one undo step. Opened only once
            // something is about to be inserted; always closed by
            // `end_composition`.
            self.model.history.begin_transaction();
            self.composition_open = true;
        }
        let revision = self.model.revision();
        self.edit(
            EditOrigin::Ime,
            |m| m.insert_text(new_text, EditOrigin::Ime),
            cx,
        );
        let inserted = self.model.revision() != revision;
        let Some((_, head)) = self.head_anchor().filter(|_| inserted) else {
            // Nothing was inserted (e.g. into a code block): close the group.
            self.end_composition();
            return;
        };
        let block = head.block;
        let begin = if block == start.block {
            start.offset
        } else {
            head.offset.saturating_sub(new_text.len())
        };
        let range = begin..begin + new_text.len();
        self.marked = Some(Marked {
            block,
            range: range.clone(),
        });
        if let Some(sel16) = new_selected16 {
            let sel = utf16_to_byte(new_text, sel16.start)..utf16_to_byte(new_text, sel16.end);
            let _ = self.model.set_selection(BlockSelection::Text {
                anchor: BlockPosition::new(block, range.start + sel.start),
                head: BlockPosition::new(block, range.start + sel.end),
            });
        }
    }

    fn bounds_for_range(
        &mut self,
        range16: Range<usize>,
        _: Bounds<Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<Bounds<Pixels>> {
        let block = self.ime_block()?;
        let text = self.ime_text();
        let start = utf16_to_byte(text, range16.start);
        let end = utf16_to_byte(text, range16.end);
        let frame = self.frame.borrow();
        let width = self.style.caret_width();
        let a = frame.caret_bounds(BlockPosition::new(block, start), width)?;
        let b = frame.caret_bounds(BlockPosition::new(block, end), width)?;
        Some(Bounds::from_corners(
            a.origin,
            gpui::point(
                b.origin.x.max(a.origin.x + width),
                a.origin.y + a.size.height,
            ),
        ))
    }

    fn character_index_for_point(
        &mut self,
        at: Point<Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<usize> {
        let pos = self.frame.borrow().hit_test(at)?;
        if Some(pos.block) != self.ime_block() {
            return None;
        }
        Some(byte_to_utf16(self.ime_text(), pos.offset))
    }
}

/// The byte range of the contiguous run linking to `url` around `offset`.
fn link_extent(
    inline: &super::inline::InlineText,
    offset: usize,
    url: &SharedString,
) -> Option<Range<usize>> {
    let pieces: Vec<_> = inline
        .pieces()
        .map(|(range, marks, _)| (range, marks.link.as_ref().map(|l| l.url.clone())))
        .collect();
    let ix = pieces
        .iter()
        .position(|(r, _)| r.start <= offset && offset < r.end)?;
    let same = |i: usize| pieces[i].1.as_ref() == Some(url);
    let (mut lo, mut hi) = (ix, ix);
    while lo > 0 && same(lo - 1) {
        lo -= 1;
    }
    while hi + 1 < pieces.len() && same(hi + 1) {
        hi += 1;
    }
    Some(pieces[lo].0.start..pieces[hi].0.end)
}

/// `[text](url)` ending at `caret`: the `[` offset, the text and the url.
fn link_rule(text: &str, caret: usize) -> Option<(usize, String, String)> {
    let before = text.get(..caret)?.strip_suffix(')')?;
    let open_paren = before.rfind("](")?;
    let url = &before[open_paren + 2..];
    if url.is_empty() || url.contains(char::is_whitespace) {
        return None;
    }
    let head = &before[..open_paren];
    let open = head.rfind('[')?;
    let label = &head[open + 1..];
    if label.is_empty() || label.contains(['[', ']']) {
        return None;
    }
    Some((open, label.to_string(), url.to_string()))
}

/// The language of a typed code fence (```` ``` ```` plus an optional word).
fn code_fence(text: &str) -> Option<String> {
    let lang = text.strip_prefix("```")?;
    lang.chars()
        .all(|c| c.is_alphanumeric() || matches!(c, '+' | '-' | '_' | '#' | '.'))
        .then(|| lang.to_string())
}

/// The `(opening delimiter, closing delimiter, mark)` of an inline-mark input
/// rule whose closing delimiter ends at `caret`, if any. Nothing fires inside
/// inline code, across an atom, or around empty / space-padded content.
fn mark_rule(
    inline: &super::inline::InlineText,
    caret: usize,
) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
    let text = inline.text();
    let prefix = text.get(..caret)?;
    let (delim, kind) = if prefix.ends_with('`') {
        ("`", MarkKind::Code)
    } else if prefix.ends_with("~~") {
        ("~~", MarkKind::Strikethrough)
    } else if prefix.ends_with("**") {
        ("**", MarkKind::Bold)
    } else if prefix.ends_with('*') {
        ("*", MarkKind::Italic)
    } else {
        return None;
    };
    let close = caret - delim.len()..caret;
    let before = &prefix[..close.start];
    let start = before.rfind(delim)?;
    // `*` must not be half of a `**`.
    if delim == "*" && (before[..start].ends_with('*') || before.ends_with('*')) {
        return None;
    }
    let open = start..start + delim.len();
    let content = &text[open.end..close.start];
    if content.is_empty()
        || content.contains(super::inline::ATOM_CHAR)
        || (kind != MarkKind::Code
            && (content.starts_with(char::is_whitespace) || content.ends_with(char::is_whitespace)))
    {
        return None;
    }
    let in_code = inline
        .pieces()
        .any(|(r, m, _)| m.code && r.start < close.end && r.end > open.start);
    (!in_code).then_some((open, close, kind))
}