cellix 0.5.2

The AI companion IDE inside your agent: a Claude Code mod, Codex plugin and Gemini CLI extension
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
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use cellix_core::{Buffer, Motion, Selection, Selections};
use cellix_doc::changes::{self, Change, Kind, Syntax};
use cellix_doc::latex::Project;
use cellix_doc::notebook::{Marker, Notebook, marker};
use cellix_doc::prose::{Issue, Source};
use cellix_doc::table::Edit as TableEdit;
use cellix_input::{Command, Direction, Format};
use cellix_lang::{Registry, Span, Worker};
use cellix_render::{
    Bounds, Font, Grid, INTERFACE_SIZE, Icon, Measure, Paint, Rect, Rgb, Strip, units,
};
use cellix_review::LineChange;
use unicode_width::UnicodeWidthChar;

use crate::panels::Symbol;
use crate::rendered::{
    self, Callout, Dialect, Extras, Figure, Glyph, Intent, Library, Row, Target, Tone,
};
use crate::snippets::Snippet;
use crate::theme::Theme;

const TAB_WIDTH: usize = 4;
const GUTTER_MIN_DIGITS: usize = 4;
const NARROW_PANE: u16 = 60;
/// Left margin of a rendered page, which also carries comment marks.
/// Heading levels the toolbar steps through before going back to plain text.
const MAX_HEADING_CYCLE: usize = 3;
const INDENT: &str = "    ";
const MINIMAP_WIDTH: u16 = 13;
/// Lines of code a minimap fits in one row of the grid.
const MINIMAP_LINES_PER_ROW: usize = 6;
/// Columns of code a minimap shows, past which lines are cut off.
const MINIMAP_COLUMNS: usize = 96;
/// Narrower panes spend every column on the code, as beside an agent.
const MIN_MINIMAP_PANE: u16 = 90;
/// Files up to this size highlight as they're drawn. Past it, a background thread does it,
/// because a full reparse on each key starts to show.
const MAX_INLINE_HIGHLIGHT: usize = 32 * 1024;
/// How far a tall heading sits below its row: closer to its own text than to what's above.
const TALL_DROP: f32 = 0.9;
const PAGE_MARGIN: u16 = 2;
const WIDE_PAGE_MARGIN: u16 = 4;
/// How wide a page can be set.
const MAX_PAGE_WIDTH: u16 = 512;

/// Per-line marks for the gutter, as 1-based lines.
#[derive(Default)]
pub struct Marks {
    pub comments: Vec<usize>,
    pub errors: Vec<usize>,
}

/// A page's rows, its figures, and where its formulas and images are.
type LaidOut = (
    Rc<Vec<Row>>,
    Vec<Figure>,
    Vec<(usize, usize)>,
    Option<usize>,
);

/// A laid-out page, and what it was made for.
struct PageCache {
    revision: u64,
    width: usize,
    /// The formula showing as source.
    open: Option<(usize, usize)>,
    rows: Rc<Vec<Row>>,
    figures: Rc<Vec<Figure>>,
    /// Every formula and image, which the caret opens by moving into.
    spans: Rc<Vec<(usize, usize)>>,
    /// The picture of a formula being edited in a line.
    preview: Option<usize>,
}

/// One open document and where the view is within it.
/// A colour pulled towards the background, as text is at a minimap's size.
fn dimmed(color: Rgb, bg: Rgb) -> Rgb {
    let mix = |a: u8, b: u8| ((a as u16 * 3 + b as u16 * 2) / 5) as u8;
    Rgb(mix(color.0, bg.0), mix(color.1, bg.1), mix(color.2, bg.2))
}

/// Bars per row, with the revision, height and width they fit.
type MinimapRows = ((u64, u16, u16), Vec<Vec<Strip>>);

pub struct Editor {
    pub buffer: Buffer,
    pub selections: Selections,
    /// Char ranges to mark, while find is open.
    pub found: Vec<(usize, usize)>,
    /// The last commit's copy of this file, to mark changed lines against.
    pub committed: Option<String>,
    /// Changed lines by number, with the revision they were worked out at.
    changes: RefCell<(u64, HashMap<usize, LineChange>)>,
    /// Bars for each row of the minimap, with what they were built for.
    minimap: RefCell<Option<MinimapRows>>,
    pub top: usize,
    pub left: usize,
    spans: RefCell<Option<(u64, Vec<Span>)>>,
    /// How many rows the pane showed last, which is what bounds scrolling.
    view_rows: Cell<u16>,
    /// Started for the first large file, and only then.
    worker: OnceCell<Worker>,
    /// The revision the worker was last asked about.
    asked: Cell<u64>,
    /// What the cached spans were read from, to carry them across an edit.
    spans_bytes: Cell<usize>,
    /// Show Markdown as an editable page rather than its source, as Xcode does.
    pub rendered: bool,
    /// The file changed on disk under unsaved edits, so saving would erase that change.
    pub conflict: bool,
    /// Whether the minimap may show, given the room.
    pub minimap_on: bool,
    /// The laid-out page, for one revision and width.
    page: RefCell<Option<PageCache>>,
    /// Formulas and images already drawn, so typing doesn't redo them.
    library: RefCell<Library>,
    /// Whether the sheet is dark, which diagrams are drawn for.
    dark: Cell<bool>,
    /// How wide the text was drawn, for what's drawn beside it.
    view_width: Cell<u16>,
    /// Whether typing here is kept as suggested changes.
    pub tracking: bool,
    /// While an agent's edits stand as suggestions nobody has touched: the text from before
    /// its first edit, and the buffer as Cellix last marked it. A later edit from the same
    /// turn is marked against that text again, so the edits pile up into one review.
    pub agent_review: Option<(String, String)>,
    /// The word count, how many files it took in, and what it was counted at: this file's
    /// revision, and a stamp of the other open files' unsaved edits.
    words: Cell<Option<Counted>>,
    /// The paper's other files as last read.
    paper_files: RefCell<cellix_doc::paper::Files>,
    /// The paper a LaTeX file belongs to, looked for again only once the file is saved.
    paper_root: RefCell<Option<PathBuf>>,
    /// The notebook this page was read from, which saving writes back into.
    pub notebook: Option<Notebook>,
    /// Spelling and grammar, for the revision they were checked at.
    pub issues: (u64, Vec<Issue>),
    /// The revision last sent to be checked.
    pub checked: u64,
    /// Where built pieces of LaTeX are kept.
    pub built: Option<PathBuf>,
    /// Pieces of LaTeX this page is waiting for, for the app to have built.
    wanted: RefCell<Vec<Snippet>>,
    /// Text comments are about, as char ranges, tinted on a page.
    pub quoted: RefCell<Vec<(usize, usize)>>,
    /// The paper this file belongs to, and the revision it was read at.
    project: RefCell<Option<(u64, Rc<Project>)>>,
    show_preamble: bool,
    measure: Rc<dyn Measure>,
    registry: Rc<Registry>,
    /// The revision last sent to a language server.
    pub synced: u64,
}

/// A word count, how many files it took in, and what it was counted at: the file's revision and a
/// stamp of the other open files' unsaved edits.
type Counted = ((u64, u64), usize, usize);

fn display_width(c: char, column: usize) -> usize {
    if c == '\t' {
        TAB_WIDTH - column % TAB_WIDTH
    } else {
        c.width().unwrap_or(0)
    }
}

/// The colour a callout's bar and title take.
fn callout_colour(kind: Callout, theme: &Theme) -> Rgb {
    match kind {
        Callout::Note => theme.accent,
        Callout::Tip => theme.inserted(),
        Callout::Important => Rgb(0x88, 0x57, 0xe0),
        Callout::Warning => Rgb(0xc0, 0x86, 0x10),
        Callout::Caution => theme.deleted(),
    }
}

/// How far below a paper's figure the line naming its image can be.
const FIGURE_LINES: usize = 6;

impl Editor {
    pub fn new(buffer: Buffer, measure: Rc<dyn Measure>, registry: Rc<Registry>) -> Self {
        // A file of definitions is code: it has no page to show.
        let definitions = |text: &str| {
            let lines = text.lines().filter(|l| !l.trim().is_empty());
            let marks = [
                "\\newcommand",
                "\\renewcommand",
                "\\def",
                "\\usepackage",
                "\\Declare",
            ];
            let (total, defining) = lines.fold((0, 0), |(total, defining), line| {
                let is = marks.iter().any(|m| line.trim_start().starts_with(m));
                (total + 1, defining + usize::from(is))
            });
            total > 0 && defining * 2 > total
        };
        let is_page =
            buffer.path().is_some_and(|p| Dialect::of(p).is_some()) && !definitions(&buffer.text());
        Self {
            buffer,
            selections: Selections::default(),
            found: Vec::new(),
            committed: None,
            changes: RefCell::new((u64::MAX, HashMap::new())),
            minimap: RefCell::new(None),
            top: 0,
            left: 0,
            spans: RefCell::new(None),
            view_rows: Cell::new(0),
            worker: OnceCell::new(),
            asked: Cell::new(u64::MAX),
            spans_bytes: Cell::new(0),
            rendered: is_page,
            conflict: false,
            minimap_on: true,
            page: RefCell::new(None),
            library: RefCell::default(),
            dark: Cell::new(false),
            view_width: Cell::new(0),
            tracking: false,
            agent_review: None,
            words: Cell::new(None),
            paper_files: RefCell::default(),
            paper_root: RefCell::new(None),
            notebook: None,
            issues: (0, Vec::new()),
            checked: 0,
            built: None,
            wanted: RefCell::default(),
            quoted: RefCell::default(),
            project: RefCell::new(None),
            show_preamble: false,
            measure,
            registry,
            synced: 0,
        }
    }

    pub fn title(&self) -> String {
        self.buffer
            .path()
            .and_then(Path::file_name)
            .map_or_else(|| "untitled".into(), |n| n.to_string_lossy().into_owned())
    }

    /// Whether a pane has room for a minimap, which only pixels can draw.
    fn shows_minimap(&self, area: Rect) -> bool {
        // A document that fits has nothing for a minimap to show.
        let fits = self.rendered && {
            let cache = self.page.borrow();
            cache
                .as_ref()
                .is_some_and(|p| p.rows.len() <= area.h as usize)
        };
        self.minimap_on && !self.measure.in_cells() && area.w >= MIN_MINIMAP_PANE && !fits
    }

    /// Where text goes in `area`: all of it, less the minimap or the scrollbar.
    fn text_area(&self, area: Rect) -> Rect {
        let side = if self.shows_minimap(area) {
            MINIMAP_WIDTH
        } else {
            1
        };
        Rect::new(area.x, area.y, area.w.saturating_sub(side), area.h)
    }

    /// Forgets the changed lines, as when the file's committed copy changes.
    pub fn refresh_changes(&self) {
        self.changes.borrow_mut().0 = u64::MAX;
    }

    fn line_changes(&self) -> std::cell::Ref<'_, (u64, HashMap<usize, LineChange>)> {
        let revision = self.buffer.revision();
        if self.changes.borrow().0 != revision {
            let found = self.committed.as_ref().map_or_else(HashMap::new, |old| {
                cellix_review::line_changes(old, &self.buffer.text())
                    .into_iter()
                    .collect()
            });
            *self.changes.borrow_mut() = (revision, found);
        }
        self.changes.borrow()
    }

    /// The bar beside a changed line, in the margin of `x`.
    fn draw_change(&self, grid: &mut Grid, x: f32, y: u16, change: LineChange, theme: &Theme) {
        let color = match change {
            LineChange::Added => theme.git_added,
            LineChange::Modified => theme.git_modified,
            LineChange::DeletedAbove => theme.error,
        };
        let bounds = match change {
            LineChange::DeletedAbove => Bounds::cells(x, y as f32 - 0.06, 0.55, 0.12),
            _ => Bounds::cells(x, y as f32, 0.28, 1.0),
        };
        grid.panel(bounds, 0, Some(color), None);
        if self.measure.in_cells() {
            let style = cellix_render::Style {
                fg: color,
                ..theme.gutter
            };
            grid.put_str(x as u16, y, "▎", style, x as u16 + 1);
        }
    }

    /// The words of a line of code, as (column, length, colour).
    fn code_words(&self, line: usize, spans: &[Span], theme: &Theme) -> Vec<(usize, usize, Rgb)> {
        let start = self.buffer.rope().line_to_byte(line);
        let text = self.line_text(line);
        let mut words = Vec::new();
        let (mut column, mut byte) = (0, 0);
        for word in text.split_inclusive(char::is_whitespace) {
            let size = word.trim_end().chars().count();
            if size > 0 {
                let at = start + byte;
                let found = spans.partition_point(|s| s.end <= at);
                let span = spans.get(found).filter(|s| s.start <= at);
                let color = span.map_or(theme.text.fg, |s| theme.token(s.token));
                words.push((column, size, color));
            }
            column += word.chars().count();
            byte += word.len();
        }
        words
    }

    /// The words of a page row, in the same shape.
    fn page_words(row: &Row, theme: &Theme) -> Vec<(usize, usize, Rgb)> {
        let color = |tone| match tone {
            Tone::Heading => theme.heading,
            Tone::Code | Tone::Block(_) => theme.string,
            Tone::Link | Tone::Check(_) => theme.accent,
            _ => theme.text.fg,
        };
        let mut words = Vec::new();
        let mut run: Option<(usize, usize, Rgb)> = None;
        for g in &row.glyphs {
            if g.ch.is_whitespace() {
                words.extend(run.take());
            } else {
                let column = g.x as usize;
                let word = run.get_or_insert((column, 0, color(g.tone)));
                word.1 = (column + 1).saturating_sub(word.0);
            }
        }
        words.extend(run);
        words
    }

    /// Bars for each row of a minimap `rows` tall, in the colours of the code. The whole
    /// file always fits, so the map's fill shows how long the file is.
    fn minimap_rows(&self, rows: u16, text: Rect, theme: &Theme) -> Vec<Vec<Strip>> {
        let page = self.rendered.then(|| self.page(text));
        let lines = page
            .as_ref()
            .map_or_else(|| self.buffer.rope().len_lines(), |p| p.len());
        let capacity = rows as usize * MINIMAP_LINES_PER_ROW;
        let shown = lines.min(capacity);
        let mut out = vec![Vec::new(); rows as usize];
        let spans = self.spans.borrow();
        let no_spans = Vec::new();
        let spans = spans.as_ref().map_or(&no_spans, |(_, spans)| spans);
        for slot in 0..shown {
            let line = slot * lines / shown.max(1);
            let words = match &page {
                Some(page) => Self::page_words(&page[line], theme),
                None => self.code_words(line, spans, theme),
            };
            let row = slot / MINIMAP_LINES_PER_ROW;
            let y = ((slot % MINIMAP_LINES_PER_ROW) * 256 / MINIMAP_LINES_PER_ROW) as u8;
            for (column, size, color) in words {
                if column < MINIMAP_COLUMNS {
                    let x = (column * 256 / MINIMAP_COLUMNS) as u8;
                    let w = (size.min(MINIMAP_COLUMNS - column) * 256 / MINIMAP_COLUMNS) as u8;
                    let color = dimmed(color, theme.text.bg);
                    out[row].push(Strip { x, y, w, color });
                }
            }
        }
        out
    }

    /// Pictures in the map, small, where they stand in the document.
    fn draw_minimap_pictures(
        &self,
        grid: &mut Grid,
        track: Rect,
        (margin, width): (f32, f32),
        theme: &Theme,
    ) {
        if !self.rendered {
            return;
        }
        let area = self.text_area(Rect::new(
            track.x.saturating_sub(self.view_width.get()),
            track.y,
            self.view_width.get() + track.w,
            track.h,
        ));
        let page = self.page(area);
        let figures = self.figures();
        let per_row = MINIMAP_LINES_PER_ROW as f32;
        let capacity = track.h as f32 * per_row;
        let squeeze = (capacity / page.len().max(1) as f32).min(1.0);
        let column = width / MINIMAP_COLUMNS as f32;
        let clip = Bounds::cells(
            track.x as f32,
            track.y as f32,
            track.w as f32,
            track.h as f32,
        );
        for (index, row) in page.iter().enumerate() {
            let Some((figure, x)) = row.figure else {
                continue;
            };
            let Some(figure) = figures.get(figure) else {
                continue;
            };
            let top = track.y as f32 + index as f32 * squeeze / per_row;
            let bounds = Bounds::cells(
                track.x as f32 + margin + x * column,
                top,
                figure.width * column,
                figure.height * squeeze / per_row,
            );
            grid.paint.push(Paint::Image {
                bounds,
                clip,
                bitmap: figure.bitmap.clone(),
                color: dimmed(theme.text.fg, theme.text.bg),
            });
        }
    }

    fn draw_minimap(&self, grid: &mut Grid, full: Rect, theme: &Theme) {
        let text = self.text_area(full);
        let track = Rect::new(text.right(), full.y, full.w - text.w, full.h);
        grid.fill(track, theme.text);
        let total = if self.rendered {
            self.page(text).len()
        } else {
            self.buffer.rope().len_lines()
        }
        .max(1);
        let revision = self.buffer.revision();
        let built = (revision, track.h, text.w);
        let stale = !self
            .minimap
            .borrow()
            .as_ref()
            .is_some_and(|(key, _)| *key == built);
        if stale {
            let rows = self.minimap_rows(track.h, text, theme);
            *self.minimap.borrow_mut() = Some((built, rows));
        }
        let height = track.h as f32;
        let filled = (total as f32 / MINIMAP_LINES_PER_ROW as f32).min(height);
        let span = (text.h as f32 * filled / total as f32).clamp(1.0, height);
        // Past the fold the marker's top stops short, so the end of the file meets the end
        // of the map rather than sliding off it.
        let range = total.saturating_sub(text.h as usize).max(1) as f32;
        let travel = (filled - span).max(0.0);
        let top = track.y as f32 + (self.top as f32 / range).min(1.0) * travel;
        let margin = 0.6;
        let width = track.w as f32 - margin * 1.5;
        let view = Bounds::cells(track.x as f32 + margin - 0.3, top, width + 0.6, span);
        grid.panel(view, 12, Some(theme.minimap_view), Some(theme.popup_border));
        self.draw_minimap_pictures(grid, track, (margin, width), theme);
        if let Some((_, rows)) = self.minimap.borrow().as_ref() {
            for (row, strips) in rows.iter().enumerate().filter(|(_, s)| !s.is_empty()) {
                let bounds = Bounds::cells(
                    track.x as f32 + margin,
                    track.y as f32 + row as f32,
                    width,
                    1.0,
                );
                grid.paint.push(cellix_render::Paint::Strips {
                    bounds,
                    strips: strips.clone(),
                });
            }
        }
        // Changes down the edge, so they're findable in a long file.
        let lines = self.buffer.rope().len_lines().max(1);
        let fill_lines = lines as f32;
        for (line, change) in &self.line_changes().1 {
            let y = track.y as f32 + *line as f32 * filled / fill_lines;
            let color = match change {
                LineChange::Added => theme.git_added,
                LineChange::Modified => theme.git_modified,
                LineChange::DeletedAbove => theme.error,
            };
            let height = (filled / fill_lines).max(0.1);
            let mark = Bounds::cells(track.right() as f32 - 0.45, y, 0.3, height);
            grid.panel(mark, 0, Some(color), None);
        }
    }

    /// Scrolls to a point on the minimap or scrollbar.
    fn map_filled(&self, area: Rect, lines: usize) -> usize {
        if self.shows_minimap(area) {
            (lines.div_ceil(MINIMAP_LINES_PER_ROW)).clamp(1, area.h as usize)
        } else {
            area.h.max(1) as usize
        }
    }

    /// Pages use the whole pane, with room in the margin for marks.
    fn page_margin(area: Rect) -> u16 {
        if area.w < NARROW_PANE {
            PAGE_MARGIN
        } else {
            WIDE_PAGE_MARGIN
        }
    }

    fn page_width(area: Rect) -> usize {
        area.w
            .saturating_sub(Self::page_margin(area) * 2 + 1)
            .clamp(1, MAX_PAGE_WIDTH) as usize
    }

    /// The paper this file is part of, read again once each time the file is saved.
    fn project(&self, text: &str) -> Rc<Project> {
        let saved = self.buffer.is_dirty();
        let mut cache = self.project.borrow_mut();
        if let Some((revision, project)) = cache.as_ref()
            && (saved || *revision == self.buffer.revision())
        {
            return project.clone();
        }
        let project = match self.buffer.path() {
            Some(path) if !saved => {
                let root = cellix_doc::latex::root_of(path, text);
                Project::read(&root)
            }
            _ => Project::from_text(text),
        };
        let project = Rc::new(project);
        *cache = Some((self.buffer.revision(), project.clone()));
        project
    }

    /// Words in the document, and in the selection when there is one. A paper split over
    /// `\input` files counts whole, from its root, and the last says it did; any of its files
    /// open in `others` counts as edited there, saved or not. Counted once a revision.
    pub fn word_count(&self, others: &[&Editor]) -> (usize, Option<usize>, bool) {
        let latex = self.dialect() == Dialect::Latex;
        // Other open papers with unsaved edits, which count as they stand.
        let unsaved: Vec<&Editor> = others
            .iter()
            .copied()
            .filter(|e| latex && e.buffer.is_dirty() && e.dialect() == Dialect::Latex)
            .filter(|e| e.buffer.path().is_some() && !std::ptr::eq(*e, self))
            .collect();
        let stamp = {
            use std::hash::{Hash, Hasher};
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            for editor in &unsaved {
                (editor.buffer.path(), editor.buffer.revision()).hash(&mut hasher);
            }
            hasher.finish()
        };
        let revision = (self.buffer.revision(), stamp);
        let (all, files) = match self.words.get() {
            Some((counted, words, files)) if counted == revision => (words, files),
            _ => {
                let text = self.buffer.text();
                let (words, files) = match self.buffer.path().filter(|_| latex) {
                    Some(path) => {
                        let root = self.paper_root(path, &text);
                        let texts: Vec<(&Path, String)> = unsaved
                            .iter()
                            .filter_map(|e| Some((e.buffer.path()?, e.buffer.text())))
                            .collect();
                        let mut open = vec![(path, text.as_str())];
                        open.extend(texts.iter().map(|(p, t)| (*p, t.as_str())));
                        let mut files = self.paper_files.borrow_mut();
                        cellix_doc::words::paper(&root, path, &open, &mut files)
                    }
                    None => (cellix_doc::words::count(&text, latex), 1),
                };
                self.words.set(Some((revision, words, files)));
                (words, files)
            }
        };
        let selected = self
            .selected_text()
            .filter(|t| !t.trim().is_empty())
            .map(|t| cellix_doc::words::count(&t, false));
        (all, selected, files > 1)
    }

    /// Counts again on the next look, as when another file of the paper was saved.
    pub fn recount(&self) {
        self.words.set(None);
    }

    /// The root of the paper this file is in. Finding it can read the folder, so it's found
    /// again only while the file is as saved, not on every keystroke.
    fn paper_root(&self, path: &Path, text: &str) -> PathBuf {
        let mut known = self.paper_root.borrow_mut();
        match known.as_ref() {
            Some(root) if self.buffer.is_dirty() => root.clone(),
            _ => known.insert(cellix_doc::latex::root_of(path, text)).clone(),
        }
    }

    /// How this document writes a suggestion.
    pub fn change_syntax(&self) -> cellix_doc::changes::Syntax {
        if self.dialect() == Dialect::Latex {
            cellix_doc::changes::Syntax::Latex
        } else {
            cellix_doc::changes::Syntax::Critic
        }
    }

    /// Replaces the whole text as one edit, keeping the caret where it was as far as it can.
    pub fn set_all_text(&mut self, text: &str) {
        let head = self.selections.primary().head;
        self.selections.set_single(Selection {
            anchor: 0,
            head: self.buffer.rope().len_chars(),
            goal: None,
        });
        self.buffer.replace(&mut self.selections, text);
        let end = self.buffer.rope().len_chars();
        self.selections.set_single(Selection::cursor(head.min(end)));
    }

    /// The paper this file belongs to, with its labels and citations.
    pub fn latex_project(&self) -> Rc<Project> {
        self.project(&self.buffer.text())
    }

    /// Where a clickable row leads, if there's one at this place on screen.
    pub fn row_target(&self, area: Rect, y: u16) -> Option<Target> {
        let area = self.text_area(area);
        let rows = self.page(area);
        let row = self.top + y.saturating_sub(area.y) as usize;
        rows.get(row)?.target.clone()
    }

    /// Shows or hides a paper's preamble.
    pub fn toggle_preamble(&mut self) {
        self.show_preamble = !self.show_preamble;
        *self.page.borrow_mut() = None;
    }

    pub fn dialect(&self) -> Dialect {
        let path = self.buffer.path();
        path.and_then(Dialect::of).unwrap_or_default()
    }

    /// Lays the page out, with `open` showing as source.
    fn lay_out(&self, text: &str, width: usize, open: Option<(usize, usize)>) -> LaidOut {
        let folder = self.buffer.path().and_then(Path::parent);
        let dialect = self.dialect();
        let extras = Extras {
            dialect,
            project: (dialect == Dialect::Latex).then(|| self.project(text)),
            file: self.buffer.path(),
            preamble: self.show_preamble,
            open,
            folder,
            library: Some(&self.library),
            dark: self.dark.get(),
            built: self.built.as_deref(),
            notebook: self.notebook.as_ref(),
            ..Extras::default()
        };
        let rows = rendered::layout_with(text, width, &*self.measure, &self.registry, &extras);
        self.wanted.borrow_mut().extend(extras.wanted.take());
        (
            Rc::new(rows),
            extras.figures.into_inner(),
            extras.spans.into_inner(),
            extras.preview.into_inner(),
        )
    }

    /// The rendered page for this width, laid out again only after an edit, or when the
    /// caret moves into or out of a formula.
    fn page(&self, area: Rect) -> Rc<Vec<Row>> {
        let width = Self::page_width(area);
        let revision = self.buffer.revision();
        let head = self.selections.primary().head;
        let mut cache = self.page.borrow_mut();
        let stale = cache
            .as_ref()
            .is_none_or(|c| c.revision != revision || c.width != width);
        if stale {
            let text = self.buffer.text();
            let (rows, figures, spans, _) = self.lay_out(&text, width, None);
            *cache = Some(PageCache {
                revision,
                width,
                open: None,
                rows,
                figures: Rc::new(figures),
                spans: Rc::new(spans),
                preview: None,
            });
        }
        let page = cache.as_mut().expect("laid out above");
        let open = page
            .spans
            .iter()
            .copied()
            .find(|s| s.0 < head && head < s.1);
        if open != page.open {
            let text = self.buffer.text();
            let (rows, figures, _, preview) = self.lay_out(&text, width, open);
            page.open = open;
            page.rows = rows;
            page.figures = Rc::new(figures);
            page.preview = preview;
        }
        page.rows.clone()
    }

    fn figures(&self) -> Rc<Vec<Figure>> {
        let cache = self.page.borrow();
        cache
            .as_ref()
            .map_or_else(Rc::default, |page| page.figures.clone())
    }

    /// The picture a screen row is on, of any kind: its source line and its box on the
    /// screen, as left, right, top and bottom.
    pub fn figure_on_row(&self, area: Rect, y: u16) -> Option<(usize, [f32; 4])> {
        let area = self.text_area(area);
        let rows = self.page(area);
        let figures = self.figures();
        let left = (area.x + Self::page_margin(area)) as f32;
        let row = (y as f32) + 0.5;
        for (index, found) in rows.iter().enumerate() {
            let Some((figure, x)) = found.figure else {
                continue;
            };
            let figure = figures.get(figure)?;
            let top = area.y as f32 + index as f32 - self.top as f32 + 0.2;
            if row < top || row > top + figure.height {
                continue;
            }
            let shown = [left + x, left + x + figure.width, top, top + figure.height];
            return Some((found.line, shown));
        }
        None
    }

    /// The source line of the code block a screen row is in, and the screen row its first
    /// row is on.
    pub fn code_block_on_row(&self, area: Rect, y: u16) -> Option<(usize, u16)> {
        let area = self.text_area(area);
        let rows = self.page(area);
        let index = self.top + y.checked_sub(area.y)? as usize;
        let row = rows.get(index).filter(|r| r.shaded)?;
        let first = (0..=index).rev().take_while(|n| rows[*n].shaded).last()?;
        let top = first.max(self.top) - self.top;
        Some((row.line, area.y + top as u16))
    }

    /// The image a screen row is on. Formulas and diagrams have no size of their own to change.
    fn image_on_row(&self, area: Rect, y: u16) -> Option<(usize, [f32; 4])> {
        let (line, shown) = self.figure_on_row(area, y)?;
        let text = self.line_text(line);
        let names_one = cellix_doc::figure::image_line(&text).is_some()
            || self.dialect() == Dialect::Latex && {
                let lines = line..self.buffer.rope().len_lines();
                let mut lines = lines.take(FIGURE_LINES);
                lines.any(|n| self.line_text(n).contains("\\includegraphics"))
            };
        names_one.then_some((line, shown))
    }

    /// What a comment on a picture is about, in words an agent can act on.
    pub fn figure_quote(&self, line: usize) -> String {
        let text = self.line_text(line);
        let next = || self.line_text(line + 1).trim().to_string();
        if let Some(image) = cellix_doc::figure::image_line(&text) {
            return format!("Image {}", image.path);
        }
        let trimmed = text.trim();
        if let Some(language) = trimmed.strip_prefix("```") {
            return format!("{} diagram: {}", language.trim(), next());
        }
        if trimmed.starts_with("$$") || trimmed.starts_with("\\[") {
            return format!("Formula: {}", trimmed.trim_matches('$'));
        }
        let lines = line..self.buffer.rope().len_lines();
        let named = lines.take(FIGURE_LINES).find_map(|n| {
            let source = self.line_text(n);
            let open = source.find("\\includegraphics")?;
            let brace = open + source[open..].find('{')?;
            let close = brace + source[brace..].find('}')?;
            Some(source[brace + 1..close].to_string())
        });
        match named {
            Some(path) => format!("Image {path}"),
            None => format!("Figure: {trimmed}"),
        }
    }

    /// Shows a handle on the image under the pointer.
    pub fn draw_hover(&self, grid: &mut Grid, area: Rect, hover: (u16, u16), theme: &Theme) {
        if self.rendered && !self.measure.in_cells() {
            self.draw_image_handle(grid, area, hover, theme);
        }
    }

    /// The image whose right edge is under the pointer, ready to be dragged.
    pub fn image_edge(&self, area: Rect, x: f32, y: u16) -> Option<usize> {
        const REACH: f32 = 1.2;
        let (line, [_, right, ..]) = self.image_on_row(area, y)?;
        ((x - right).abs() <= REACH).then_some(line)
    }

    /// Sets an image's width from where its edge was dragged to. A picture stands in the
    /// middle of the page, so the edge is half its width from there.
    pub fn drag_image(&mut self, area: Rect, line: usize, x: f32) {
        const STEP: f32 = 5.0;
        let page = Self::page_width(self.text_area(area)) as f32;
        let middle = (area.x + Self::page_margin(self.text_area(area))) as f32 + page / 2.0;
        let share = (x - middle).max(0.0) * 2.0 / page.max(1.0) * 100.0;
        let percent = ((share / STEP).round() * STEP).clamp(STEP * 2.0, 100.0) as u32;
        let at = self.buffer.position(line, 0);
        self.selections.set_single(Selection::cursor(at));
        self.set_image_width(percent);
    }

    /// Draws the pictures in view, including those that started above it.
    fn draw_image_handle(&self, grid: &mut Grid, area: Rect, hover: (u16, u16), theme: &Theme) {
        let Some((_, [_, right, top, bottom])) = self.image_on_row(area, hover.1) else {
            return;
        };
        let middle = (top + bottom) / 2.0;
        let handle = Bounds::cells(right + 0.25, middle - 0.8, 0.3, 1.6);
        grid.panel(handle, 30, Some(theme.accent), None);
    }

    fn draw_figures(&self, grid: &mut Grid, area: Rect, rows: &[Row], theme: &Theme) {
        let figures = self.figures();
        let left = (area.x + Self::page_margin(area)) as f32;
        let end = (self.top + area.h as usize).min(rows.len());
        for (index, row) in rows.iter().enumerate().take(end) {
            let Some((figure, x)) = row.figure else {
                continue;
            };
            let Some(figure) = figures.get(figure) else {
                continue;
            };
            let top = area.y as f32 + index as f32 - self.top as f32;
            if top + figure.height < area.y as f32 {
                continue;
            }
            grid.paint.push(Paint::Image {
                bounds: Bounds::cells(left + x, top + 0.2, figure.width, figure.height),
                clip: Bounds::cells(area.x as f32, area.y as f32, area.w as f32, area.h as f32),
                bitmap: figure.bitmap.clone(),
                color: theme.text.fg,
            });
        }
    }

    /// The page as it stands, for tests to read.
    #[cfg(test)]
    pub fn page_rows(&self, area: Rect) -> Rc<Vec<Row>> {
        self.page(self.text_area(area))
    }

    /// What this page is waiting on LaTeX for.
    pub fn take_wanted(&self) -> Vec<Snippet> {
        self.wanted.take()
    }

    /// Sets the page again, now something it was waiting for has come.
    pub fn refresh_page(&mut self) {
        *self.page.borrow_mut() = None;
    }

    /// Text is measured differently from here on, so the page has to be set again.
    pub fn set_measure(&mut self, measure: Rc<dyn Measure>) {
        self.measure = measure;
        *self.page.borrow_mut() = None;
        *self.library.borrow_mut() = Library::default();
    }

    /// Moves a caret out of hidden source, so typing never lands inside a marker.
    pub fn prepare_edit(&mut self, area: Rect) {
        if !self.rendered {
            return;
        }
        let area = self.text_area(area);
        let primary = self.selections.primary();
        // Only for one caret: replacing it would end a multi-cursor edit after a letter.
        if primary.is_empty() && self.selections.len() == 1 {
            let at = rendered::snap(&self.page(area), primary.head);
            self.selections.set_single(Selection::cursor(at));
        }
    }

    /// Runs a move on the page, where rows and hidden markers change what it means.
    fn move_on_page(&mut self, area: Rect, direction: Direction, extend: bool) -> bool {
        let rows = self.page(area);
        // Start from a visible place, so a selection never takes in a hidden marker.
        let mut primary = self.selections.primary();
        if primary.is_empty() {
            let at = rendered::snap(&rows, primary.head);
            primary.anchor = at;
            primary.head = at;
        }
        let head = primary.head;
        let page = area.h.max(2) as isize - 1;
        let (_, column) = rendered::locate(&rows, head);
        // Selection keeps its goal as a whole number, so this one is in paint units.
        let goal = primary
            .goal
            .map_or(column, |g| g as f32 / units(1.0) as f32);
        let vertical = |delta| rendered::vertical(&rows, head, delta, goal);
        let (next, keep_goal) = match direction {
            Direction::Left => (rendered::step(&rows, head, false), false),
            Direction::Right => (rendered::step(&rows, head, true), false),
            Direction::Up => (vertical(-1), true),
            Direction::Down => (vertical(1), true),
            Direction::PageUp => (vertical(-page), true),
            Direction::PageDown => (vertical(page), true),
            Direction::LineStart | Direction::LineColumnZero => {
                (rendered::row_edge(&rows, head, false), false)
            }
            Direction::LineEnd => (rendered::row_edge(&rows, head, true), false),
            _ => return false,
        };
        self.selections.set_single(Selection {
            anchor: if extend { primary.anchor } else { next },
            head: next,
            goal: keep_goal.then_some(units(goal) as usize),
        });
        true
    }

    fn line_of_head(&self) -> (String, usize) {
        let rope = self.buffer.rope();
        let line = rope.char_to_line(self.selections.primary().head);
        (self.line_text(line), rope.line_to_char(line))
    }

    /// Enter on a page continues lists and quotes, and ends them on an empty item.
    fn enter_on_page(&mut self) {
        let (line, start) = self.line_of_head();
        let head = self.selections.primary().head;
        let at_end = head == start + line.chars().count();
        match rendered::enter_intent(&line) {
            Intent::Continue(marker) if at_end => {
                self.buffer
                    .replace(&mut self.selections, &format!("\n{marker}"));
            }
            Intent::EndList(hidden) => {
                self.buffer
                    .replace_range(&mut self.selections, start, start + hidden, "");
                self.selections.set_single(Selection::cursor(start));
            }
            _ => self.buffer.replace(&mut self.selections, "\n"),
        }
    }

    /// Backspace at the start of an item or heading removes its marker in one step.
    fn backspace_on_page(&mut self) {
        let (line, start) = self.line_of_head();
        let hidden = rendered::hidden_prefix(&line);
        let primary = self.selections.primary();
        if primary.is_empty() && hidden > 0 && primary.head == start + hidden {
            self.buffer
                .replace_range(&mut self.selections, start, start + hidden, "");
            self.selections.set_single(Selection::cursor(start));
        } else {
            self.buffer.delete_backward(&mut self.selections);
        }
    }

    /// Tab moves between table cells, and otherwise indents.
    /// The next empty `{}` of a formula being edited, for Tab.
    fn next_slot(&self, head: usize) -> Option<usize> {
        let cache = self.page.borrow();
        let (_, end) = cache.as_ref()?.open?;
        let rope = self.buffer.rope();
        let text: Vec<char> = rope
            .slice(head..end.min(rope.len_chars()))
            .chars()
            .collect();
        let found = text.windows(2).skip(1).position(|w| w == ['{', '}'])?;
        Some(head + found + 2)
    }

    fn tab_on_page(&mut self, area: Rect) {
        let rows = self.page(area);
        let head = self.selections.primary().head;
        if let Some(slot) = self.next_slot(head) {
            self.selections.set_single(Selection::cursor(slot));
            return;
        }
        if let Some(cell) = rendered::next_cell(&rows, head) {
            self.select_cell(area, cell);
            return;
        }
        // Past the last cell comes a new row, as in a sheet.
        if self.selection_in_table(area) {
            self.edit_table(TableEdit::RowBelow);
            let rows = self.page(area);
            let head = self.selections.primary().head;
            if let Some(cell) = rendered::cell_in_row(&rows, head, 0) {
                self.select_cell(area, cell);
            }
            return;
        }
        let (line, start) = self.line_of_head();
        if rendered::hidden_prefix(&line) > 0 {
            self.buffer
                .replace_range(&mut self.selections, start, start, "  ");
            self.selections.set_single(Selection::cursor(head + 2));
        } else {
            self.buffer.type_text(&mut self.selections, "    ");
        }
    }

    /// Whether the caret is in a table the page is showing.
    fn selection_in_table(&self, area: Rect) -> bool {
        let rows = self.page(area);
        let head = self.selections.primary().head;
        rendered::cell_column(&rows, head).is_some() && self.table_at_caret().is_some()
    }

    /// Lands on a cell with what it holds selected, so typing replaces it.
    fn select_cell(&mut self, area: Rect, cell: usize) {
        let rows = self.page(area);
        let (anchor, head) = rendered::cell_range(&rows, cell);
        self.selections.set_single(Selection {
            anchor,
            head,
            goal: None,
        });
    }

    /// Enter in a table: the same column one row down, with a new row past the last.
    fn next_row(&mut self, area: Rect) {
        let rows = self.page(area);
        let head = self.selections.primary().start();
        let column = rendered::cell_column(&rows, head).unwrap_or(0);
        if let Some(cell) = rendered::cell_below(&rows, head) {
            self.select_cell(area, cell);
            return;
        }
        self.edit_table(TableEdit::RowBelow);
        let rows = self.page(area);
        let head = self.selections.primary().head;
        if let Some(cell) = rendered::cell_in_row(&rows, head, column) {
            self.select_cell(area, cell);
        }
    }

    /// Toggles a task checkbox at a click. Returns true if there was one.
    pub fn click_checkbox(&mut self, area: Rect, x: f32, y: u16) -> bool {
        if !self.rendered {
            return false;
        }
        let area = self.text_area(area);
        let rows = self.page(area);
        let row = self.top + y.saturating_sub(area.y) as usize;
        let column = x - (area.x + Self::page_margin(area)) as f32;
        let Some((at, mark)) = rows.get(row).and_then(|r| r.checkbox) else {
            return false;
        };
        if column < at || column >= at + 1.3 {
            return false;
        }
        let checked = self.buffer.rope().char(mark) != ' ';
        let text = if checked { " " } else { "x" };
        self.buffer
            .replace_range(&mut self.selections, mark, mark + 1, text);
        true
    }

    /// True when a click at `x` lands on the scrollbar.
    pub fn on_scrollbar(&self, area: Rect, x: u16) -> bool {
        x >= self.text_area(area).right()
    }

    /// Scrolls so that row `y` of the scrollbar's track matches the document.
    pub fn scroll_to_row(&mut self, area: Rect, y: u16) {
        let lines = if self.rendered {
            self.page(self.text_area(area)).len()
        } else {
            self.buffer.rope().len_lines()
        };
        let row = y.saturating_sub(area.y) as usize;
        let filled = self.map_filled(area, lines);
        // The point clicked comes to the middle of the view.
        let middle = (row * lines / filled).saturating_sub(area.h as usize / 2);
        self.view_rows.set(area.h);
        self.top = middle.min(self.last_top());
    }

    /// Narrow panes keep only the digits they need: every column counts there.
    fn gutter_width(&self, pane_width: u16) -> u16 {
        let digits = self.buffer.rope().len_lines().to_string().len();
        let minimum = if pane_width < NARROW_PANE {
            2
        } else {
            GUTTER_MIN_DIGITS
        };
        (digits.max(minimum) + 2) as u16
    }

    pub fn line_text(&self, line: usize) -> String {
        let text = self.buffer.rope().line(line).to_string();
        text.trim_end_matches(['\n', '\r']).to_string()
    }

    /// Display column of a char position.
    fn column_of(&self, at: usize) -> usize {
        let rope = self.buffer.rope();
        let line = rope.char_to_line(at);
        let start = rope.line_to_char(line);
        let mut column = 0;
        for c in rope.slice(start..at).chars() {
            column += display_width(c, column);
        }
        column
    }

    /// Char position at a screen cell inside `area`, clamped to the text.
    pub fn position_at(&self, area: Rect, fine_x: f32, y: u16) -> usize {
        let x = fine_x as u16;
        let area = self.text_area(area);
        if self.rendered {
            let rows = self.page(area);
            let row = self.top + y.saturating_sub(area.y) as usize;
            let column = (fine_x - (area.x + Self::page_margin(area)) as f32).max(0.0);
            let row = row.min(rows.len().saturating_sub(1));
            // A tall heading's lower half is the spacer under it, and still the heading.
            let above = row
                .checked_sub(1)
                .and_then(|r| rows.get(r))
                .filter(|r| r.tall);
            // So is any part of a picture, which opens it wherever it's clicked.
            let picture = (!rows[row].stop)
                .then(|| {
                    rows[..=row]
                        .iter()
                        .rev()
                        .find(|r| r.stop || r.figure.is_some())
                })
                .flatten()
                .filter(|r| r.figure.is_some());
            let stop = above
                .or(picture)
                .or_else(|| rows[row..].iter().find(|r| r.stop));
            return stop.map_or(self.buffer.rope().len_chars(), |r| r.position_at(column));
        }
        let rope = self.buffer.rope();
        let line = (self.top + (y.saturating_sub(area.y)) as usize).min(rope.len_lines() - 1);
        let target = self.left + x.saturating_sub(area.x + self.gutter_width(area.w)) as usize;
        let start = rope.line_to_char(line);
        let mut column = 0;
        for (i, c) in self.line_text(line).chars().enumerate() {
            let width = display_width(c, column);
            if column + width > target {
                return start + i;
            }
            column += width;
        }
        start + self.line_text(line).chars().count()
    }

    pub fn top(&self) -> usize {
        self.top
    }

    /// The lines or page rows there are to scroll through.
    fn scroll_length(&self) -> usize {
        // A cached page is close enough to bound the scroll; draw corrects any slack.
        let rows = self.page.borrow().as_ref().map(|page| page.rows.len());
        rows.filter(|_| self.rendered)
            .unwrap_or_else(|| self.buffer.rope().len_lines())
    }

    /// The furthest down the view goes: the end of the file at the bottom of the pane.
    fn last_top(&self) -> usize {
        self.scroll_length()
            .saturating_sub(self.view_rows.get().max(1) as usize)
    }

    pub fn scroll_by(&mut self, delta: isize) {
        let last = self.last_top() as isize;
        self.top = (self.top as isize + delta).clamp(0, last) as usize;
    }

    /// What moves when the wheel does: the text, without the minimap beside it or the left
    /// column, where the sheet's rounded corners are.
    pub fn scroll_region(&self, area: Rect) -> Rect {
        let text = self.text_area(area);
        Rect::new(text.x + 1, text.y, text.w.saturating_sub(1), text.h)
    }

    /// Scrolls just enough to show the primary cursor.
    pub fn reveal(&mut self, area: Rect) {
        let area = self.text_area(area);
        if self.rendered {
            let (row, _) = rendered::locate(&self.page(area), self.selections.primary().head);
            let height = area.h.max(1) as usize;
            if row < self.top {
                self.top = row;
            } else if row >= self.top + height {
                self.top = row + 1 - height;
            }
            self.left = 0;
            return;
        }
        let head = self.selections.primary().head;
        let line = self.buffer.rope().char_to_line(head);
        let rows = area.h.max(1) as usize;
        if line < self.top {
            self.top = line;
        } else if line >= self.top + rows {
            self.top = line + 1 - rows;
        }
        let column = self.column_of(head);
        let cols = area.w.saturating_sub(self.gutter_width(area.w)).max(1) as usize;
        if column < self.left {
            self.left = column;
        } else if column >= self.left + cols {
            self.left = column + 1 - cols;
        }
    }

    pub fn run(&mut self, command: Command, area: Rect) {
        let page = area.h.max(2) as usize - 1;
        if self.rendered {
            let text_area = self.text_area(area);
            self.prepare_for_command(command, text_area);
            let handled = match command {
                Command::Move(direction, extend) => self.move_on_page(text_area, direction, extend),
                Command::DeleteBackward if self.tracking => {
                    self.tracked_delete(false);
                    true
                }
                Command::DeleteForward if self.tracking => {
                    self.tracked_delete(true);
                    true
                }
                Command::Newline if self.selection_in_table(text_area) => {
                    self.next_row(text_area);
                    true
                }
                Command::Outdent if self.selection_in_table(text_area) => {
                    let rows = self.page(text_area);
                    let start = self.selections.primary().start();
                    if let Some(cell) = rendered::previous_cell(&rows, start) {
                        self.select_cell(text_area, cell);
                    }
                    true
                }
                Command::Newline => {
                    self.enter_on_page();
                    true
                }
                Command::DeleteBackward => {
                    self.backspace_on_page();
                    true
                }
                Command::Indent => {
                    self.tab_on_page(text_area);
                    true
                }
                _ => false,
            };
            if handled {
                self.reveal(area);
                return;
            }
        }
        match command {
            Command::Move(direction, extend) => {
                let motion = match direction {
                    Direction::Left => Motion::Left,
                    Direction::Right => Motion::Right,
                    Direction::Up => Motion::Up,
                    Direction::Down => Motion::Down,
                    Direction::WordLeft => Motion::WordLeft,
                    Direction::WordRight => Motion::WordRight,
                    Direction::LineStart => Motion::LineStart,
                    Direction::LineColumnZero => Motion::LineColumnZero,
                    Direction::LineEnd => Motion::LineEnd,
                    Direction::Top => Motion::Top,
                    Direction::Bottom => Motion::Bottom,
                    Direction::PageUp => Motion::PageUp(page),
                    Direction::PageDown => Motion::PageDown(page),
                    Direction::NextWordStart => Motion::NextWordStart,
                    Direction::FindChar(c, forward, till) => Motion::FindChar(c, forward, till),
                };
                self.selections
                    .apply_motion(self.buffer.rope(), motion, extend);
            }
            Command::Newline => self.newline(),
            Command::Type(c) => self.type_char(c),
            Command::ToggleComment => self.toggle_comment(),
            Command::MoveLineUp => self.move_line(-1),
            Command::MoveLineDown => self.move_line(1),
            Command::DuplicateLine => self.duplicate_line(),
            Command::DeleteLine => self.delete_line(),
            Command::InsertLineBelow | Command::InsertLineAbove => {
                self.insert_line(command == Command::InsertLineAbove);
            }
            Command::SelectAllMatches => {
                // Next match until no new one comes.
                self.buffer.select_next_match(&mut self.selections);
                if !self.selections.primary().is_empty() {
                    loop {
                        let before = self.selections.len();
                        self.buffer.select_next_match(&mut self.selections);
                        if self.selections.len() == before {
                            break;
                        }
                    }
                }
            }
            Command::AddCursorAbove | Command::AddCursorBelow => {
                let rope = self.buffer.rope();
                let primary = self.selections.primary();
                let line = rope.char_to_line(primary.head);
                let column = primary.head - rope.line_to_char(line);
                let next = if command == Command::AddCursorAbove {
                    line.checked_sub(1)
                } else {
                    Some(line + 1).filter(|l| *l < rope.len_lines())
                };
                if let Some(next) = next {
                    let width = self.line_text(next).chars().count();
                    let at = rope.line_to_char(next) + column.min(width);
                    self.selections.add(Selection::cursor(at));
                }
            }
            Command::Indent => self.buffer.type_text(&mut self.selections, "    "),
            Command::Outdent => self.outdent(),
            Command::DeleteWordLeft => self.delete_to(Motion::WordLeft),
            Command::DeleteWordRight => self.delete_to(Motion::WordRight),
            Command::DeleteToLineStart => self.delete_to(Motion::LineColumnZero),
            Command::DeleteToLineEnd => self.delete_to(Motion::LineEnd),
            Command::DeleteBackward => self.backspace(),
            Command::DeleteForward => self.buffer.delete_forward(&mut self.selections),
            Command::Undo => {
                self.buffer.undo(&mut self.selections);
            }
            Command::Redo => {
                self.buffer.redo(&mut self.selections);
            }
            Command::SelectAll => {
                let len = self.buffer.rope().len_chars();
                self.selections.set_single(Selection {
                    anchor: 0,
                    head: len,
                    goal: None,
                });
            }
            Command::SelectLines(count) => {
                let rope = self.buffer.rope();
                let line = rope.char_to_line(self.selections.primary().head);
                let last = rope.len_lines();
                self.selections.set_single(Selection {
                    anchor: rope.line_to_char(line),
                    head: rope.line_to_char((line + count).min(last)),
                    goal: None,
                });
            }
            Command::SelectNextMatch => self.buffer.select_next_match(&mut self.selections),
            _ => return,
        }
        self.reveal(area);
    }

    /// Edits start from a visible place. Moves start wherever the caret is.
    fn prepare_for_command(&mut self, command: Command, area: Rect) {
        if matches!(
            command,
            Command::Newline | Command::DeleteBackward | Command::DeleteForward | Command::Indent
        ) {
            let primary = self.selections.primary();
            if primary.is_empty() {
                let at = rendered::snap(&self.page(area), primary.head);
                self.selections.set_single(Selection::cursor(at));
            }
        }
    }

    fn outdent(&mut self) {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let start = rope.line_to_char(rope.char_to_line(head));
        let spaces = rope
            .line(rope.char_to_line(head))
            .chars()
            .take(TAB_WIDTH)
            .take_while(|c| *c == ' ')
            .count();
        if spaces > 0 {
            self.buffer
                .replace_range(&mut self.selections, start, start + spaces, "");
        }
    }

    fn char_at(&self, at: usize) -> Option<char> {
        let rope = self.buffer.rope();
        (at < rope.len_chars()).then(|| rope.char(at))
    }

    /// Keeps the line's indent, adds a level after an opening bracket, and puts a closing
    /// bracket on a line of its own.
    fn newline(&mut self) {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = rope.line(rope.char_to_line(head));
        let indent: String = line
            .chars()
            .take_while(|c| matches!(c, ' ' | '\t'))
            .collect();
        let before = head.checked_sub(1).and_then(|at| self.char_at(at));
        let after = self.char_at(head);
        let opens = matches!(before, Some('{' | '(' | '['));
        let closes = matches!(
            (before, after),
            (Some('{'), Some('}')) | (Some('('), Some(')')) | (Some('['), Some(']'))
        );
        let inner = format!("{indent}{}", if opens { INDENT } else { "" });
        let text = if closes {
            format!("\n{inner}\n{indent}")
        } else {
            format!("\n{inner}")
        };
        self.buffer.type_text(&mut self.selections, &text);
        if closes {
            let at = head + 1 + inner.chars().count();
            self.selections.set_single(Selection::cursor(at));
        }
    }

    /// Types a character, closing brackets and quotes, wrapping a selection in them, and
    /// stepping over a closing one that's already there.
    pub fn type_char(&mut self, c: char) {
        if self.tracking && self.rendered {
            self.tracked_type(c.encode_utf8(&mut [0; 4]));
            return;
        }
        let primary = self.selections.primary();
        let close = match c {
            '(' => Some(')'),
            '[' => Some(']'),
            '{' => Some('}'),
            '"' | '`' | '\'' => Some(c),
            _ => None,
        };
        let pairs = !self.rendered && self.selections.len() == 1;
        let after = self.char_at(primary.head);
        let before = primary.head.checked_sub(1).and_then(|at| self.char_at(at));
        if pairs
            && primary.is_empty()
            && after == Some(c)
            && matches!(c, ')' | ']' | '}' | '"' | '`' | '\'')
        {
            self.selections
                .set_single(Selection::cursor(primary.head + 1));
            return;
        }
        let text = c.to_string();
        let Some(close) = close.filter(|_| pairs) else {
            self.buffer.type_text(&mut self.selections, &text);
            return;
        };
        if !primary.is_empty() {
            let (start, end) = (primary.start(), primary.end());
            let inner = self.buffer.rope().slice(start..end).to_string();
            let wrapped = format!("{c}{inner}{close}");
            self.buffer
                .replace_range(&mut self.selections, start, end, &wrapped);
            self.selections.set_single(Selection {
                anchor: start + 1,
                head: end + 1,
                goal: None,
            });
            return;
        }
        // Beside a word, a quote is an apostrophe or a lifetime, and a bracket wraps it later.
        let by_word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
        if by_word(after) || (c == close && by_word(before)) {
            self.buffer.type_text(&mut self.selections, &text);
            return;
        }
        self.buffer
            .type_text(&mut self.selections, &format!("{c}{close}"));
        self.selections
            .set_single(Selection::cursor(primary.head + 1));
    }

    /// Deletes both halves of an empty pair.
    fn backspace(&mut self) {
        let primary = self.selections.primary();
        let pair = primary.head.checked_sub(1).and_then(|at| {
            let open = self.char_at(at)?;
            let close = self.char_at(primary.head)?;
            matches!(
                (open, close),
                ('(', ')') | ('[', ']') | ('{', '}') | ('"', '"') | ('`', '`') | ('\'', '\'')
            )
            .then_some(at)
        });
        match pair.filter(|_| primary.is_empty() && self.selections.len() == 1) {
            Some(at) => {
                self.buffer
                    .replace_range(&mut self.selections, at, at + 2, "");
                self.selections.set_single(Selection::cursor(at));
            }
            None => self.buffer.delete_backward(&mut self.selections),
        }
    }

    /// The whole lines the selection touches, as (first, last, start, end in chars).
    fn selected_lines(&self) -> (usize, usize, usize, usize) {
        let primary = self.selections.primary();
        let rope = self.buffer.rope();
        let first = rope.char_to_line(primary.start());
        let last = rope.char_to_line(primary.end());
        let start = rope.line_to_char(first);
        let end = rope.line_to_char(last) + self.line_text(last).chars().count();
        (first, last, start, end)
    }

    fn toggle_comment(&mut self) {
        let Some(mark) = self.buffer.path().and_then(Registry::line_comment) else {
            return;
        };
        let (first, last, start, end) = self.selected_lines();
        let lines: Vec<String> = (first..=last).map(|line| self.line_text(line)).collect();
        let written = |line: &&String| !line.trim().is_empty();
        let commented = lines
            .iter()
            .filter(written)
            .all(|line| line.trim_start().starts_with(mark));
        let margin = lines
            .iter()
            .filter(written)
            .map(|line| line.len() - line.trim_start().len())
            .min()
            .unwrap_or(0);
        let changed: Vec<String> = lines
            .iter()
            .map(|line| {
                if line.trim().is_empty() {
                    line.clone()
                } else if commented {
                    let at = line.len() - line.trim_start().len();
                    let rest = line[at + mark.len()..]
                        .strip_prefix(' ')
                        .unwrap_or(&line[at + mark.len()..]);
                    format!("{}{rest}", &line[..at])
                } else {
                    format!("{}{mark} {}", &line[..margin], &line[margin..])
                }
            })
            .collect();
        let text = changed.join("\n");
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        self.selections
            .set_single(Selection::cursor(start + text.chars().count()));
    }

    fn move_line(&mut self, by: isize) {
        let (first, last, start, end) = self.selected_lines();
        let rope = self.buffer.rope();
        let count = rope.len_lines();
        let trailing = rope.line(count - 1).len_chars() == 0;
        let lines = count - usize::from(trailing);
        let other = if by < 0 {
            first.checked_sub(1)
        } else {
            (last + 1 < lines).then_some(last + 1)
        };
        let Some(other) = other else {
            return;
        };
        let head = self.selections.primary().head;
        let block = rope.slice(start..end).to_string();
        let neighbour = self.line_text(other);
        let (from, to, text, moved) = if by < 0 {
            let from = rope.line_to_char(other);
            (
                from,
                end,
                format!("{block}\n{neighbour}"),
                from + head - start,
            )
        } else {
            let to = rope.line_to_char(other) + neighbour.chars().count();
            let shift = neighbour.chars().count() + 1;
            (start, to, format!("{neighbour}\n{block}"), head + shift)
        };
        self.buffer
            .replace_range(&mut self.selections, from, to, &text);
        self.selections.set_single(Selection::cursor(moved));
    }

    /// Takes out the lines the selection touches, newline and all.
    fn delete_line(&mut self) {
        let (first, last, start, _) = self.selected_lines();
        let rope = self.buffer.rope();
        let lines = rope.len_lines();
        let end = if last + 1 < lines {
            rope.line_to_char(last + 1)
        } else {
            rope.len_chars()
        };
        // The last line takes the newline before it instead.
        let start = if end == rope.len_chars() && first > 0 && start > 0 {
            start - 1
        } else {
            start
        };
        self.buffer
            .replace_range(&mut self.selections, start, end, "");
        let rope = self.buffer.rope();
        let line = first.min(rope.len_lines().saturating_sub(1));
        self.selections
            .set_single(Selection::cursor(rope.line_to_char(line)));
    }

    /// Opens a line below this one, or above, at its indent, and goes there.
    fn insert_line(&mut self, above: bool) {
        let (first, last, start, end) = self.selected_lines();
        let line = if above { first } else { last };
        let indent: String = self
            .line_text(line)
            .chars()
            .take_while(|c| *c == ' ' || *c == '\t')
            .collect();
        let (at, text) = if above {
            (start, format!("{indent}\n"))
        } else {
            (end, format!("\n{indent}"))
        };
        self.buffer
            .replace_range(&mut self.selections, at, at, &text);
        let caret = if above {
            start + indent.chars().count()
        } else {
            at + text.chars().count()
        };
        self.selections.set_single(Selection::cursor(caret));
    }

    fn duplicate_line(&mut self) {
        let (_, _, start, end) = self.selected_lines();
        let block = self.buffer.rope().slice(start..end).to_string();
        let head = self.selections.primary().head;
        let copy = format!("\n{block}");
        self.buffer
            .replace_range(&mut self.selections, end, end, &copy);
        let at = head + block.chars().count() + 1;
        self.selections.set_single(Selection::cursor(at));
    }

    pub fn go_to_line(&mut self, line: usize, area: Rect) {
        let at = self.buffer.position(line.saturating_sub(1), 0);
        self.selections.set_single(Selection::cursor(at));
        self.reveal(area);
    }

    /// Where the caret is on screen, if it's in view.
    pub fn caret_cell(&self, area: Rect) -> Option<(f32, u16)> {
        self.cell_of(area, self.selections.primary().head)
    }

    /// Where a place in the text is on screen, if it's in view.
    pub fn cell_of(&self, area: Rect, head: usize) -> Option<(f32, u16)> {
        let area = self.text_area(area);
        let (row, x) = if self.rendered {
            let rows = self.page(area);
            let (row, x) = rendered::locate(&rows, head);
            (row, (area.x + Self::page_margin(area)) as f32 + x)
        } else {
            let row = self.buffer.rope().char_to_line(head);
            let column = self.column_of(head).checked_sub(self.left)?;
            let gutter = self.gutter_width(area.w);
            (row, (area.x + gutter) as f32 + column as f32)
        };
        let y = row.checked_sub(self.top)?;
        (y < area.h as usize).then_some((x, area.y + y as u16))
    }

    /// Takes a finished highlight. Returns whether there's something new to draw.
    pub fn collect_highlights(&self) -> bool {
        let Some((revision, spans)) = self.worker.get().and_then(Worker::finished) else {
            return false;
        };
        // It was asked for at this revision's size, or the next answer will correct it.
        if revision == self.buffer.revision() {
            self.spans_bytes.set(self.buffer.rope().len_bytes());
            *self.spans.borrow_mut() = Some((revision, spans));
            // Its bars were drawn without colours.
            *self.minimap.borrow_mut() = None;
            true
        } else {
            false
        }
    }

    /// Deletes from the cursor to where a motion lands, or just the selection if any.
    fn delete_to(&mut self, motion: Motion) {
        let primary = self.selections.primary();
        let (start, end) = if primary.is_empty() {
            let mut moved = self.selections.clone();
            moved.apply_motion(self.buffer.rope(), motion, false);
            let target = moved.primary().head;
            (target.min(primary.head), target.max(primary.head))
        } else {
            (primary.start(), primary.end())
        };
        if self.tracking && self.rendered {
            self.selections.set_single(Selection {
                anchor: start,
                head: end,
                goal: None,
            });
            self.tracked_delete(false);
            return;
        }
        self.buffer
            .replace_range(&mut self.selections, start, end, "");
        self.selections.set_single(Selection::cursor(start));
    }

    fn toggle_inline(&mut self, marker: &str) {
        let primary = self.selections.primary();
        let (start, end) = if primary.is_empty() {
            self.buffer.word_at(primary.head)
        } else {
            (primary.start(), primary.end())
        };
        let size = marker.chars().count();
        let rope = self.buffer.rope();
        let before = start
            .checked_sub(size)
            .filter(|from| rope.slice(*from..start) == marker);
        let after_end = end + size;
        let after = after_end <= rope.len_chars() && rope.slice(end..after_end) == marker;
        let inner = rope.slice(start..end).to_string();
        let (from, to, text, selected) = match before.filter(|_| after) {
            Some(from) => (from, after_end, inner, from),
            None => (start, end, format!("{marker}{inner}{marker}"), start + size),
        };
        let length = end - start;
        self.buffer
            .replace_range(&mut self.selections, from, to, &text);
        self.selections.set_single(Selection {
            anchor: selected,
            head: selected + length,
            goal: None,
        });
    }

    /// The prefix a selected line should get, given the one it has.
    fn next_prefix(format: Format, line: &str) -> (usize, String) {
        let hashes = line.chars().take_while(|c| *c == '#').count();
        let heading = hashes > 0 && line[hashes..].starts_with(' ');
        let simple = |prefix: &str| {
            if line.starts_with(prefix) {
                (prefix.len(), String::new())
            } else {
                (0, prefix.to_string())
            }
        };
        match format {
            Format::Heading if heading && hashes < MAX_HEADING_CYCLE => {
                (hashes + 1, format!("{} ", "#".repeat(hashes + 1)))
            }
            Format::Heading if heading => (hashes + 1, String::new()),
            Format::Heading => (0, "# ".to_string()),
            Format::Level(level) => {
                let drop = if heading { hashes + 1 } else { 0 };
                let add = "#".repeat(level as usize);
                (drop, if level == 0 { add } else { format!("{add} ") })
            }
            Format::Numbered => simple("1. "),
            Format::Bullet => simple("- "),
            Format::Task => simple("- [ ] "),
            Format::PlainText if heading => (hashes + 1, String::new()),
            Format::PlainText => {
                let markers = ["- [ ] ", "- [x] ", "- ", "* ", "> "];
                let found = markers.iter().find(|m| line.starts_with(**m));
                (found.map_or(0, |m| m.len()), String::new())
            }
            _ => simple("> "),
        }
    }

    fn toggle_lines(&mut self, format: Format) {
        let primary = self.selections.primary();
        let rope = self.buffer.rope();
        let first = rope.char_to_line(primary.start());
        let last = rope.char_to_line(primary.end());
        let start = rope.line_to_char(first);
        let end = rope.line_to_char(last) + self.line_text(last).chars().count();
        let mut text = Vec::new();
        for line in first..=last {
            let line = self.line_text(line);
            let (drop, add) = Self::next_prefix(format, &line);
            text.push(format!("{add}{}", &line[drop..]));
        }
        let text = text.join("\n");
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        let at = start + text.chars().count();
        self.selections.set_single(Selection::cursor(at));
    }

    /// Wraps the word or selection in a command, or takes it back out.
    fn toggle_command(&mut self, open: &str) {
        let primary = self.selections.primary();
        let (start, end) = if primary.is_empty() {
            self.buffer.word_at(primary.head)
        } else {
            (primary.start(), primary.end())
        };
        let size = open.chars().count();
        let rope = self.buffer.rope();
        let inside = start >= size
            && rope.slice(start - size..start) == open
            && rope.get_char(end) == Some('}');
        let inner = rope.slice(start..end).to_string();
        let length = end - start;
        let selected = if inside {
            let (from, to) = (start - size, end + 1);
            self.buffer
                .replace_range(&mut self.selections, from, to, &inner);
            from
        } else {
            let text = format!("{open}{inner}}}");
            self.buffer
                .replace_range(&mut self.selections, start, end, &text);
            start + size
        };
        self.selections.set_single(Selection {
            anchor: selected,
            head: selected + length,
            goal: None,
        });
    }

    /// The caret's line and its text, with any section command taken off.
    fn line_as_text(&self) -> (usize, String) {
        let rope = self.buffer.rope();
        let line = rope.char_to_line(self.selections.primary().head);
        let text = self.line_text(line);
        let plain = text
            .split_once('{')
            .filter(|_| text.trim_start().starts_with("\\"))
            .and_then(|(_, rest)| rest.trim_end().strip_suffix('}'))
            .unwrap_or(&text)
            .to_string();
        (line, plain)
    }

    fn set_section(&mut self, level: u8) {
        let (line, plain) = self.line_as_text();
        let start = self.buffer.rope().line_to_char(line);
        let end = start + self.line_text(line).chars().count();
        let text = match level {
            1 => format!("\\section{{{plain}}}"),
            2 => format!("\\subsection{{{plain}}}"),
            3 => format!("\\subsubsection{{{plain}}}"),
            _ => plain,
        };
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        let at = start + text.chars().count();
        self.selections.set_single(Selection::cursor(at));
    }

    /// Puts the selected lines in an environment, each one an `\\item` if it's a list.
    fn wrap_environment(&mut self, name: &str, items: bool) {
        let primary = self.selections.primary();
        let rope = self.buffer.rope();
        let first = rope.char_to_line(primary.start());
        let last = rope.char_to_line(primary.end());
        let start = rope.line_to_char(first);
        let end = rope.line_to_char(last) + self.line_text(last).chars().count();
        let mut text = format!("\\begin{{{name}}}\n");
        for line in first..=last {
            let lead = if items { "  \\item " } else { "  " };
            text.push_str(&format!("{lead}{}\n", self.line_text(line).trim()));
        }
        text.push_str(&format!("\\end{{{name}}}"));
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        let at = start + text.chars().count() - name.len() - 7;
        self.selections.set_single(Selection::cursor(at));
    }

    fn format_latex(&mut self, format: Format) {
        match format {
            Format::Bold => self.toggle_command("\\textbf{"),
            Format::Italic => self.toggle_command("\\emph{"),
            Format::Code => self.toggle_command("\\texttt{"),
            Format::Strikethrough => {
                // `\\sout` is ulem's, which a paper needs to build.
                self.ensure_package("[normalem]{ulem}", "{ulem}");
                self.toggle_command("\\sout{");
            }
            Format::Link => self.make_link("https://"),
            Format::Bullet | Format::Task => self.wrap_environment("itemize", true),
            Format::Numbered => self.wrap_environment("enumerate", true),
            Format::Quote => self.wrap_environment("quote", false),
            Format::CodeBlock => self.wrap_environment("verbatim", false),
            Format::Level(level) => self.set_section(level),
            Format::Heading => self.set_section(1),
            Format::PlainText => self.set_section(0),
            Format::Rule => self.insert_block("\\bigskip\\hrule\\bigskip", 0),
            Format::Table => self.insert_table(3, 3),
        }
    }

    pub fn format(&mut self, format: Format, area: Rect) {
        self.prepare_edit(area);
        if self.dialect() == Dialect::Latex {
            self.format_latex(format);
            return;
        }
        match format {
            Format::Bold => self.toggle_inline("**"),
            Format::Italic => self.toggle_inline("*"),
            Format::Code => self.toggle_inline("`"),
            Format::Strikethrough => self.toggle_inline("~~"),
            Format::CodeBlock => self.fence_lines(),
            Format::Table => self.insert_table(3, 3),
            Format::Rule => self.insert_block("---", 3),
            Format::Link => self.make_link("https://"),
            _ => self.toggle_lines(format),
        }
    }

    /// Makes the word or selection a link to `address`.
    pub fn make_link(&mut self, address: &str) {
        let primary = self.selections.primary();
        let (start, end) = if primary.is_empty() {
            self.buffer.word_at(primary.head)
        } else {
            (primary.start(), primary.end())
        };
        let text = self.buffer.rope().slice(start..end).to_string();
        let link = if self.dialect() == Dialect::Latex {
            format!("\\href{{{address}}}{{{text}}}")
        } else {
            format!("[{text}]({address})")
        };
        self.buffer
            .replace_range(&mut self.selections, start, end, &link);
        let after = start + link.chars().count();
        self.selections.set_single(Selection::cursor(after));
    }

    /// Finds where each comment's quote is, for tinting it.
    pub fn set_quotes(&self, quotes: &[(usize, String)]) {
        let rope = self.buffer.rope();
        let mut ranges = Vec::new();
        for (line, quote) in quotes {
            let index = line.saturating_sub(1);
            if quote.is_empty() || index >= rope.len_lines() {
                continue;
            }
            let text = self.line_text(index);
            if let Some(at) = text.find(quote.as_str()) {
                let start = rope.line_to_char(index) + text[..at].chars().count();
                ranges.push((start, start + quote.chars().count()));
            }
        }
        *self.quoted.borrow_mut() = ranges;
    }

    /// Puts text in a block of its own below this line, with the caret `caret` chars in.
    pub fn insert_block(&mut self, block: &str, caret: usize) {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = rope.char_to_line(head);
        let text = self.line_text(line);
        let at = rope.line_to_char(line) + text.chars().count();
        let gap = if text.trim().is_empty() { "" } else { "\n\n" };
        let insert = format!("{gap}{block}\n");
        self.buffer
            .replace_range(&mut self.selections, at, at, &insert);
        let spot = at + gap.chars().count() + caret;
        self.selections.set_single(Selection::cursor(spot));
    }

    /// Adds an image: a figure with a caption in a paper, a plain image in a note.
    pub fn insert_image(&mut self, path: &str) {
        if self.dialect() == Dialect::Latex {
            let figure = format!(
                "\\begin{{figure}}[h]\n  \\centering\n  \\includegraphics[width=\\linewidth]{{{path}}}\n  \\caption{{}}\n\\end{{figure}}"
            );
            let caret = figure.find("\\caption{}").unwrap_or(0) + "\\caption{".len();
            self.insert_block(&figure, caret);
        } else {
            self.insert_block(&format!("![]({path})"), 2);
        }
    }

    /// Writes this file, through its notebook if it has one.
    pub fn save(&mut self) -> io::Result<()> {
        match &self.notebook {
            Some(notebook) => {
                let written = notebook.write(&self.buffer.text());
                self.buffer.save_as(&written)
            }
            None => self.buffer.save(),
        }
    }

    /// Takes the file back from disk, through its notebook if it has one.
    pub fn reload(&mut self) -> io::Result<()> {
        let notebook = self.notebook.is_some();
        let read = self
            .buffer
            .path()
            .filter(|_| notebook)
            .map(std::fs::read_to_string);
        let Some(text) = read else {
            return self.buffer.reload(&mut self.selections);
        };
        let notebook = Notebook::read(&text?).map_err(io::Error::other)?;
        let page = notebook.page();
        self.notebook = Some(notebook);
        *self.page.borrow_mut() = None;
        self.buffer.reload_as(&mut self.selections, page)
    }

    /// The cell a source line is in, as its marker's line, what it says of itself and its
    /// code. None for a line that isn't in a code cell.
    pub fn code_cell_at(&self, line: usize) -> Option<(usize, Marker, String)> {
        self.notebook.as_ref()?;
        let last = self.buffer.rope().len_lines();
        let top = (0..=line.min(last.saturating_sub(1)))
            .rev()
            .find(|n| marker(&self.line_text(*n)).is_some())?;
        let mark = marker(&self.line_text(top)).filter(|m| m.code)?;
        let lines = (top + 1..last).map(|n| self.line_text(n));
        let lines: Vec<String> = lines.take_while(|text| marker(text).is_none()).collect();
        let open = lines.iter().position(|l| l.starts_with("```"))?;
        let close = lines.iter().rposition(|l| l.trim() == "```")?;
        (close > open).then(|| (top, mark, lines[open + 1..close].join("\n")))
    }

    /// Every code cell, top to bottom, as its number and code.
    pub fn code_cells(&self) -> Vec<(Marker, String)> {
        let lines = 0..self.buffer.rope().len_lines();
        let tops = lines.filter(|n| marker(&self.line_text(*n)).is_some_and(|m| m.code));
        let cells = tops.filter_map(|n| self.code_cell_at(n));
        cells.map(|(_, mark, code)| (mark, code)).collect()
    }

    /// Writes new cells into the file, so they have numbers of their own to run as.
    pub fn number_new_cells(&mut self) -> io::Result<()> {
        let head = self.selections.primary().head;
        self.save()?;
        self.reload()?;
        self.selections.set_single(Selection::cursor(head));
        Ok(())
    }

    /// Adds a cell after the one the caret is in, with the caret ready in it.
    pub fn insert_cell(&mut self, code: bool) {
        let language = self
            .notebook
            .as_ref()
            .map_or("python", |n| n.language.as_str());
        let cell = if code {
            cellix_doc::notebook::new_code_cell(language)
        } else {
            cellix_doc::notebook::new_text_cell()
        };
        let rope = self.buffer.rope();
        let line = rope.char_to_line(self.selections.primary().head);
        let next = (line + 1..rope.len_lines()).find(|n| marker(&self.line_text(*n)).is_some());
        let at = next.map_or(rope.len_chars(), |n| rope.line_to_char(n));
        let caret = if code {
            cell.find("\n\n").map_or(0, |gap| gap + 1)
        } else {
            cell.chars().count()
        };
        let lead = if at == rope.len_chars() && !self.buffer.text().ends_with("\n\n") {
            "\n"
        } else {
            ""
        };
        let block = format!("{lead}{cell}\n\n");
        self.buffer
            .replace_range(&mut self.selections, at, at, &block);
        let spot = at + lead.chars().count() + cell[..caret].chars().count();
        self.selections.set_single(Selection::cursor(spot));
    }

    /// Moves to the first line of the next code cell, if there is one.
    pub fn go_to_next_cell(&mut self, area: Rect) {
        let rope = self.buffer.rope();
        let line = rope.char_to_line(self.selections.primary().head);
        let next = (line + 1..rope.len_lines())
            .find(|n| marker(&self.line_text(*n)).is_some_and(|m| m.code));
        if let Some(next) = next {
            self.go_to_line(next + 3, area);
        }
    }

    /// What's wrong with this revision of the text.
    fn current_issues(&self) -> &[Issue] {
        if self.issues.0 == self.buffer.revision() {
            &self.issues.1
        } else {
            &[]
        }
    }

    /// What this document is written in, for the prose checker.
    pub fn prose_source(&self) -> Source {
        match self.dialect() {
            Dialect::Latex => Source::Latex,
            _ => Source::Markdown,
        }
    }

    /// The spelling or grammar issue at the caret.
    pub fn issue_at_caret(&self) -> Option<&Issue> {
        let head = self.selections.primary().head;
        let holds = |issue: &&Issue| issue.start <= head && head <= issue.end;
        self.current_issues().iter().find(holds)
    }

    /// The words of a range of the document.
    pub fn words_in(&self, start: usize, end: usize) -> String {
        self.buffer.rope().slice(start..end).to_string()
    }

    /// Puts a suggested word in place, and forgets the issue it settles.
    pub fn apply_fix(&mut self, start: usize, end: usize, text: &str) {
        self.buffer
            .replace_range(&mut self.selections, start, end, text);
        let at = start + text.chars().count();
        self.selections.set_single(Selection::cursor(at));
    }

    /// Takes a word off the list of what's wrong, wherever it stands.
    pub fn forget_issues(&mut self, word: &str) {
        let wanted = word.to_lowercase();
        let rope = self.buffer.rope().clone();
        self.issues.1.retain(|issue| {
            rope.slice(issue.start..issue.end)
                .to_string()
                .to_lowercase()
                != wanted
        });
    }

    fn syntax(&self) -> Syntax {
        match self.dialect() {
            Dialect::Latex => Syntax::Latex,
            _ => Syntax::Critic,
        }
    }

    fn changes(&self) -> Vec<Change> {
        changes::find(&self.buffer.text(), self.syntax())
    }

    /// The change the caret is in or right after.
    pub fn change_at_caret(&self) -> Option<Change> {
        let head = self.selections.primary().head;
        let holds = |c: &Change| c.start <= head && head <= c.end;
        self.changes().into_iter().find(holds)
    }

    /// Keeps or drops the change at the caret.
    pub fn settle_change(&mut self, accept: bool) {
        let Some(change) = self.change_at_caret() else {
            return;
        };
        let kept = if accept { &change.new } else { &change.old };
        self.buffer
            .replace_range(&mut self.selections, change.start, change.end, kept);
        let at = change.start + kept.chars().count();
        self.selections.set_single(Selection::cursor(at));
    }

    /// Keeps or drops every change, and says how many there were.
    pub fn settle_all_changes(&mut self, accept: bool) -> usize {
        let text = self.buffer.text();
        let count = changes::find(&text, self.syntax()).len();
        if count > 0 {
            let settled = changes::settle_all(&text, self.syntax(), accept);
            let total = self.buffer.rope().len_chars();
            self.buffer
                .replace_range(&mut self.selections, 0, total, &settled);
            let head = self.selections.primary().head.min(settled.chars().count());
            self.selections.set_single(Selection::cursor(head));
        }
        count
    }

    /// Adds `\\usepackage<what>` before `\\begin{document}`, unless `known` is already used.
    fn ensure_package(&mut self, what: &str, known: &str) {
        let text = self.buffer.text();
        if text.contains(known) {
            return;
        }
        let Some(at) = text.find("\\begin{document}") else {
            return;
        };
        let at = text[..at].chars().count();
        let mut selections = self.selections.clone();
        let line = format!("\\usepackage{what}\n");
        self.buffer.replace_range(&mut selections, at, at, &line);
        let length = line.chars().count();
        // The caret stays on the words it was on.
        let shifted: Vec<Selection> = self
            .selections
            .iter()
            .map(|s| Selection {
                anchor: s.anchor + length,
                head: s.head + length,
                goal: s.goal,
            })
            .collect();
        if let Some(first) = shifted.first() {
            self.selections.set_single(*first);
            for s in &shifted[1..] {
                self.selections.add(*s);
            }
        }
    }

    /// Turns tracking on or off. A paper needs the package that prints its marks.
    pub fn toggle_tracking(&mut self) -> bool {
        self.tracking = !self.tracking;
        let text = self.buffer.text();
        if self.tracking
            && self.dialect() == Dialect::Latex
            && !text.contains("{changes}")
            && let Some(at) = text.find("\\begin{document}")
        {
            let at = text[..at].chars().count();
            let mut selections = self.selections.clone();
            self.buffer
                .replace_range(&mut selections, at, at, "\\usepackage{changes}\n");
        }
        self.tracking
    }

    /// Where typing goes: a caret inside something crossed out stands after it.
    fn tracked_head(&self, changes: &[Change]) -> usize {
        let head = self.selections.primary().head;
        let deleted = changes
            .iter()
            .find(|c| c.kind == Kind::Delete && c.start < head && head < c.end);
        deleted.map_or(head, |c| c.end)
    }

    /// Takes out what's selected, as a suggestion if changes are being tracked.
    pub fn cut_selection(&mut self) {
        if self.tracking && self.rendered {
            self.tracked_delete(false);
        } else {
            self.buffer.replace(&mut self.selections, "");
        }
    }

    /// Pastes as a suggestion.
    pub fn tracked_paste(&mut self, text: &str) {
        self.tracked_type(text);
    }

    /// Adds text as a suggestion, joining the one the caret is at the end of.
    fn tracked_type(&mut self, text: &str) {
        if !self.selections.primary().is_empty() {
            self.tracked_delete(false);
            let changes = self.changes();
            let head = self.selections.primary().head;
            if let Some(change) = changes.iter().find(|c| c.start == head) {
                self.selections.set_single(Selection::cursor(change.end));
            }
        }
        let changes = self.changes();
        let head = self.tracked_head(&changes);
        let (open, close) = self.syntax().insertion();
        let closing = close.chars().count();
        let joins = changes
            .iter()
            .find(|c| c.kind == Kind::Insert && c.start < head && head <= c.end);
        let (at, typed) = match joins {
            Some(change) => (head.min(change.end - closing), text.to_string()),
            None => (head, format!("{open}{text}{close}")),
        };
        self.buffer
            .replace_range(&mut self.selections, at, at, &typed);
        let caret = match joins {
            Some(_) => at + text.chars().count(),
            None => at + open.chars().count() + text.chars().count(),
        };
        self.selections.set_single(Selection::cursor(caret));
    }

    /// Crosses out what's selected or next to the caret. Words the suggestion added simply
    /// go, since nobody has seen them yet.
    fn tracked_delete(&mut self, forward: bool) {
        let primary = self.selections.primary();
        let changes = self.changes();
        let (open, close) = self.syntax().deletion();
        if !primary.is_empty() {
            let text = self
                .buffer
                .rope()
                .slice(primary.start()..primary.end())
                .to_string();
            let lines: Vec<String> = text
                .split('\n')
                .map(|line| {
                    if line.is_empty() {
                        String::new()
                    } else {
                        format!("{open}{line}{close}")
                    }
                })
                .collect();
            let start = primary.start();
            self.buffer.replace_range(
                &mut self.selections,
                start,
                primary.end(),
                &lines.join("\n"),
            );
            self.selections.set_single(Selection::cursor(start));
            return;
        }
        let head = self.selections.primary().head;
        let total = self.buffer.rope().len_chars();
        // Step over what's already crossed out, as the page shows it as gone.
        let settled = changes.iter().find(|c| {
            c.kind == Kind::Delete
                && if forward {
                    c.start <= head && head < c.end
                } else {
                    c.start < head && head <= c.end
                }
        });
        let head = settled.map_or(head, |c| if forward { c.end } else { c.start });
        let at = if forward {
            (head < total).then_some(head)
        } else {
            head.checked_sub(1)
        };
        let Some(at) = at else {
            return;
        };
        let (added_open, added_close) = self.syntax().insertion();
        let added = changes.iter().find(|c| {
            let inner =
                (c.start + added_open.chars().count())..(c.end - added_close.chars().count());
            c.kind == Kind::Insert && (inner.contains(&at) || (!forward && head == c.end))
        });
        if let Some(change) = added {
            // The last of a suggestion takes its markers with it.
            if change.new.chars().count() <= 1 {
                self.buffer
                    .replace_range(&mut self.selections, change.start, change.end, "");
                self.selections.set_single(Selection::cursor(change.start));
                return;
            }
            let inner_end = change.end - added_close.chars().count();
            let at = if head == change.end {
                inner_end - 1
            } else {
                at
            };
            self.buffer
                .replace_range(&mut self.selections, at, at + 1, "");
            self.selections.set_single(Selection::cursor(at));
            return;
        }
        let Some(gone) = self.char_at(at) else {
            return;
        };
        if gone == '\n' {
            self.buffer
                .replace_range(&mut self.selections, at, at + 1, "");
            self.selections.set_single(Selection::cursor(at));
            return;
        }
        // Next to a crossing out, it joins that one.
        let opening = open.chars().count();
        if let (false, Some(change)) = (
            forward,
            changes
                .iter()
                .find(|c| c.kind == Kind::Delete && c.start == head),
        ) {
            let joined = format!("{open}{gone}");
            self.buffer
                .replace_range(&mut self.selections, at, change.start + opening, &joined);
            self.selections.set_single(Selection::cursor(at));
            return;
        }
        let crossed = format!("{open}{gone}{close}");
        self.buffer
            .replace_range(&mut self.selections, at, at + 1, &crossed);
        let caret = if forward {
            at + crossed.chars().count()
        } else {
            at
        };
        self.selections.set_single(Selection::cursor(caret));
    }

    /// The line that names the image the caret is on. A paper's figure counts as a whole.
    fn image_line_at_caret(&self) -> Option<usize> {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = rope.char_to_line(head);
        if self.dialect() == Dialect::Markdown {
            return cellix_doc::figure::image_line(&self.line_text(line)).map(|_| line);
        }
        let names = |n: &usize| self.line_text(*n).contains("\\includegraphics");
        if names(&line) {
            return Some(line);
        }
        let opens = |n: &usize| self.line_text(*n).contains("\\begin{figure");
        let closes = |n: &usize| self.line_text(*n).contains("\\end{figure");
        let first = (0..=line).rev().find(opens)?;
        let last = (line..rope.len_lines()).find(closes)?;
        (first..=last).find(names)
    }

    pub fn image_at_caret(&self) -> bool {
        self.image_line_at_caret().is_some()
    }

    /// Puts a new line in place of the image's, leaving the caret where the line starts so
    /// the picture shows again.
    fn rewrite_image(&mut self, line: usize, text: &str) {
        let start = self.buffer.rope().line_to_char(line);
        let end = start + self.line_text(line).chars().count();
        self.buffer
            .replace_range(&mut self.selections, start, end, text);
        self.selections.set_single(Selection::cursor(start));
    }

    /// Sets how much of the page the image at the caret takes, in percent.
    pub fn set_image_width(&mut self, percent: u32) {
        let Some(line) = self.image_line_at_caret() else {
            return;
        };
        let text = self.line_text(line);
        let sized = if self.dialect() == Dialect::Latex {
            cellix_doc::figure::set_graphics_width(&text, percent)
        } else {
            cellix_doc::figure::set_width(&text, percent)
        };
        if let Some(sized) = sized {
            self.rewrite_image(line, &sized);
        }
    }

    /// Shows another file in the image's place, keeping its words and size.
    pub fn replace_image(&mut self, path: &str) {
        let Some(line) = self.image_line_at_caret() else {
            return;
        };
        let text = self.line_text(line);
        let replaced = if self.dialect() == Dialect::Latex {
            cellix_doc::figure::set_graphics_path(&text, path)
        } else {
            cellix_doc::figure::set_path(&text, path)
        };
        if let Some(replaced) = replaced {
            self.rewrite_image(line, &replaced);
        }
    }

    /// Takes the image out, with the figure around it in a paper.
    pub fn remove_image(&mut self) {
        let Some(line) = self.image_line_at_caret() else {
            return;
        };
        let rope = self.buffer.rope();
        let (mut first, mut last) = (line, line);
        if self.dialect() == Dialect::Latex {
            let opens = |n: &usize| self.line_text(*n).contains("\\begin{figure");
            let closes = |n: &usize| self.line_text(*n).contains("\\end{figure");
            if let (Some(a), Some(b)) = (
                (0..=line).rev().find(opens),
                (line..rope.len_lines()).find(closes),
            ) {
                (first, last) = (a, b);
            }
        }
        let start = rope.line_to_char(first);
        let end = rope.line_to_char((last + 1).min(rope.len_lines() - 1));
        let end = end.max(start + self.line_text(last).chars().count());
        self.buffer
            .replace_range(&mut self.selections, start, end, "");
        self.selections.set_single(Selection::cursor(start));
    }

    /// Adds a diagram below this line, with the caret in its source to go on writing.
    pub fn insert_diagram(&mut self, language: &str, source: &str) {
        let block = format!("```{language}\n{source}\n```");
        self.insert_block(&block, language.chars().count() + 4);
    }

    /// Types text where the caret is.
    pub fn insert_text(&mut self, text: &str) {
        self.buffer.replace(&mut self.selections, text);
    }

    /// Whether the caret is inside a formula showing as source.
    pub fn in_formula(&self) -> bool {
        self.page
            .borrow()
            .as_ref()
            .is_some_and(|p| p.open.is_some())
    }

    /// Inserts a symbol or template. Inside a formula it goes in where the caret is, and
    /// anywhere else it starts a new formula.
    pub fn insert_math(&mut self, symbol: &Symbol) {
        let display = if self.dialect() == Dialect::Latex {
            ("\\begin{equation}\n", "\n\\end{equation}")
        } else {
            ("$$\n", "\n$$")
        };
        let (open, close, block) = match (self.in_formula(), symbol.block) {
            (true, _) => ("", "", false),
            (false, true) => (display.0, display.1, true),
            (false, false) => ("$", "$", false),
        };
        let chars = symbol.text.chars().count();
        let caret = symbol.caret.min(chars) + open.chars().count();
        // What's selected goes in the template's first slot, rather than being replaced.
        let selected = self.selected_text().unwrap_or_default();
        let slot = symbol.caret < chars && !selected.is_empty();
        let body = if slot {
            let at: String = symbol.text.chars().take(symbol.caret).collect();
            let rest: String = symbol.text.chars().skip(symbol.caret).collect();
            format!("{at}{selected}{rest}")
        } else {
            symbol.text.to_string()
        };
        let text = format!("{open}{body}{close}");
        if block {
            self.insert_block(&text, caret);
            return;
        }
        let primary = self.selections.primary();
        let (start, end) = (primary.start(), primary.end());
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        self.selections.set_single(Selection::cursor(start + caret));
    }

    /// The `tabular` the caret is in, read the same way as a Markdown table.
    fn tabular_at_caret(&self) -> Option<(usize, usize, usize, usize)> {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = rope.char_to_line(head);
        let first = (0..=line)
            .rev()
            .find(|n| self.line_text(*n).contains("\\begin{tabular}"))?;
        let last =
            (line..rope.len_lines()).find(|n| self.line_text(*n).contains("\\end{tabular}"))?;
        let row = (first..line)
            .filter(|n| self.line_text(*n).contains("\\\\"))
            .count();
        let before: String = self
            .line_text(line)
            .chars()
            .take(head - rope.line_to_char(line))
            .collect();
        Some((first, last, row, before.matches('&').count()))
    }

    /// The table the caret is in, as its first and last lines and the caret's row and
    /// column, with the header as row zero and the rule left out.
    pub fn table_at_caret(&self) -> Option<(usize, usize, usize, usize)> {
        if self.dialect() == Dialect::Latex {
            return self.tabular_at_caret();
        }
        if let Dialect::Data(separator) = self.dialect() {
            let head = self.selections.primary().head;
            let rope = self.buffer.rope();
            let line = rope.char_to_line(head);
            let last = (0..rope.len_lines())
                .rev()
                .find(|n| !self.line_text(*n).is_empty())
                .unwrap_or(0);
            let before = rope.slice(rope.line_to_char(line)..head).to_string();
            return Some((
                0,
                last,
                line,
                cellix_doc::table::field_of(&before, separator),
            ));
        }
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = rope.char_to_line(head);
        let has_pipe = |n: usize| n < rope.len_lines() && self.line_text(n).contains('|');
        if !has_pipe(line) {
            return None;
        }
        let first = (0..=line)
            .rev()
            .take_while(|n| has_pipe(*n))
            .last()
            .unwrap_or(line);
        let last = (line..rope.len_lines())
            .take_while(|n| has_pipe(*n))
            .last()
            .unwrap_or(line);
        let rule = self.line_text(first + 1);
        let is_rule = |c: char| "|-: ".contains(c);
        if last == first || !rule.contains('-') || !rule.chars().all(is_rule) {
            return None;
        }
        let column = head - rope.line_to_char(line);
        let before: String = self.line_text(line).chars().take(column).collect();
        let pipes = before.matches('|').count().saturating_sub(1);
        let row = match line - first {
            0 => 0,
            1 => 1,
            below => below - 1,
        };
        Some((first, last, row, pipes))
    }

    /// Changes the table the caret is in, and leaves the caret in the cell that matters.
    pub fn edit_table(&mut self, edit: TableEdit) {
        let Some((first, last, row, column)) = self.table_at_caret() else {
            return;
        };
        let rope = self.buffer.rope();
        let start = rope.line_to_char(first);
        let end = rope.line_to_char(last) + self.line_text(last).chars().count();
        let text = rope.slice(start..end).to_string();
        if let Dialect::Data(separator) = self.dialect() {
            if let Some((table, at)) =
                cellix_doc::table::edit_rows(&text, separator, row, column, edit)
            {
                self.buffer
                    .replace_range(&mut self.selections, start, end, &table);
                self.selections.set_single(Selection::cursor(start + at));
            }
            return;
        }
        if self.dialect() == Dialect::Latex {
            let table = cellix_doc::latex::edit_tabular(&text, row, column, edit);
            let table = table.unwrap_or_default();
            self.buffer
                .replace_range(&mut self.selections, start, end, &table);
            let row = row + usize::from(edit == TableEdit::RowBelow);
            let column = column + usize::from(edit == TableEdit::ColumnRight);
            let at = cellix_doc::latex::tabular_cell_offset(&table, row, column);
            self.selections.set_single(Selection::cursor(start + at));
            return;
        }
        match cellix_doc::table::apply(&text, row, column, edit) {
            Some((table, row, column)) => {
                self.buffer
                    .replace_range(&mut self.selections, start, end, &table);
                let at = start + cellix_doc::table::cell_offset(&table, row, column);
                self.selections.set_single(Selection::cursor(at));
            }
            None => {
                // Whatever's after the table closes up behind it.
                let total = self.buffer.rope().len_chars();
                self.buffer
                    .replace_range(&mut self.selections, start, (end + 1).min(total), "");
                self.selections.set_single(Selection::cursor(start));
            }
        }
    }

    /// What kind of paragraph the caret is in, and which formats it's already in.
    pub fn caret_formats(&self) -> (&'static str, Vec<Format>) {
        let head = self.selections.primary().head;
        let rope = self.buffer.rope();
        let line = self.line_text(rope.char_to_line(head));
        let hashes = line.chars().take_while(|c| *c == '#').count();
        let trimmed = line.trim_start();
        let digits = trimmed.chars().take_while(char::is_ascii_digit).count();
        let mut active = Vec::new();
        if trimmed.starts_with("- [") {
            active.push(Format::Task);
        } else if trimmed.starts_with("- ") || trimmed.starts_with("* ") {
            active.push(Format::Bullet);
        } else if digits > 0 && trimmed[digits..].starts_with(". ") {
            active.push(Format::Numbered);
        } else if trimmed.starts_with("> ") {
            active.push(Format::Quote);
        }
        let cache = self.page.borrow();
        let rows = cache.as_ref().map(|p| p.rows.clone());
        let at = rows.iter().flat_map(|r| r.iter()).find_map(|row| {
            row.glyphs
                .iter()
                .find(|g| g.at == Some(head) || g.at.map(|a| a + 1) == Some(head))
        });
        if let Some(glyph) = at {
            if glyph.font.bold && hashes == 0 {
                active.push(Format::Bold);
            }
            if glyph.font.italic {
                active.push(Format::Italic);
            }
            if glyph.tone == Tone::Code {
                active.push(Format::Code);
            }
            if glyph.tone == Tone::Link {
                active.push(Format::Link);
            }
        }
        let style = match hashes {
            1 => "Heading 1",
            2 => "Heading 2",
            3 => "Heading 3",
            4 => "Heading 4",
            5 => "Heading 5",
            6 => "Heading 6",
            _ => "Text",
        };
        (style, active)
    }

    /// Puts the selected lines in a fenced block, with the caret on its first line.
    fn fence_lines(&mut self) {
        let primary = self.selections.primary();
        let rope = self.buffer.rope();
        let first = rope.char_to_line(primary.start());
        let last = rope.char_to_line(primary.end());
        let start = rope.line_to_char(first);
        let end = rope.line_to_char(last) + self.line_text(last).chars().count();
        let inner = rope.slice(start..end).to_string();
        let text = format!("```\n{inner}\n```");
        self.buffer
            .replace_range(&mut self.selections, start, end, &text);
        self.selections.set_single(Selection::cursor(start + 4));
    }

    /// Adds a new table below this line, with its first heading selected to type over.
    pub fn insert_table(&mut self, rows: usize, columns: usize) {
        if self.dialect() == Dialect::Latex {
            let table = cellix_doc::latex::new_table(rows, columns);
            let first = table.find("Column 1").unwrap_or(0);
            self.insert_block(&table, first);
            return;
        }
        let table = cellix_doc::table::new_table(rows, columns);
        self.insert_block(&table, 2);
        let head = self.selections.primary().head;
        self.selections.set_single(Selection {
            anchor: head,
            head: head + "Column 1".len(),
            goal: None,
        });
    }

    /// Selects the word at a place, as a double click does.
    pub fn select_word_at(&mut self, at: usize) {
        let (start, end) = self.buffer.word_at(at);
        self.selections.set_single(Selection {
            anchor: start,
            head: end,
            goal: None,
        });
    }

    /// Selects the whole line at a place, as a triple click does.
    pub fn select_line_at(&mut self, at: usize) {
        let rope = self.buffer.rope();
        let line = rope.char_to_line(at);
        let start = rope.line_to_char(line);
        let end = if line + 1 < rope.len_lines() {
            rope.line_to_char(line + 1)
        } else {
            rope.len_chars()
        };
        self.selections.set_single(Selection {
            anchor: start,
            head: end,
            goal: None,
        });
    }

    /// Whether this file has a page to show, whichever view it's in.
    pub fn has_page(&self) -> bool {
        self.buffer.path().is_some_and(|p| Dialect::of(p).is_some())
    }

    pub fn selected_text(&self) -> Option<String> {
        let rope = self.buffer.rope();
        let parts: Vec<String> = self
            .selections
            .iter()
            .filter(|s| !s.is_empty())
            .map(|s| rope.slice(s.start()..s.end()).to_string())
            .collect();
        (!parts.is_empty()).then(|| parts.join("\n"))
    }

    pub fn draw(
        &self,
        grid: &mut Grid,
        area: Rect,
        theme: &Theme,
        focused: bool,
        registry: &Registry,
        marks: &Marks,
    ) {
        let full = area;
        let area = self.text_area(full);
        self.view_rows.set(area.h);
        self.view_width.set(area.w);
        let dark = !theme.is_light();
        if self.dark.replace(dark) != dark {
            *self.page.borrow_mut() = None;
            *self.library.borrow_mut() = Library::default();
        }
        if self.rendered {
            self.draw_page(grid, area, theme, focused, marks);
            if self.shows_minimap(full) {
                self.draw_minimap(grid, full, theme);
            } else {
                let track = Rect::new(area.right(), area.y, 1, area.h);
                self.draw_scrollbar(grid, track, self.page(area).len(), theme);
            }
            return;
        }
        let lines = self.buffer.rope().len_lines();
        let track = Rect::new(area.right(), area.y, 1, area.h);
        if !self.shows_minimap(full) {
            self.draw_scrollbar(grid, track, lines, theme);
        }
        grid.fill(area, theme.text);
        let gutter = self.gutter_width(area.w);
        let rope = self.buffer.rope();
        let current = rope.char_to_line(self.selections.primary().head);
        for row in 0..area.h {
            let line = self.top + row as usize;
            if line >= rope.len_lines() {
                break;
            }
            let y = area.y + row;
            let active = focused && line == current;
            let bg = if active { theme.line } else { theme.text.bg };
            let text_style = cellix_render::Style { bg, ..theme.text };
            grid.fill(Rect::new(area.x, y, area.w, 1), text_style);
            let number_fg = if marks.errors.contains(&(line + 1)) {
                theme.error
            } else if active {
                theme.number_active
            } else {
                theme.gutter.fg
            };
            let gutter_style = cellix_render::Style {
                fg: number_fg,
                bg,
                ..theme.gutter
            };
            let number = format!("{:>w$} ", line + 1, w = gutter as usize - 1);
            grid.put_str(area.x, y, &number, gutter_style, area.x + gutter);
            if marks.comments.contains(&(line + 1)) {
                let mark = cellix_render::Style {
                    fg: theme.accent,
                    bg,
                    ..theme.gutter
                };
                grid.put_str(area.x, y, "◆", mark, area.x + gutter);
            }

            let mut column = 0;
            let mut text = String::new();
            for c in self.line_text(line).chars() {
                let width = display_width(c, column);
                if column + width > self.left {
                    if c == '\t' {
                        text.extend(std::iter::repeat_n(' ', width));
                    } else {
                        text.push(c);
                    }
                }
                column += width;
            }
            grid.put_str(area.x + gutter, y, &text, text_style, area.right());
            let guide = cellix_render::Style {
                fg: theme.guide,
                bg,
                ..theme.text
            };
            let indent = text.chars().take_while(|c| *c == ' ').count();
            for at in (0..indent).step_by(TAB_WIDTH) {
                let x = area.x + gutter + at as u16;
                if x < area.right() {
                    grid.put_str(x, y, "│", guide, area.right());
                }
            }
        }
        self.draw_highlights(grid, area, gutter, theme, registry);
        if self.shows_minimap(full) {
            self.draw_minimap(grid, full, theme);
        }
        for (line, change) in &self.line_changes().1 {
            if *line >= self.top && *line < self.top + area.h as usize {
                let y = area.y + (*line - self.top) as u16;
                self.draw_change(grid, area.x as f32 + gutter as f32 - 0.7, y, *change, theme);
            }
        }
        for (start, end) in self.found.iter().copied() {
            let s = Selection {
                anchor: start,
                head: end,
                goal: None,
            };
            self.draw_range(grid, area, gutter, &s, theme.found);
        }
        for s in self.selections.iter().filter(|s| !s.is_empty()) {
            self.draw_range(grid, area, gutter, s, theme.selection);
        }
        if focused {
            let head = self.selections.primary().head;
            let line = rope.char_to_line(head);
            let column = self.column_of(head);
            if line >= self.top && column >= self.left {
                let x = area.x as usize + gutter as usize + column - self.left;
                let y = area.y as usize + line - self.top;
                if x < area.right() as usize && y < area.bottom() as usize {
                    grid.cursor = Some((x as u16, y as u16));
                }
            }
        }
    }

    fn draw_scrollbar(&self, grid: &mut Grid, track: Rect, lines: usize, theme: &Theme) {
        grid.fill(track, theme.text);
        let rows = track.h as usize;
        if lines <= rows {
            return;
        }
        let height = (rows * rows / lines).max(1);
        let top = self.top * rows / lines;
        // A slim rounded thumb on the pixel tiers, and a block of colour on cells.
        let cells = Rect::new(track.x, track.y + top as u16, 1, height as u16);
        let thumb = cellix_render::Style {
            fg: theme.scrollbar,
            painted: true,
            ..theme.text
        };
        for y in cells.y..cells.bottom() {
            grid.put_str(cells.x, y, "▐", thumb, cells.right());
        }
        let bounds =
            cellix_render::Bounds::cells(cells.x as f32 + 0.3, cells.y as f32, 0.5, cells.h as f32);
        grid.panel(bounds, 20, Some(theme.scrollbar), None);
    }

    /// Backgrounds of code blocks and tables, drawn before the text on top of them.
    fn draw_page_blocks(&self, grid: &mut Grid, area: Rect, rows: &[Row], theme: &Theme) {
        let left = (area.x + Self::page_margin(area)) as f32;
        let visible = self.top..(self.top + area.h as usize).min(rows.len());
        let y_of = |index: usize| area.y as f32 + (index - self.top) as f32;
        let mut index = visible.start;
        while index < visible.end {
            let row = &rows[index];
            let group =
                |r: &Row| (row.shaded && r.shaded) || (row.table.is_some() && r.table.is_some());
            if !group(row) {
                index += 1;
                continue;
            }
            let end = (index..visible.end)
                .find(|i| !group(&rows[*i]))
                .unwrap_or(visible.end);
            let (top, height) = (y_of(index), (end - index) as f32);
            if row.shaded {
                let width = area.right() as f32 - left - 1.0;
                let bounds = Bounds::cells(left, top - 0.08, width, height + 0.2);
                grid.panel(bounds, 22, Some(theme.code_bg), Some(theme.border));
            } else if let Some(table) = &row.table {
                let width = table.columns.last().copied().unwrap_or(0.0);
                let bounds = Bounds::cells(left, top + 0.02, width, height - 0.04);
                if table.header {
                    let head = Bounds::cells(left, top + 0.02, width, 1.0);
                    grid.panel(head, 14, Some(theme.code_bg), None);
                }
                for at in index + 1..end {
                    let line = Bounds::cells(left, y_of(at), width, 0.0);
                    grid.hairline(line, theme.popup_border);
                }
                let inner = table.columns.len().saturating_sub(2);
                for x in table.columns.iter().skip(1).take(inner) {
                    let line = Bounds::cells(left + x, top + 0.02, 0.0, height - 0.04);
                    grid.hairline(line, theme.popup_border);
                }
                grid.panel(bounds, 14, None, Some(theme.popup_border));
            }
            index = end;
        }
    }

    fn draw_page(&self, grid: &mut Grid, area: Rect, theme: &Theme, focused: bool, marks: &Marks) {
        grid.fill(area, theme.text);
        let rows = self.page(area);
        let proportional = !self.measure.in_cells();
        let left = area.x + Self::page_margin(area);
        let primary = self.selections.primary();
        let (caret_row, caret_x) = rendered::locate(&rows, primary.head);
        if proportional {
            self.draw_page_blocks(grid, area, &rows, theme);
            self.draw_figures(grid, area, &rows, theme);
        }
        let changes = self.line_changes();
        for (index, row) in rows.iter().enumerate().skip(self.top) {
            let y = area.y + (index - self.top) as u16;
            if y >= area.bottom() {
                break;
            }
            let bg = if row.shaded && !proportional {
                theme.code_bg
            } else {
                theme.text.bg
            };
            if !proportional {
                grid.fill(
                    Rect::new(area.x, y, area.w, 1),
                    cellix_render::Style { bg, ..theme.text },
                );
            }
            // A tall heading's spacer shares its line, and takes no mark.
            let mut earlier = rows[..index]
                .iter()
                .rev()
                .take_while(|r| r.line == row.line);
            let first_row = row.stop && !earlier.any(|r| r.stop);
            if first_row && let Some(change) = changes.1.get(&row.line) {
                // Beside a tall heading's text, which sits in the row below its own.
                let mark = if row.tall { y + 1 } else { y };
                self.draw_change(grid, left as f32 - 1.4, mark, *change, theme);
            }
            if first_row && marks.comments.contains(&(row.line + 1)) {
                let mark = cellix_render::Style {
                    fg: theme.accent,
                    bg,
                    ..theme.text
                };
                grid.put_str(area.x + 1, y, "◆", mark, left);
            }
            // Xcode shows a heading's level in the margin, beside the caret.
            let commented = marks.comments.contains(&(row.line + 1));
            if proportional && focused && index == caret_row && row.heading > 0 && !commented {
                let dim = cellix_render::Style {
                    fg: theme.gutter.fg,
                    ..theme.text
                };
                self.draw_heading_mark(grid, row, (area.x, left, y), dim.fg);
            }
            if row.rule && proportional {
                let line = Bounds::cells(left as f32, y as f32 + 0.5, 60.0, 0.0);
                grid.hairline(line, theme.popup_border);
            }
            if row.quote {
                // Whole rows, so a block's bar runs on unbroken from row to row.
                let bar = Bounds::cells(left as f32 + 0.1, y as f32, 0.3, 1.0);
                let colour = row.callout.map(|kind| callout_colour(kind, theme));
                grid.panel(bar, 0, Some(colour.unwrap_or(theme.popup_border)), None);
            }
            // A tall heading on the last row would reach into the status bar, which paint
            // can't be clipped by, so it waits until it fits.
            if !(proportional && row.tall && y + 2 >= area.bottom()) {
                self.draw_page_row(grid, row, (left, y), area, bg, theme);
            }
        }
        if focused && primary.is_empty() && caret_row >= self.top {
            let y = area.y as usize + caret_row - self.top;
            let x = left as f32 + caret_x;
            self.draw_preview(grid, area, (x, y as f32), theme);
            if y < area.bottom() as usize && x < area.right() as f32 {
                let row = &rows[caret_row];
                let size = row.glyphs.first().map_or(100, |g| g.font.size) as f32 / 100.0;
                grid.set_caret(x, y as u16, (0.62 * size).min(1.6));
                if row.tall
                    && let Some(caret) = &mut grid.caret
                {
                    caret.y += units(TALL_DROP);
                }
            }
        }
    }

    /// Shows what the formula under the caret looks like, just below its line.
    fn draw_preview(&self, grid: &mut Grid, area: Rect, (x, y): (f32, f32), theme: &Theme) {
        let cache = self.page.borrow();
        let Some(page) = cache.as_ref() else {
            return;
        };
        let Some(figure) = page.preview.and_then(|index| page.figures.get(index)) else {
            return;
        };
        const PADDING: (f32, f32) = (1.0, 0.3);
        let (width, height) = (
            figure.width + PADDING.0 * 2.0,
            figure.height + PADDING.1 * 2.0,
        );
        let left = x.min(area.right() as f32 - width - 1.0).max(area.x as f32);
        let top = y + 1.2;
        let clip = Bounds::cells(area.x as f32, area.y as f32, area.w as f32, area.h as f32);
        grid.popup(
            Bounds::cells(left, top, width, height),
            22,
            theme.popup,
            theme.popup_border,
        );
        grid.paint.push(Paint::Image {
            bounds: Bounds::cells(
                left + PADDING.0,
                top + PADDING.1,
                figure.width,
                figure.height,
            ),
            clip,
            bitmap: figure.bitmap.clone(),
            color: theme.text.fg,
        });
    }

    /// The small `#` beside a heading, sitting on the heading's baseline.
    fn draw_heading_mark(
        &self,
        grid: &mut Grid,
        row: &Row,
        (x, left, y): (u16, u16, u16),
        color: Rgb,
    ) {
        /// How far a font's baseline sits below the middle of its line, in font sizes.
        const BASELINE: f32 = 0.35;
        const MARK_SIZE: u8 = 85;
        let size = row.glyphs.first().map_or(100, |g| g.font.size);
        let scale = (size as f32 - MARK_SIZE as f32) / 100.0;
        let drop = BASELINE * INTERFACE_SIZE * scale;
        let top = y as f32 + if row.tall { TALL_DROP } else { 0.0 } + drop;
        let font = Font {
            size: MARK_SIZE,
            ..Font::default()
        };
        grid.text_run(
            (x as f32 + 0.7, top),
            left as f32,
            "#",
            (color, false),
            font,
        );
    }

    fn draw_page_row(
        &self,
        grid: &mut Grid,
        row: &Row,
        (left, y): (u16, u16),
        area: Rect,
        bg: Rgb,
        theme: &Theme,
    ) {
        let proportional = !self.measure.in_cells();
        let origin = left as f32;
        let fg_of = |tone: Tone| match tone {
            Tone::Text | Tone::Block(None) => theme.text.fg,
            Tone::Heading => theme.heading,
            Tone::Code => theme.string,
            Tone::Block(Some(token)) => theme.token(token),
            Tone::Link | Tone::Check(_) => theme.accent,
            Tone::Dim | Tone::TableLine => theme.gutter.fg,
            Tone::Formula { .. } | Tone::Source | Tone::Marked => theme.text.fg,
            Tone::Struck | Tone::Raised | Tone::Lowered => theme.text.fg,
            Tone::Footnote => theme.accent,
            Tone::Callout(kind) => callout_colour(kind, theme),
            Tone::Inserted => theme.inserted(),
            Tone::Deleted | Tone::Failed => theme.deleted(),
            Tone::Margin(_) => theme.gutter.fg,
        };
        let selected = |at: Option<usize>| {
            at.is_some_and(|at| {
                self.selections
                    .iter()
                    .any(|s| at >= s.start() && at < s.end())
            })
        };
        let found = |at: Option<usize>| {
            at.is_some_and(|at| self.found.iter().any(|f| at >= f.0 && at < f.1))
        };
        let quoted = |at: Option<usize>| {
            at.is_some_and(|at| self.quoted.borrow().iter().any(|q| at >= q.0 && at < q.1))
        };
        let mark = |at: Option<usize>| {
            if selected(at) {
                Some(theme.selection)
            } else if found(at) {
                Some(theme.found)
            } else {
                quoted(at).then_some(theme.pick)
            }
        };
        let issues = self.current_issues();
        let flagged = |at: Option<usize>| {
            at.is_some_and(|at| issues.iter().any(|i| at >= i.start && at < i.end))
        };
        // Cells carry the text for the cell tier, and for tests. Pixels come from paint.
        for g in &row.glyphs {
            let style = cellix_render::Style {
                fg: fg_of(g.tone),
                bg: mark(g.at).filter(|_| !proportional).unwrap_or(bg),
                bold: g.font.bold,
                italic: g.font.italic,
                underline: g.underline || flagged(g.at),
                painted: proportional,
            };
            let x = left + g.x as u16;
            grid.put_str(x, y, g.ch.encode_utf8(&mut [0; 4]), style, area.right());
        }
        if !proportional {
            return;
        }
        let text_y = y as f32 + if row.tall { TALL_DROP } else { 0.0 };
        let right = area.right() as f32;
        for issue in issues {
            let inside = |g: &&Glyph| g.at.is_some_and(|at| at >= issue.start && at < issue.end);
            let mut word = row.glyphs.iter().filter(inside);
            let Some(first) = word.next() else {
                continue;
            };
            let last = word.next_back().unwrap_or(first);
            let x = origin + first.x;
            let width = last.x + last.advance - first.x;
            let colour = if issue.spelling {
                theme.deleted()
            } else {
                theme.accent
            };
            // Dots, since a solid line means a link, or text a change added.
            const DOT: f32 = 0.18;
            const STEP: f32 = 0.4;
            for dot in 0..(width / STEP).ceil() as usize {
                let spot = Bounds::cells(x + dot as f32 * STEP, text_y + 0.9, DOT, 0.07);
                grid.panel(spot, 0, Some(colour), None);
            }
        }
        let mut i = 0;
        while i < row.glyphs.len() {
            let g = row.glyphs[i];
            let same = |o: &Glyph| {
                o.font == g.font
                    && o.tone == g.tone
                    && o.underline == g.underline
                    && mark(o.at) == mark(g.at)
                    && (g.tone != Tone::TableLine || o.x == g.x)
            };
            // A table's cells are apart, so a run stops at a jump in position.
            let mut end = i + 1;
            while end < row.glyphs.len() && same(&row.glyphs[end]) {
                let prior = row.glyphs[end - 1];
                if (prior.x + prior.advance - row.glyphs[end].x).abs() > 0.01 {
                    break;
                }
                end += 1;
            }
            let run = &row.glyphs[i..end];
            let text: String = run.iter().map(|g| g.ch).collect();
            let x = origin + g.x;
            let width: f32 = run.iter().map(|g| g.advance).sum();
            if let Some(color) = mark(g.at) {
                let bounds = Bounds::cells(x, text_y + 0.06, width, 0.88);
                grid.panel(bounds, 6, Some(color), None);
            }
            match g.tone {
                Tone::TableLine => {}
                Tone::Formula { index, .. } => {
                    if let Some(figure) = self.figures().get(index as usize) {
                        // Text sits on a baseline below the row's middle: stand on it.
                        let line = text_y + 0.5 + 0.35 * cellix_render::INTERFACE_SIZE;
                        let top = line - figure.baseline;
                        grid.paint.push(Paint::Image {
                            bounds: Bounds::cells(x, top, figure.width, figure.height),
                            clip: Bounds::cells(
                                area.x as f32,
                                area.y as f32,
                                area.w as f32,
                                area.h as f32,
                            ),
                            bitmap: figure.bitmap.clone(),
                            color: theme.text.fg,
                        });
                    }
                }
                Tone::Check(checked) => {
                    // Square on screen: a row is about twice as tall as a column is wide.
                    const SIDE: f32 = 0.56;
                    let cell = self.measure.cell_pixels().unwrap_or((1, 2));
                    let across = SIDE * cell.1 as f32 / cell.0.max(1) as f32;
                    let left = x + ((width - across) / 2.0).max(0.0);
                    let top = y as f32 + (1.0 - SIDE) / 2.0;
                    let bounds = Bounds::cells(left, top, across, SIDE);
                    let (fill, edge) = if checked {
                        (Some(theme.accent), Some(theme.accent))
                    } else {
                        (None, Some(theme.gutter.fg))
                    };
                    grid.panel(bounds, 22, fill, edge);
                    if checked {
                        grid.paint.push(cellix_render::Paint::Icon {
                            bounds,
                            icon: Icon::Check,
                            color: theme.button_text,
                        });
                    }
                }
                _ => {
                    if matches!(g.tone, Tone::Code | Tone::Source) {
                        let pill = Bounds::cells(x - 0.2, text_y + 0.14, width + 0.4, 0.72);
                        grid.panel(pill, 14, Some(theme.code_bg), None);
                    }
                    if g.tone == Tone::Marked {
                        let pill = Bounds::cells(x - 0.1, text_y + 0.1, width + 0.2, 0.8);
                        grid.panel(pill, 8, Some(theme.highlighter()), None);
                    }
                    let shift = match g.tone {
                        Tone::Raised | Tone::Footnote => -0.2,
                        Tone::Lowered => 0.2,
                        Tone::Margin(moved) => moved as f32 / 64.0,
                        _ => 0.0,
                    };
                    let inked = g.underline || g.tone == Tone::Inserted;
                    let color = (fg_of(g.tone), inked);
                    grid.text_run((x, text_y + shift), right, &text, color, g.font);
                    if matches!(g.tone, Tone::Struck | Tone::Deleted) {
                        let line = Bounds::cells(x, text_y + 0.5, width, 0.0);
                        grid.hairline(line, fg_of(g.tone));
                    }
                }
            }
            i = end;
        }
    }

    fn draw_highlights(
        &self,
        grid: &mut Grid,
        area: Rect,
        gutter: u16,
        theme: &Theme,
        registry: &Registry,
    ) {
        let Some(path) = self.buffer.path() else {
            return;
        };
        let revision = self.buffer.revision();
        let mut cache = self.spans.borrow_mut();
        if !cache.as_ref().is_some_and(|(r, _)| *r == revision) {
            let bytes = self.buffer.rope().len_bytes();
            if bytes <= MAX_INLINE_HIGHLIGHT {
                *cache = Some((revision, registry.highlight(path, &self.buffer.text())));
                self.spans_bytes.set(bytes);
            } else if self.asked.get() != revision {
                self.asked.set(revision);
                let worker = self.worker.get_or_init(Worker::default);
                worker.request(path, self.buffer.text(), revision);
            }
        }
        let Some((cached, spans)) = cache.as_ref() else {
            return;
        };
        let rope = self.buffer.rope();
        // Until the worker answers, text after the edit keeps its colours by moving with it.
        let moved = rope.len_bytes() as isize - self.spans_bytes.get() as isize;
        let edit = rope.char_to_byte(self.selections.primary().head.min(rope.len_chars()));
        let shifted: Vec<Span>;
        let spans = if *cached == revision || moved == 0 {
            spans
        } else {
            let shift = |at: usize| {
                if at >= edit.saturating_sub(moved.max(0) as usize) {
                    at.saturating_add_signed(moved).min(rope.len_bytes())
                } else {
                    at
                }
            };
            shifted = spans
                .iter()
                .map(|s| Span {
                    start: shift(s.start),
                    end: shift(s.end),
                    token: s.token,
                })
                .collect();
            &shifted
        };
        let last_line = (self.top + area.h as usize).min(rope.len_lines());
        let from = rope.line_to_byte(self.top);
        let to = rope.line_to_byte(last_line);
        let first = spans.partition_point(|s| s.end <= from);
        for span in spans[first..].iter().take_while(|s| s.start < to) {
            let fg = theme.token(span.token);
            let (mut at, end) = (rope.byte_to_char(span.start), rope.byte_to_char(span.end));
            while at < end {
                let line = rope.char_to_line(at);
                let line_end =
                    end.min(rope.line_to_char(line) + self.line_text(line).chars().count());
                if line >= self.top && line < last_line && at < line_end {
                    let (a, b) = (self.column_of(at), self.column_of(line_end));
                    let x_from = a.max(self.left) - self.left;
                    let x_to = b.max(self.left) - self.left;
                    let rect = Rect::new(
                        (area.x + gutter).saturating_add(x_from as u16),
                        area.y + (line - self.top) as u16,
                        (x_to - x_from) as u16,
                        1,
                    );
                    let clipped = Rect::new(
                        rect.x,
                        rect.y,
                        rect.w.min(area.right().saturating_sub(rect.x)),
                        1,
                    );
                    grid.set_style(clipped, |style| cellix_render::Style { fg, ..style });
                }
                let next = rope.len_lines().min(line + 1);
                if next == line + 1 && next < rope.len_lines() {
                    at = rope.line_to_char(next);
                } else {
                    break;
                }
            }
        }
    }

    fn draw_range(&self, grid: &mut Grid, area: Rect, gutter: u16, s: &Selection, bg: Rgb) {
        let rope = self.buffer.rope();
        let (first, last) = (rope.char_to_line(s.start()), rope.char_to_line(s.end()));
        for line in first.max(self.top)..=last {
            if line >= self.top + area.h as usize {
                break;
            }
            let start = rope.line_to_char(line);
            let from = self.column_of(s.start().max(start));
            let line_end = start + self.line_text(line).chars().count();
            let to = self.column_of(s.end().min(line_end));
            let x_from = (area.x + gutter) as usize + from.saturating_sub(self.left);
            let x_to = (area.x + gutter) as usize + to.saturating_sub(self.left);
            let y = area.y + (line - self.top) as u16;
            let rect = Rect::new(
                x_from as u16,
                y,
                (x_to - x_from.min(x_to)).max(usize::from(line < last)) as u16,
                1,
            );
            grid.set_style(rect, |style| cellix_render::Style { bg, ..style });
        }
    }
}