summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 369df16010deb080900a39ade658d17c9367965e (plain)
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
//! Write_Away: the AppKit shell. One window, one piece.
//!
//! The page is an NSTextView and its text storage is the truth about the text. Two custom
//! attributes ride on that text: `key_group` (the id of a doc.Group, whose active variant
//! is the attributed run) and `key_ghost`. The Lab also marks skipped proposals for Undo.
//! The tints and dimming in `refresh` and the pen lines and dots in `drawBackground` are
//! derived from the text and its attributes.
//!
//! The alternatives panel is a second text view, one variant to a line. Its text is its
//! group: see `pull`, `fill` and `settle`.
const std = @import("std");
const objc = @import("objc.zig");
const markdown = @import("markdown.zig");
const doc = @import("doc.zig");
const ai = @import("ai.zig");
const lab = @import("lab.zig");
const lab_ui = @import("lab_ui.zig");

const id = objc.id;
const SEL = objc.SEL;
const NSRange = objc.NSRange;
const NSPoint = objc.NSPoint;
const NSSize = objc.NSSize;
const NSRect = objc.NSRect;
const msg = objc.msg;
const str = objc.str;
const gpa = std.heap.c_allocator;

extern const NSFontAttributeName: id;
extern const NSForegroundColorAttributeName: id;
extern const NSUnderlineStyleAttributeName: id;
extern const NSStrikethroughStyleAttributeName: id;
extern const NSUnderlineColorAttributeName: id;
extern const NSBackgroundColorAttributeName: id;
extern const NSParagraphStyleAttributeName: id;
extern const NSViewFrameDidChangeNotification: id;
extern const NSAppearanceNameDarkAqua: id;
extern const NSFileTypeRegular: id;
extern const NSDeviceRGBColorSpace: id;
extern fn NSRectFill(rect: NSRect) void;
extern fn NSBeep() void;

const CFRange = extern struct { location: isize, length: isize };
extern fn CFStringTokenizerCreate(alloc: ?*anyopaque, string: id, range: CFRange, options: usize, locale: ?*anyopaque) ?*anyopaque;
extern fn CFStringTokenizerGoToTokenAtIndex(tokenizer: ?*anyopaque, index: isize) usize;
extern fn CFStringTokenizerGetCurrentTokenRange(tokenizer: ?*anyopaque) CFRange;
extern fn CFRelease(object: ?*anyopaque) void;

extern var _dispatch_main_q: anyopaque; // what C's dispatch_get_main_queue() is
extern fn dispatch_async_f(queue: *anyopaque, context: ?*anyopaque, work: *const fn (?*anyopaque) callconv(.c) void) void;
extern fn NSHomeDirectory() id;

const column_w = 780; // 65 characters
const panel_w = 280;
const margin = 44; // the least there is beside the column, for the marks that stand there
const Mod = struct {
    const shift: usize = 1 << 17;
    const ctrl: usize = 1 << 18;
    const opt: usize = 1 << 19;
    const cmd: usize = 1 << 20;
};

var ctl: id = null; // the one controller: every delegate, every menu target
var window: id = null;
var page: id = null; // the piece
var storage: id = null;
var layout: id = null;
var scroll: id = null;
var over: id = null; // Overflow
var over_scroll: id = null;
var split: id = null;
var draft_item: id = null;
var overflow_item: id = null;
var count: id = null; // the word count, above the page on the left
var alts: id = null; // the alternatives panel: one variant to a line
var alts_scroll: id = null;
var alts_hint: id = null;
var alts_undo: id = null; // the panel's typing has its own undo, not the page's
var tabs: [3]id = undefined; // Word, Sentence, Paragraph

var key_group: id = null;
var key_ghost: id = null;
var key_lab_keep: id = null;
var key_fence: id = null; // on a paragraph that leaves a code fence open: `markdown.fenceLine`'s state after it
var key_comment: id = null; // on an HTML comment: `yes` on what it says, 2 on its delimiters
var key_rule: id = null; // on a "---" or "***" or "___" that is drawn as a rule, and on
var key_quote: id = null; // a quoted line that has a bar for its ">": neither while the caret is there
var key_picture: id = null; // on a line that is all one image, the NSImage drawn in its place: likewise
var pictures: id = null; // every picture this piece has shown, by its file's path
var yes: id = null;
var font: id = null;
var bold: id = null;
var small: id = null;
var hidden: id = null; // Markdown punctuation: too small to see
var italic: id = null;
var bold_italic: id = null;
var code_font: id = null;
var markdown_dirty: ?NSRange = null;
var markdown_caret: ?usize = null;
var markdown_rendering = false;
var markdown_front = false; // the piece opens with YAML frontmatter: see `doc.frontmatter`
var markdown_comments: std.ArrayList(markdown.Span) = .empty; // as of the last `scanComments`
var markdown_units: std.ArrayList(u16) = .empty;
var markdown_parser: markdown.Parser = .{};
var markdown_line: id = null; // a single line, struck through the text or under a link
var spaced: id = null; // the page's paragraph style,
var quote_shown: id = null; // a quoted paragraph's with the caret in it, its lines hung from the "> ",
var quote_hidden: id = null; // and without: indented by as much as the "> " that is out of sight
var script: id = null; // the hand the panel's tabs are written in
var base_attrs: id = null;
var color: struct { bg: id, panel: id, text: id, near: id, far: id, ghost: id, clear: id, dim: id, word: id, word_line: id, sentence: id, sentence_line: id, paragraph: id, bar: id, ring: id, hover: id, selection: id, code: id, link: id } = undefined;

var groups: std.AutoArrayHashMapUnmanaged(u32, doc.Group) = .empty;
var next_id: u32 = 1;
var file_path: ?[]u8 = null;
var document_defaults: id = null;
const last_document = "LastDocumentPath";
var received_open = false; // Finder can send openFile: before didFinishLaunching:
var tools = true; // off is read mode: just the text
var overflow_open = false;
var hover: u32 = 0; // the group under the pointer
var armed = false; // the pointer was used last, so the arrow keys are the hovered group's
var target: u32 = 0; // the group the alternatives panel is on, when it is open
var home: std.ArrayList(u8) = .empty; // what the target showed when the page's undo last heard: see `settle`
var quiet = false; // the panel is changing the page, and undo is not to be told yet
var filling = false; // the panel's text is being set from its group, not typed

var threaded: std.Io.Threaded = undefined;
var io: std.Io = undefined; // for libpantograph: the AI's network and the key's file
var tones: [2]id = undefined; // the tick, and the lower tick
var tick_gid: u32 = 0; // the group being played with,
var tick_home: std.ArrayList(u8) = .empty; // what it showed when the playing began,
var tick_at: f64 = 0; // and when it last changed
var asking: u32 = 0; // the group the AI is being asked about: one question at a time
var ask_seq: u32 = 0; // which question, so that an answer nobody is waiting for is dropped
var inf_style: id = null; // the inference dialog's dialect menu and URL field, while it is up
var inf_url: id = null;
var reading: ?*Job = null; // worker owns a pending job; the review owns an answered one
var lab_message: std.ArrayList(u8) = .empty;
var lab_changing = false; // grouping a change to the proposal's own ghost runs

// --- Small conveniences ---------------------------------------------------------------------

fn rgb(hex: u24, alpha: f64) id {
    const ch = struct {
        fn f(h: u24, by: u5) f64 {
            return @as(f64, @floatFromInt((h >> by) & 0xff)) / 255.0;
        }
    }.f;
    const c = msg(id, objc.class("NSColor"), "colorWithSRGBRed:green:blue:alpha:", .{ ch(hex, 16), ch(hex, 8), ch(hex, 0), alpha });
    return msg(id, c, "retain", .{});
}

fn number(n: u32) id {
    return msg(id, objc.class("NSNumber"), "numberWithUnsignedInt:", .{n});
}

fn dict(pairs: []const [2]id) id {
    const d = msg(id, objc.new("NSMutableDictionary"), "autorelease", .{});
    for (pairs) |p| msg(void, d, "setObject:forKey:", .{ p[1], p[0] });
    return d;
}

fn len() usize {
    return msg(usize, storage, "length", .{});
}

fn string(view: id) id {
    return msg(id, view, "string", .{});
}

fn textOf(r: NSRange) []const u8 {
    return objc.utf8(msg(id, string(page), "substringWithRange:", .{r}));
}

fn selection() NSRange {
    return msg(NSRange, page, "selectedRange", .{});
}

fn select(r: NSRange) void {
    msg(void, page, "setSelectedRange:", .{r});
}

fn end(r: NSRange) usize {
    return r.location + r.length;
}

fn overlap(a: NSRange, b: NSRange) bool {
    return a.location < end(b) and b.location < end(a);
}

fn shift(i: usize, by: isize) usize {
    return @intCast(@as(isize, @intCast(i)) + by);
}

/// `r` without the blanks at its ends.
fn trimmed(range: NSRange) NSRange {
    var r = range;
    while (r.length > 0 and isBlank(charAt(r.location))) r = .{ .location = r.location + 1, .length = r.length - 1 };
    while (r.length > 0 and isBlank(charAt(end(r) - 1))) r.length -= 1;
    return r;
}

fn isBlank(c: u16) bool {
    return c == ' ' or c == '\n' or c == '\t' or c == '\r';
}

fn styled(text: []const u8, face: id, ink: id) id {
    const raw = msg(id, objc.class("NSAttributedString"), "alloc", .{});
    const rich = msg(id, raw, "initWithString:attributes:", .{ str(text), dict(&.{ .{ NSFontAttributeName, face }, .{ NSForegroundColorAttributeName, ink } }) });
    return msg(id, rich, "autorelease", .{});
}

fn wordAt(i: usize) NSRange {
    const by_word: isize = 1;
    return msg(NSRange, page, "selectionRangeForProposedRange:granularity:", .{ NSRange{ .location = i }, by_word });
}

fn paragraphOf(view: id, r: NSRange) NSRange {
    return msg(NSRange, string(view), "paragraphRangeForRange:", .{r});
}

fn charAt(i: usize) u16 {
    return msg(u16, string(page), "characterAtIndex:", .{i});
}

fn setDirty(dirty: bool) void {
    msg(void, window, "setDocumentEdited:", .{dirty});
    lab_ui.state(dirty, overflow_open);
}

fn alert(what: []const u8, detail: []const u8) void {
    const a = msg(id, objc.new("NSAlert"), "autorelease", .{});
    msg(void, a, "setMessageText:", .{str(what)});
    msg(void, a, "setInformativeText:", .{str(detail)});
    _ = msg(isize, a, "runModal", .{});
}

// --- Reading the attributes -----------------------------------------------------------------

/// Walks the runs of the page that carry `key`.
const Runs = struct {
    key: id,
    at: usize = 0,

    const Run = struct { value: id, range: NSRange };

    fn next(it: *Runs) ?Run {
        const n = len();
        while (it.at < n) {
            var r: NSRange = .{};
            const v = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ it.key, it.at, &r, NSRange{ .location = it.at, .length = n - it.at } });
            it.at = end(r);
            if (v != null) return .{ .value = v, .range = r };
        }
        return null;
    }
};

fn runAt(key: id, i: usize) ?Runs.Run {
    if (i >= len()) return null;
    var r: NSRange = .{};
    const v = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, i, &r, NSRange{ .length = len() } });
    return if (v == null) null else .{ .value = v, .range = r };
}

fn idOf(value: id) u32 {
    return msg(u32, value, "unsignedIntValue", .{});
}

fn groupRange(gid: u32) ?NSRange {
    var it: Runs = .{ .key = key_group };
    while (it.next()) |run| if (idOf(run.value) == gid) return run.range;
    return null;
}

/// The group a caret or selection is in, counting a caret at either edge.
fn groupTouching(sel: NSRange) ?Runs.Run {
    if (runAt(key_group, sel.location)) |run| if (end(sel) <= end(run.range)) return run;
    if (sel.length == 0 and sel.location > 0) return runAt(key_group, sel.location - 1);
    return null;
}

/// The value of `key` if the caret or selection lies strictly inside one run of it. Text
/// typed at a run's edge lands outside the run.
fn inside(key: id, sel: NSRange) id {
    if (sel.length == 0 and sel.location == 0) return null;
    const run = runAt(key, if (sel.length == 0) sel.location - 1 else sel.location) orelse return null;
    const fits = if (sel.length == 0) end(run.range) > sel.location else end(run.range) >= end(sel);
    return if (fits) run.value else null;
}

// --- Changing the page ----------------------------------------------------------------------

/// Replace text by way of the text view's own protocol, so undo sees it. With no `attrs`
/// the new text looks like what it replaces. While `quiet`, undo is not told: see `settle`.
fn replace(r: NSRange, text: []const u8, attrs: id) void {
    const ns = str(text);
    if (!quiet and !msg(bool, page, "shouldChangeTextInRange:replacementString:", .{ r, ns })) return;
    if (attrs == null) {
        msg(void, storage, "replaceCharactersInRange:withString:", .{ r, ns });
    } else {
        const raw = msg(id, objc.class("NSAttributedString"), "alloc", .{});
        const rich = msg(id, msg(id, raw, "initWithString:attributes:", .{ ns, attrs }), "autorelease", .{});
        msg(void, storage, "replaceCharactersInRange:withAttributedString:", .{ r, rich });
    }
    if (!quiet) msg(void, page, "didChangeText", .{});
}

/// Put one of our attributes on a range, or with a null value take it off. Undoable.
fn mark(r: NSRange, key: id, value: id) void {
    if (r.length == 0) return;
    if (!msg(bool, page, "shouldChangeTextInRange:replacementString:", .{ r, @as(id, null) })) return;
    if (value != null) {
        msg(void, storage, "addAttribute:value:range:", .{ key, value, r });
    } else {
        msg(void, storage, "removeAttribute:range:", .{ key, r });
    }
    msg(void, page, "didChangeText", .{});
}

/// Put `text` on the page as what group `gid` shows, in place of what is at `r`. Returns
/// where it is now.
fn put(gid: u32, r: NSRange, text: []const u8) NSRange {
    const g = groups.getPtr(gid) orelse return r;
    const new_len = doc.utf16Len(text);
    var sel = selection();
    const attrs = msg(id, msg(id, base_attrs, "mutableCopy", .{}), "autorelease", .{});
    msg(void, attrs, "setObject:forKey:", .{ number(gid), key_group });
    if (inside(key_ghost, r)) |owner| msg(void, attrs, "setObject:forKey:", .{ owner, key_ghost });
    replace(r, text, attrs);
    // A caret in the group goes to the end of the new text; one further on stays among its words.
    if (sel.location >= end(r)) {
        sel.location = sel.location - r.length + new_len;
    } else if (end(sel) >= r.location) {
        sel = .{ .location = r.location + new_len };
    }
    // The article comes second: between the two changes the page must not show one variant
    // while the group holds another, or `refresh` would take the page's word for it.
    const moved = if (g.scope == .word) agree(r.location, text) else 0;
    if (sel.location >= r.location) sel.location = shift(sel.location, moved);
    select(sel);
    return .{ .location = shift(r.location, moved), .length = new_len };
}

/// "a thumbtack", "an eraser": the article in front of a word follows the word. `at` is
/// where the word starts. Returns how far the word moved.
fn agree(at: usize, word: []const u8) isize {
    const an = doc.takesAn(word) orelse return 0;
    if (at < 2 or charAt(at - 1) != ' ') return 0;
    const was_an = at > 2 and charAt(at - 2) | 0x20 == 'n';
    const a = at - @as(usize, if (was_an) 3 else 2);
    if (charAt(a) | 0x20 != 'a') return 0;
    if (a > 0 and isLetter(charAt(a - 1))) return 0; // the end of some other word
    if (was_an == an) return 0;
    replace(.{ .location = a + 1, .length = @intFromBool(was_an) }, if (an) "n" else "", null);
    return if (an) 1 else -1;
}

fn isLetter(c: u16) bool {
    return c > 127 or std.ascii.isAlphabetic(@intCast(c));
}

fn flip(gid: u32, delta: isize) void {
    settle();
    const r = groupRange(gid) orelse return;
    const g = groups.getPtr(gid) orelse return;
    if (g.variants.items.len < 2) return if (gid != target) mark(r, key_group, null); // nothing to choose between
    if (mixedGhost(r)) return aim(gid); // panel explains why this swap is blocked
    const was = textOf(r);
    g.step(delta);
    _ = put(gid, r, g.shown());
    tick(gid, was);
}

/// The two tones. Every change of what a group shows ticks, and the tick is lower when it
/// lands back on what the group showed when the playing began. `was` is what it showed
/// before this change.
fn tick(gid: u32, was: []const u8) void {
    const g = groups.getPtr(gid) orelse return;
    const now = msg(f64, objc.class("NSDate"), "timeIntervalSinceReferenceDate", .{});
    // Under the pointer a pause ends the playing. In the panel it lasts as long as the visit.
    if (gid != tick_gid or (gid != target and now - tick_at > 1.75)) startPlaying(gid, was);
    tick_at = now;
    if (!msg(bool, window, "isVisible", .{})) return; // nothing to hear from a window nobody can see
    const tone = tones[@intFromBool(std.mem.eql(u8, tick_home.items, g.shown()))];
    _ = msg(bool, tone, "stop", .{});
    _ = msg(bool, tone, "play", .{});
}

fn startPlaying(gid: u32, showing: []const u8) void {
    tick_gid = gid;
    tick_home.clearRetainingCapacity();
    tick_home.appendSlice(gpa, showing) catch {};
}

/// A short sine tick, as a sound ready to play.
fn makeTone(hz: f64) id {
    const rate = 44100;
    const n = rate * 45 / 1000; // 45 ms
    var wav: [44 + 2 * n]u8 = undefined;
    const le = std.mem.writeInt;
    @memcpy(wav[0..4], "RIFF");
    le(u32, wav[4..8], wav.len - 8, .little);
    @memcpy(wav[8..16], "WAVEfmt ");
    le(u32, wav[16..20], 16, .little); // what follows describes plain PCM:
    le(u16, wav[20..22], 1, .little);
    le(u16, wav[22..24], 1, .little); // one channel
    le(u32, wav[24..28], rate, .little);
    le(u32, wav[28..32], rate * 2, .little); // bytes a second
    le(u16, wav[32..34], 2, .little); // bytes a sample
    le(u16, wav[34..36], 16, .little); // bits a sample
    @memcpy(wav[36..40], "data");
    le(u32, wav[40..44], 2 * n, .little);
    for (0..n) |i| {
        const t = @as(f64, @floatFromInt(i)) / rate;
        const level = 0.2 * @exp(-t * 90) * @sin(2 * std.math.pi * hz * t);
        le(i16, wav[44 + 2 * i ..][0..2], @intFromFloat(level * 32767), .little);
    }
    const data = msg(id, objc.class("NSData"), "dataWithBytes:length:", .{ @as([*]const u8, &wav), @as(usize, wav.len) });
    return msg(id, msg(id, objc.class("NSSound"), "alloc", .{}), "initWithData:", .{data});
}

/// Delete the variant that is showing. A group left with one variant is plain text again.
fn removeShown(gid: u32) void {
    settle();
    const r = groupRange(gid) orelse return;
    const g = groups.getPtr(gid) orelse return;
    if (g.variants.items.len > 1) {
        if (mixedGhost(r)) return aim(gid);
        g.remove(gpa) catch return;
        _ = put(gid, r, g.shown());
    }
    if (g.variants.items.len < 2 and gid != target) if (groupRange(gid)) |now| mark(now, key_group, null);
}

/// After any change: bring the groups in line with the text, then redraw every mark.
fn refresh() void {
    const all: NSRange = .{ .length = len() };
    validateReading();
    for ([_]id{ NSForegroundColorAttributeName, NSBackgroundColorAttributeName, NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName }) |key| {
        msg(void, layout, "removeTemporaryAttribute:forCharacterRange:", .{ key, all });
    }
    if (target != 0 and groupRange(target) == null) { // its text has gone from the page
        target = 0;
        panels();
    }
    // While the panel is open its target stands out: the rest of its paragraph is dimmed a
    // little and every other paragraph a lot.
    if (tools) if (groupRange(target)) |r| {
        tint(NSForegroundColorAttributeName, color.far, all);
        tint(NSForegroundColorAttributeName, color.near, paragraphOf(page, r));
        msg(void, layout, "removeTemporaryAttribute:forCharacterRange:", .{ NSForegroundColorAttributeName, r });
    };
    markdownRefresh();

    const um = msg(id, page, "undoManager", .{});
    const undoing = msg(bool, um, "isUndoing", .{}) or msg(bool, um, "isRedoing", .{});
    var it: Runs = .{ .key = key_group };
    while (it.next()) |run| {
        const gid = idOf(run.value);
        const g = groups.getPtr(gid) orelse continue;
        g.sync(gpa, textOf(run.range), undoing) catch {};
        if (tools and armed and hover == gid) tint(NSBackgroundColorAttributeName, color.hover, run.range);
    }
    drawReview();
    it = .{ .key = key_ghost };
    while (it.next()) |run| tint(NSForegroundColorAttributeName, color.ghost, run.range);
    it = .{ .key = key_comment };
    while (it.next()) |run| if (idOf(run.value) == 1) tint(NSForegroundColorAttributeName, color.ghost, run.range);

    msg(void, page, "setNeedsDisplay:", .{true});
    status();
    fill(false);
}

fn tint(key: id, value: id, r: NSRange) void {
    msg(void, layout, "addTemporaryAttribute:value:forCharacterRange:", .{ key, value, r });
}

fn scopeColor(scope: doc.Scope) id {
    return switch (scope) {
        .word => color.word,
        .sentence => color.sentence,
        .paragraph => color.paragraph,
    };
}

/// Record the post-edit range; don't mutate storage while it is processing an edit.
fn markdownEdited(_: id, _: SEL, _: id, _: usize, changed: NSRange, delta: isize) callconv(.c) void {
    if (markdown_rendering) return;
    const old_end: usize = @intCast(@as(isize, @intCast(end(changed))) - delta);
    if (markdown_caret) |i| markdown_caret = afterEdit(i, changed, old_end);
    markdown_dirty = if (markdown_dirty) |r| markdownRange(
        @min(changed.location, afterEdit(r.location, changed, old_end)),
        @max(end(changed), afterEdit(end(r), changed, old_end)),
    ) else changed;
}

fn afterEdit(i: usize, changed: NSRange, old_end: usize) usize {
    if (i < changed.location) return i;
    if (i < old_end) return changed.location;
    return end(changed) + (i - old_end);
}

fn markdownRange(start: usize, stop: usize) NSRange {
    return .{ .location = start, .length = stop - start };
}

/// Fonts must be in storage, not temporary attributes. Style only the edited paragraphs
/// and the ones whose active inline syntax might change. No character edits or undo entries.
fn markdownRefresh() void {
    if (markdown_rendering or msg(bool, page, "hasMarkedText", .{})) return;
    // The layout manager moves the selection while it is still hearing about an edit, and a
    // font changed under it then keeps the old font's glyphs. `textDidChange` comes after.
    if (msg(usize, storage, "editedMask", .{}) != 0) return;
    const sel = selection();
    const caret = if (sel.length == 0) sel.location else null;
    if (markdown_dirty == null and caret == markdown_caret) return;
    const n = len();
    const previous = markdown_caret;
    const changed = markdown_dirty;
    markdown_caret = caret;
    markdown_dirty = null;
    if (n == 0) return;

    var dirty = if (changed) |r| markdownRange(
        paragraphOf(page, .{ .location = @min(r.location, n) }).location,
        end(paragraphOf(page, .{ .location = @min(end(r), n) })),
    ) else NSRange{};
    if (changed != null) {
        // The line that closes frontmatter makes its first line an opening one, from afar.
        markdown_front = charAt(0) == '-' and doc.frontmatter(objc.utf8(string(page))) != 0;
        if (markdown_front != (fenceAt(0) == markdown.front)) dirty = markdownRange(0, @max(end(dirty), end(paragraphOf(page, .{}))));
    }
    markdown_rendering = true;
    defer markdown_rendering = false;
    msg(void, storage, "beginEditing", .{});
    defer msg(void, storage, "endEditing", .{});
    // A comment can open or close by what is typed far from what it hides.
    if (changed != null) if (markComments()) |r| {
        const lines = paragraphOf(page, r);
        dirty = markdownRange(@min(dirty.location, lines.location), @max(end(dirty), end(lines)));
    };
    var open = fenceBefore(dirty.location);
    var i = dirty.location;
    while (i < end(dirty)) {
        const para = paragraphOf(page, .{ .location = i });
        markdownParagraph(para, caret, &open);
        i = end(para);
    }
    // A fence that came or went changes the lines after it, up to one it leaves as it found.
    while (changed != null and i < n) {
        const para = paragraphOf(page, .{ .location = i });
        const was = fenceAt(i);
        markdownParagraph(para, caret, &open);
        i = end(para);
        if (open == was) break;
    }
    var last: ?usize = null;
    for ([_]?usize{ previous, caret }) |pos| if (pos) |at| {
        const para = paragraphOf(page, .{ .location = @min(at, n) });
        if (para.length == 0 or (para.location >= dirty.location and para.location < i) or last == para.location) continue;
        open = fenceBefore(para.location);
        markdownParagraph(para, caret, &open);
        last = para.location;
    };
    markdownFences(caret);
    markdownDelimiters(caret);
    // A change of attributes alone does not get every line it touched drawn again.
    msg(void, page, "setNeedsDisplay:", .{true});
}

/// The fence state the paragraph at `i` leaves behind it: see `key_fence`.
fn fenceAt(i: usize) u32 {
    return idOf(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key_fence, i, @as(?*NSRange, null) }));
}

fn fenceBefore(para_start: usize) u32 {
    return if (para_start == 0 or para_start > len()) 0 else fenceAt(para_start - 1);
}

/// A block's fences show only while the caret is in the block, like any other marker. A
/// run of `key_fence` is one block, less the line that closes it.
fn markdownFences(caret: ?usize) void {
    const n = len();
    const at = if (caret) |c| paragraphOf(page, .{ .location = c }).location else n + 1;
    var it: Runs = .{ .key = key_fence };
    while (it.next()) |run| {
        const close = paragraphOf(page, .{ .location = end(run.range) });
        const closed = close.location == end(run.range) and close.length > 0;
        const show = at >= run.range.location and at < if (closed) end(close) else n + 1;
        for ([_]NSRange{ paragraphOf(page, .{ .location = run.range.location }), if (closed) close else .{} }) |line| {
            if (line.length == 0) continue;
            setMarkdownAttribute(line, NSFontAttributeName, if (show) code_font else hidden);
            setMarkdownAttribute(line, NSForegroundColorAttributeName, if (show) color.dim else color.clear);
            setMarkdownAttribute(line, NSStrikethroughStyleAttributeName, null);
            setMarkdownAttribute(line, NSUnderlineStyleAttributeName, null);
        }
    }
}

fn scanComments() void {
    markdown_comments.clearRetainingCapacity();
    const all: NSRange = .{ .length = len() };
    markdown_units.resize(gpa, all.length) catch return;
    msg(void, string(page), "getCharacters:range:", .{ markdown_units.items.ptr, all });
    var it: markdown.Comments(u16) = .{ .text = markdown_units.items, .front = markdown_front };
    while (it.next()) |c| markdown_comments.append(gpa, c) catch return;
}

/// A comment's two delimiters. One too short for both is all the first.
fn delimiters(c: markdown.Span) [2]NSRange {
    if (c.hi - c.lo < markdown.comment_open + markdown.comment_close) return .{ markdownRange(c.lo, c.hi), markdownRange(c.hi, c.hi) };
    return .{ markdownRange(c.lo, c.lo + markdown.comment_open), markdownRange(c.hi - markdown.comment_close, c.hi) };
}

/// Bring `key_comment` in line with the text. Returns what that changed, if anything.
fn markComments() ?NSRange {
    scanComments();
    var changed: ?NSRange = null;
    var at: usize = 0;
    for (markdown_comments.items) |c| {
        const tags = delimiters(c);
        markComment(markdownRange(at, c.lo), null, &changed);
        markComment(tags[0], number(2), &changed);
        markComment(markdownRange(end(tags[0]), tags[1].location), yes, &changed);
        markComment(tags[1], number(2), &changed);
        at = c.hi;
    }
    markComment(markdownRange(at, len()), null, &changed);
    return changed;
}

fn markComment(r: NSRange, want: id, changed: *?NSRange) void {
    if (r.length == 0 or uniform(r, key_comment, want)) return;
    setMarkdownAttribute(r, key_comment, want);
    changed.* = markdownRange(if (changed.*) |was| was.location else r.location, end(r));
}

/// A comment's delimiters show only while the caret is in it or against it.
fn markdownDelimiters(caret: ?usize) void {
    for (markdown_comments.items) |c| {
        const show = if (caret) |at| at >= c.lo and at <= c.hi else false;
        for (delimiters(c)) |tag| {
            if (tag.length == 0) continue;
            setMarkdownAttribute(tag, NSFontAttributeName, if (show) font else hidden);
            setMarkdownAttribute(tag, NSForegroundColorAttributeName, if (show) color.dim else color.clear);
            setMarkdownAttribute(tag, NSStrikethroughStyleAttributeName, null);
            setMarkdownAttribute(tag, NSUnderlineStyleAttributeName, null);
        }
    }
}

/// `open` is the fence state the paragraph starts in, and is left as the next will find it.
fn markdownParagraph(para: NSRange, caret: ?usize, open: *u32) void {
    if (para.length == 0) return;
    markdown_units.resize(gpa, para.length) catch return;
    msg(void, string(page), "getCharacters:range:", .{ markdown_units.items.ptr, para });
    const units = markdown_units.items;
    // In a comment there is formatting, as in a ghost, but nothing is drawn at full strength.
    const commented = msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key_comment, para.location, @as(?*NSRange, null) }) != null;
    const kind = if (commented) .text else markdown.fenceLine(u16, units, open, markdown_front and para.location == 0);
    setMarkdownAttribute(para, key_fence, if (open.* != 0) number(open.*) else null);
    // What stands for a paragraph's own marks gives way to them while the caret is in it.
    const here = if (caret) |at| paragraphOf(page, .{ .location = at }).location == para.location else false;
    const prefix = if (kind == .text and !(commented and units[0] == '>')) marker(para) else 0;
    const quote = prefix != 0 and units[0] == '>';
    const rule = kind == .text and !commented and switch (markdown.rule(units)) {
        .no => false,
        .yes => true,
        .hyphens => !underlines(para.location),
    };
    const picture = if (kind == .text and !commented and !here) pictureAt(markdown.image(units) orelse &.{}) else null;
    setMarkdownAttribute(para, key_rule, if (rule and !here) yes else null);
    setMarkdownAttribute(para, key_quote, if (quote and !here) yes else null);
    setMarkdownAttribute(para, key_picture, picture);
    setMarkdownAttribute(para, NSParagraphStyleAttributeName, if (picture != null) pictureStyle(picture) else if (!quote) spaced else if (here) quote_shown else quote_hidden);
    switch (kind) {
        .fence => return, // `markdownFences` shows or hides it
        .code => return markdownPaint(para, .{ .code = true }, false, false),
        .text => {},
    }
    if (rule or picture != null) return markdownPaint(para, .{}, false, !here);
    const heading = prefix != 0 and !quote;
    const body = markdownRange(para.location + prefix, end(para));
    markdownPaint(markdownRange(para.location, body.location), .{}, false, !here);
    const marks = markdown_parser.parse(gpa, units[prefix..]) catch return markdownPaint(body, .{}, heading, false);
    var active: markdown.Active = .{};
    var at = body.location;
    for (marks, 0..) |mark_, idx| {
        const partner = mark_.partner orelse continue;
        const tag = markdownRange(body.location + mark_.at, body.location + mark_.at + mark_.width);
        markdownPaint(markdownRange(at, tag.location), active.style(), heading, false);
        const first = body.location + marks[@min(idx, partner)].at;
        const closing = marks[@max(idx, partner)];
        const stop = body.location + closing.at + closing.width;
        const reveal = if (caret) |c| c > first and c < stop else false;
        markdownPaint(tag, .{}, heading, !reveal);
        active.toggle(mark_);
        at = end(tag);
    }
    markdownPaint(markdownRange(at, end(body)), active.style(), heading, false);
}

/// The picture an image's target names, if that is a file on this Mac that is one. A
/// relative path starts from the folder the piece is saved in. Nothing is fetched.
fn pictureAt(named: []const u16) id {
    if (named.len == 0) return null;
    var path = msg(id, objc.class("NSString"), "stringWithCharacters:length:", .{ named.ptr, named.len });
    path = msg(id, path, "stringByRemovingPercentEncoding", .{}) orelse path;
    if (!msg(bool, path, "isAbsolutePath", .{})) {
        const piece = file_path orelse return null;
        path = msg(id, msg(id, str(piece), "stringByDeletingLastPathComponent", .{}), "stringByAppendingPathComponent:", .{path});
    }
    path = msg(id, path, "stringByResolvingSymlinksInPath", .{});
    if (msg(id, pictures, "objectForKey:", .{path})) |known| return known;
    // Only a file is read: a pipe or a device could keep the page waiting for ever.
    const attrs = msg(id, msg(id, objc.class("NSFileManager"), "defaultManager", .{}), "attributesOfItemAtPath:error:", .{ path, @as(?*id, null) });
    if (!msg(bool, msg(id, attrs, "fileType", .{}), "isEqualToString:", .{NSFileTypeRegular})) return null;
    const picture = msg(id, msg(id, msg(id, objc.class("NSImage"), "alloc", .{}), "initWithContentsOfFile:", .{path}), "autorelease", .{}) orelse return null;
    const size = msg(NSSize, picture, "size", .{});
    if (!(size.width > 0 and size.height > 0)) return null;
    msg(void, pictures, "setObject:forKey:", .{ picture, path });
    return picture;
}

/// How big a picture is on the page: as wide as the column's text at most, and never
/// larger than life.
fn pictureSize(picture: id) NSSize {
    const natural = msg(NSSize, picture, "size", .{});
    const container = msg(id, page, "textContainer", .{});
    const room = msg(NSSize, container, "containerSize", .{}).width - 2 * msg(f64, container, "lineFragmentPadding", .{});
    const width = @min(natural.width, room);
    return .{ .width = width, .height = @ceil(width * natural.height / natural.width) };
}

/// A line as tall as its picture: the source, out of sight, holds the place.
fn pictureStyle(picture: id) id {
    const style = msg(id, msg(id, spaced, "mutableCopy", .{}), "autorelease", .{});
    msg(void, style, "setMinimumLineHeight:", .{pictureSize(picture).height});
    return style;
}

/// A column of another width has room for pictures of another height.
fn refitPictures() void {
    const was = markdown_rendering;
    markdown_rendering = true;
    defer markdown_rendering = was;
    msg(void, storage, "beginEditing", .{});
    defer msg(void, storage, "endEditing", .{});
    var it: Runs = .{ .key = key_picture };
    while (it.next()) |run| setMarkdownAttribute(run.range, NSParagraphStyleAttributeName, pictureStyle(run.value));
}

/// Under a line of text, hyphens are not a rule: Markdown reads them as making that line a heading.
fn underlines(at: usize) bool {
    if (at == 0) return false;
    const above = paragraphOf(page, .{ .location = at - 1 });
    return trimmed(above).length != 0 and marker(above) == 0;
}

fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) void {
    if (r.length == 0) return;
    const strong = heading or style.strong;
    const face = if (hide) hidden else if (style.code) code_font else if (style.emphasis)
        (if (strong) bold_italic else italic)
    else if (strong) bold else font;
    const link = style.link and !hide;
    setMarkdownAttribute(r, NSFontAttributeName, face);
    setMarkdownAttribute(r, NSForegroundColorAttributeName, if (hide) color.clear else if (link) color.link else color.text);
    setMarkdownAttribute(r, NSStrikethroughStyleAttributeName, if (style.strike) markdown_line else null);
    setMarkdownAttribute(r, NSUnderlineStyleAttributeName, if (link) markdown_line else null);
}

/// Whether all of `r` has `want` for its `key`. Not by identity alone: text storage may hold
/// its own copy of a paragraph style.
fn uniform(r: NSRange, key: id, want: id) bool {
    var run: NSRange = .{};
    const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, r.location, &run, r });
    return run.length == r.length and (have == want or (want != null and msg(bool, have, "isEqual:", .{want})));
}

fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
    if (uniform(r, key, want)) return;
    if (want != null) {
        msg(void, storage, "addAttribute:value:range:", .{ key, want, r });
    } else {
        msg(void, storage, "removeAttribute:range:", .{ key, r });
    }
}

/// How much of a paragraph is its marker: three characters of "## Title", two of "> quoted".
fn marker(para: NSRange) usize {
    if (para.length == 0 or fenceBefore(para.location) != 0) return 0; // code, not a heading
    if (charAt(para.location) == '>') {
        if (para.length == 1) return 1;
        const next = charAt(para.location + 1);
        return if (next == ' ') 2 else @intFromBool(next == '\n' or next == '\r'); // ">" alone is a quote's blank line
    }
    var hashes: usize = 0;
    while (hashes < para.length and charAt(para.location + hashes) == '#') hashes += 1;
    if (hashes == 0 or hashes > 6 or hashes == para.length or charAt(para.location + hashes) != ' ') return 0;
    return hashes + 1;
}

/// What the next typed character will carry.
fn typing() void {
    const sel = selection();
    const attrs = msg(id, msg(id, base_attrs, "mutableCopy", .{}), "autorelease", .{});
    const group = inside(key_group, sel);
    if (group != null) msg(void, attrs, "setObject:forKey:", .{ group, key_group });
    if (inside(key_ghost, sel) != null) msg(void, attrs, "setObject:forKey:", .{ yes, key_ghost });
    msg(void, page, "setTypingAttributes:", .{attrs});
}

fn status() void {
    const sel = selection();
    const text = if (sel.length > 0) textOf(sel) else objc.utf8(string(page));
    var note_buf: [64]u8 = undefined;
    var note: []const u8 = "";
    const gid = if (armed and hover != 0) hover else if (target != 0) target else if (groupTouching(sel)) |run| idOf(run.value) else 0;
    if (tools) if (groups.getPtr(gid)) |g| {
        note = std.fmt.bufPrint(&note_buf, "   ยท   {s} {d}/{d}", .{ @tagName(g.scope), g.active + 1, g.variants.items.len }) catch "";
    };
    var buf: [256]u8 = undefined;
    const line = std.fmt.bufPrint(&buf, "{d} words  {d} chars{s}{s}", .{
        doc.countWords(text),
        if (sel.length > 0) sel.length else len(),
        if (sel.length > 0) " selected" else "",
        note,
    }) catch return;
    msg(void, count, "setAttributedTitle:", .{styled(line, small, if (tools) color.dim else color.ring)});
    msg(void, count, "sizeToFit", .{});
}

// --- Commands -------------------------------------------------------------------------------

/// Ctrl+Shift+A, and "Alternatives forโ€ฆ" on a right-click.
fn alternative(_: id, _: SEL, _: id) callconv(.c) void {
    if (!aimHere()) NSBeep();
}

fn nextAlt(_: id, _: SEL, _: id) callconv(.c) void {
    flipHere(1);
}

fn prevAlt(_: id, _: SEL, _: id) callconv(.c) void {
    flipHere(-1);
}

/// Ctrl+] and Ctrl+[: flip from the keyboard, the hovered group or else the caret's.
fn flipHere(delta: isize) void {
    const gid = if (armed and hover != 0) hover else if (groupTouching(selection())) |run| idOf(run.value) else return NSBeep();
    flip(gid, delta);
}

/// Ctrl+/. Dim the selection or the word at the caret; on ghosted text, or in a comment,
/// bring all of it back.
fn ghost(_: id, _: SEL, _: id) callconv(.c) void {
    settle();
    const r = ghostable();
    // A suggested cut may touch a manual ghost. Revive only the suggested cut, not
    // the coalesced NSTextStorage run on either side of it.
    if (reading) |j| if (j.owner != null) if (j.hits) |hits| {
        for (hits.items, 0..) |h, i| if (overlap(h.range, r)) {
            j.current = i;
            return labKeep(null, null, null);
        };
    };
    const commented = commentIn(r);
    const revive = commented or ghostIn(r);
    var it: Runs = .{ .key = key_ghost };
    while (it.next()) |run| {
        if (reading) |j| if (run.value == j.owner) continue;
        if (overlap(run.range, r)) mark(run.range, key_ghost, null);
    }
    if (commented) uncomment(r);
    if (!revive) mark(r, key_ghost, yes);
}

fn commentIn(r: NSRange) bool {
    var it: Runs = .{ .key = key_comment };
    while (it.next()) |run| if (overlap(run.range, r)) return true;
    return false;
}

/// Make prose of every comment `r` touches, by taking its delimiters out of the text: with
/// the line, if one has a line to itself, or else with the space that sets it off.
fn uncomment(r: NSRange) void {
    scanComments();
    const found = gpa.dupe(markdown.Span, markdown_comments.items) catch return; // each change scans again
    defer gpa.free(found);
    const um = msg(id, page, "undoManager", .{});
    msg(void, page, "breakUndoCoalescing", .{});
    msg(void, um, "beginUndoGrouping", .{});
    defer msg(void, um, "endUndoGrouping", .{});
    var i = found.len;
    while (i > 0) {
        i -= 1;
        if (!overlap(markdownRange(found[i].lo, found[i].hi), r)) continue;
        var tags = delimiters(found[i]);
        for (&tags) |*tag| if (tag.length > 0) {
            const line = paragraphOf(page, tag.*);
            if (std.meta.eql(trimmed(line), tag.*)) tag.* = line;
        };
        const inner = markdownRange(end(tags[0]), @max(end(tags[0]), tags[1].location));
        if (inner.length > 0 and charAt(end(tags[0])) == ' ') tags[0].length += 1;
        if (end(tags[0]) < tags[1].location and charAt(tags[1].location - 1) == ' ') tags[1] = markdownRange(tags[1].location - 1, end(tags[1]));
        replace(tags[1], "", null);
        replace(tags[0], "", null);
    }
}

/// What Ctrl+/ is about: the selection, or the word at the caret.
fn ghostable() NSRange {
    const sel = selection();
    return if (sel.length > 0) sel else wordAt(sel.location);
}

/// An unrelated replacement has no safe mapping for an internal ghost boundary.
fn mixedGhost(r: NSRange) bool {
    if (r.length == 0) return false;
    var span: NSRange = .{};
    _ = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key_ghost, r.location, &span, r });
    return span.length != r.length;
}

fn ghostIn(r: NSRange) bool {
    var it: Runs = .{ .key = key_ghost };
    while (it.next()) |run| if (overlap(run.range, r)) return true;
    return false;
}

/// Ctrl+Shift+X. Move the selection, or the paragraph, to the end of Overflow.
fn stash(_: id, _: SEL, _: id) callconv(.c) void {
    settle();
    const sel = selection();
    var r = if (sel.length > 0) sel else paragraphOf(page, sel);
    const text = std.mem.trim(u8, textOf(r), "\n");
    if (text.len == 0) return NSBeep();
    if (sel.length == 0 and end(r) < len() and charAt(end(r)) == '\n') r.length += 1; // and the blank line after it

    const have = objc.utf8(string(over));
    const entry = std.mem.concat(gpa, u8, &.{ doc.overflowGap(have), text }) catch return;
    defer gpa.free(entry);
    insert(over, entry, .{ .location = msg(usize, string(over), "length", .{}) });
    insert(page, "", r);
    overflow_open = true;
    tools = true;
    panels();
    msg(void, over, "scrollRangeToVisible:", .{NSRange{ .location = msg(usize, string(over), "length", .{}) }});
}

/// Ctrl+Return. Move Overflow's selection, or its paragraph, to the caret in the page.
fn useOverflow(_: id, _: SEL, _: id) callconv(.c) void {
    settle();
    const sel = msg(NSRange, over, "selectedRange", .{});
    var r = if (sel.length > 0) sel else paragraphOf(over, sel);
    const all = string(over);
    const text = std.mem.trim(u8, objc.utf8(msg(id, all, "substringWithRange:", .{r})), "\n");
    if (text.len == 0) return NSBeep();
    const n = msg(usize, all, "length", .{});
    while (sel.length == 0 and end(r) < n and msg(u16, all, "characterAtIndex:", .{end(r)}) == '\n') r.length += 1;
    insert(page, text, selection());
    insert(over, "", r);
    _ = msg(bool, window, "makeFirstResponder:", .{page});
}

/// Typed-in text, as far as the view and its undo are concerned.
fn insert(view: id, text: []const u8, r: NSRange) void {
    msg(void, view, "insertText:replacementRange:", .{ str(text), r });
}

fn toggleTools(_: id, _: SEL, _: id) callconv(.c) void {
    tools = !tools;
    if (!tools) letGo(); // reading closes the alternatives panel
    panels();
    refresh();
}

fn toggleOverflow(_: id, _: SEL, _: id) callconv(.c) void {
    overflow_open = !overflow_open or !tools;
    tools = true;
    panels();
    refresh();
    _ = msg(bool, window, "makeFirstResponder:", .{if (overflow_open) over else page});
}

/// Overflow takes its strip down the right when it is open and the tools are on. The
/// alternatives panel lies over the page's left margin while it has a target.
fn panels() void {
    lab_ui.state(msg(bool, window, "isDocumentEdited", .{}), overflow_open);
    showLab();
    const showing = overflow_open and tools;
    const content = msg(id, window, "contentView", .{});
    const first = msg(id, window, "firstResponder", .{});
    msg(void, draft_item, "setMinimumThickness:", .{@as(f64, if (target != 0) panel_w + 2 * margin + 200 else 320)});
    if (msg(bool, overflow_item, "isCollapsed", .{}) == showing)
        msg(void, overflow_item, "setCollapsed:", .{!showing});
    msg(void, content, "layoutSubtreeIfNeeded", .{});
    for ([_]id{ alts_scroll, alts_hint, tabs[0], tabs[1], tabs[2] }) |view| msg(void, view, "setHidden:", .{target == 0});
    if ((!showing and first == over) or (target == 0 and first == alts)) _ = msg(bool, window, "makeFirstResponder:", .{page});
    resized(null, null, null);
}

// --- The alternatives panel -----------------------------------------------------------------
//
// The panel's text is its group, one variant to a line. `pull` takes every edit and every
// move of its caret into the group and onto the page. `fill` goes the other way, when the
// group has changed behind the panel's back. `settle` squares it all with the page's undo.

/// Open the panel on the group the caret or selection is in, or else on the selection or
/// the word at the caret. False if nothing there can be said another way.
fn aimHere() bool {
    const sel = selection();
    if (groupTouching(sel)) |run| {
        aim(idOf(run.value));
        return true;
    }
    const r = trimmed(if (sel.length > 0) sel else wordAt(sel.location));
    const para = paragraphOf(page, .{ .location = r.location });
    if (r.length == 0 or end(r) > end(para)) return false; // nothing there, or more than one paragraph
    const text = textOf(para);
    aimAt(r, doc.classify(text, doc.utf8Index(text, r.location - para.location), doc.utf8Index(text, end(r) - para.location)));
    return true;
}

/// Point the panel at `r`: at the group that already covers it, or at a new group of one.
fn aimAt(r: NSRange, scope: doc.Scope) void {
    letGo();
    defer panels(); // whatever became of the target
    if (runAt(key_group, r.location)) |run| if (end(run.range) >= end(r) and groups.contains(idOf(run.value))) return aim(idOf(run.value));

    const g = doc.Group.init(gpa, scope, &.{textOf(r)}, 0) catch return;
    groups.put(gpa, next_id, g) catch return;
    // A group of one is still only text, and undo has nothing to hear about it. But laid
    // over smaller groups it takes their place, and that is a step undo can take back.
    var covers = false;
    var it: Runs = .{ .key = key_group };
    while (it.next()) |run| covers = covers or overlap(run.range, r);
    if (covers) mark(r, key_group, number(next_id)) else msg(void, storage, "addAttribute:value:range:", .{ key_group, number(next_id), r });
    next_id += 1;
    aim(next_id - 1);
}

fn aim(gid: u32) void {
    if (gid != target) {
        letGo();
        target = gid;
        rehome();
        startPlaying(gid, home.items);
    }
    tools = true;
    msg(void, page, "breakUndoCoalescing", .{});
    panels();
    hint("");
    fill(true);
    refresh();
    _ = msg(bool, window, "makeFirstResponder:", .{alts});
}

/// The panel is done with its target. A group nothing was added to is plain text again.
fn letGo() void {
    settle();
    const gid = target;
    target = 0;
    if (asking == gid) asking = 0;
    const g = groups.getPtr(gid) orelse return;
    if (g.variants.items.len > 1) return;
    if (groupRange(gid)) |r| msg(void, storage, "removeAttribute:range:", .{ key_group, r });
    g.deinit(gpa);
    _ = groups.swapRemove(gid);
}

fn closePanel() void {
    letGo();
    panels();
    refresh();
}

/// While the panel has the keyboard, what its target shows changes on the page without a
/// word to undo: a step for every letter typed on a row would be no use to anyone. This
/// makes the whole visit one step, by putting the page quietly back as undo last knew it
/// and then openly as it is now. Everything else that changes the page settles first.
fn settle() void {
    const g = groups.getPtr(target) orelse return;
    const r = groupRange(target) orelse return;
    if (home.items.len == 0 or std.mem.eql(u8, home.items, g.shown())) return;
    if (mixedGhost(r)) return rehome(); // never replay text across a new ghost boundary
    const was = home.toOwnedSlice(gpa) catch return;
    defer gpa.free(was);
    quiet = true;
    const back = put(target, r, was);
    quiet = false;
    _ = put(target, back, g.shown());
    rehome();
}

/// From here on, undo knows what the target shows.
fn rehome() void {
    home.clearRetainingCapacity();
    if (groups.getPtr(target)) |g| home.appendSlice(gpa, g.shown()) catch {};
}

/// The panel was typed in, or its caret moved: its rows are the variants, and the row the
/// caret is on is the one the page shows.
fn pull() void {
    if (filling) return;
    const g = groups.getPtr(target) orelse return;
    const r = groupRange(target) orelse return;
    if (mixedGhost(r)) return fill(false); // don't mutate the rows or active index
    const was = textOf(r);
    const was_on = g.active;
    const was_n = g.variants.items.len;
    const panel_text = objc.utf8(string(alts));
    const changed_rows = !g.sameRows(panel_text);
    const any = g.setRows(gpa, panel_text, caretRow(), home.items) catch return;
    if (!any) return fill(true); // every row was emptied: the one showing stays
    if (changed_rows) setDirty(true); // AI can add rows without changing the visible text
    if (!std.mem.eql(u8, g.shown(), was)) {
        quiet = true;
        _ = put(target, r, g.shown());
        quiet = false;
        setDirty(true);
        if (g.active != was_on and g.variants.items.len == was_n) tick(target, was); // the caret went to another row
    }
    refresh();
    // Undoing back to a "??" does not ask again.
    const undoing = msg(bool, alts_undo, "isUndoing", .{}) or msg(bool, alts_undo, "isRedoing", .{});
    if (asking == 0 and !undoing and askRow() != null) askAI();
}

/// Make the panel say what its group holds: for a new target, and whenever the page, a
/// flip or an undo has changed the group.
fn fill(fresh: bool) void {
    const g = groups.getPtr(target) orelse return;
    filling = true;
    defer filling = false;
    const locked = mixedGhost(groupRange(target) orelse return);
    if (msg(bool, alts, "isEditable", .{}) == locked) {
        msg(void, alts, "setEditable:", .{!locked});
        if (!locked) hint("");
    }
    if (locked) hint("Revive the ghosted part before switching versions.");
    var caret: ?usize = null;
    if (fresh or !g.sameRows(objc.utf8(string(alts)))) {
        var text: std.ArrayList(u8) = .empty;
        defer text.deinit(gpa);
        for (g.variants.items) |v| text.print(gpa, "{s}\n", .{v}) catch return;
        // A lone variant has an empty row under it, where the next one is typed.
        if (g.variants.items.len > 1) _ = text.pop();
        msg(void, alts, "setString:", .{str(text.items)});
        msg(void, alts_undo, "removeAllActions", .{});
        caret = msg(usize, string(alts), "length", .{});
    }
    if (g.variants.items.len > 1 and (caret != null or (caretRow() orelse g.active) != g.active)) {
        if (rowOf(g.active)) |row| caret = end(row);
    }
    if (caret) |at| msg(void, alts, "setSelectedRange:", .{NSRange{ .location = at }});

    // Its looks: the showing row at full strength, the tab for the target's scope lit.
    const lm = msg(id, alts, "layoutManager", .{});
    const all: NSRange = .{ .length = msg(usize, string(alts), "length", .{}) };
    // Typed and landed rows come in without the row spacing the first ones were set with.
    msg(void, msg(id, alts, "textStorage", .{}), "addAttribute:value:range:", .{ NSParagraphStyleAttributeName, msg(id, alts, "defaultParagraphStyle", .{}), all });
    msg(void, lm, "removeTemporaryAttribute:forCharacterRange:", .{ NSForegroundColorAttributeName, all });
    if (rowOf(g.active)) |row| msg(void, lm, "addTemporaryAttribute:value:forCharacterRange:", .{ NSForegroundColorAttributeName, color.text, row });
    if (askRow()) |row| msg(void, lm, "addTemporaryAttribute:value:forCharacterRange:", .{ NSForegroundColorAttributeName, color.word, row });
    for (tabs, tab_names, 0..) |tab, name, i| {
        msg(void, tab, "setAttributedTitle:", .{styled(name, script, if (i == @intFromEnum(g.scope)) color.word else color.dim)});
    }
    msg(void, alts, "setNeedsDisplay:", .{true});
}

const tab_names = [_][]const u8{ "Word", "Sentence", "Paragraph" };

/// The line at the foot of the panel: how it works, or what the AI is up to.
fn hint(note: []const u8) void {
    msg(void, alts_hint, "setAttributedStringValue:", .{styled(if (note.len > 0) note else "return adds ยท esc closes", small, color.ring)});
}

/// The lines of the panel's text: where each is, and which variant it holds, if any.
const Rows = struct {
    lines: std.mem.SplitIterator(u8, .scalar),
    at: usize = 0,
    variants: usize = 0,

    const Row = struct { range: NSRange, variant: ?usize, asks: bool };

    fn init() Rows {
        return .{ .lines = std.mem.splitScalar(u8, objc.utf8(string(alts)), '\n') };
    }

    fn next(it: *Rows) ?Row {
        const line = it.lines.next() orelse return null;
        const row: Row = .{
            .range = .{ .location = it.at, .length = doc.utf16Len(line) },
            .variant = if (doc.blank(line)) null else it.variants,
            .asks = doc.asks(line),
        };
        it.at = end(row.range) + 1;
        if (row.variant != null) it.variants += 1;
        return row;
    }
};

/// The variant on the row the panel's caret is in, if that row holds one.
fn caretRow() ?usize {
    const at = msg(NSRange, alts, "selectedRange", .{}).location;
    var it = Rows.init();
    while (it.next()) |row| if (at <= end(row.range)) return row.variant;
    return null;
}

fn rowOf(variant: usize) ?NSRange {
    var it = Rows.init();
    while (it.next()) |row| if (row.variant == variant) return row.range;
    return null;
}

/// Return in the panel: an empty row at the bottom, for another variant.
fn newRow() void {
    const text = string(alts);
    const n = msg(usize, text, "length", .{});
    const open = n == 0 or msg(u16, text, "characterAtIndex:", .{n - 1}) == '\n';
    if (!open) insert(alts, "\n", .{ .location = n });
    msg(void, alts, "setSelectedRange:", .{NSRange{ .location = msg(usize, string(alts), "length", .{}) }});
}

/// A click on Word, Sentence or Paragraph: the panel moves to that much of the text
/// around the same spot.
fn retab(_: id, _: SEL, sender: id) callconv(.c) void {
    const scope: doc.Scope = @enumFromInt(msg(isize, sender, "tag", .{}));
    const at = (groupRange(target) orelse return).location;
    const para = paragraphOf(page, .{ .location = at });
    const m = marker(para);
    const body: NSRange = .{ .location = para.location + m, .length = para.length - m };
    const r = trimmed(switch (scope) {
        .word => wordAt(at),
        .sentence => sentenceAt(body, at),
        .paragraph => body,
    });
    if (r.length == 0) return NSBeep();
    aimAt(r, scope);
}

/// The sentence around `at`, as the system divides `within` into sentences.
fn sentenceAt(within: NSRange, at: usize) NSRange {
    const by_sentence: usize = 1;
    const whole: CFRange = .{ .location = @intCast(within.location), .length = @intCast(within.length) };
    const tokenizer = CFStringTokenizerCreate(null, string(page), whole, by_sentence, null);
    defer CFRelease(tokenizer);
    if (CFStringTokenizerGoToTokenAtIndex(tokenizer, @intCast(at)) == 0) return .{ .location = at };
    const r = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    return .{ .location = @intCast(r.location), .length = @intCast(r.length) };
}

// --- The AI ---------------------------------------------------------------------------------
//
// A row of the panel that reads "??" asks for suggestions. The question goes out on a
// thread of its own, and `landed` brings the answer back to the main thread.

const Hit = struct { range: NSRange, replacement: ?[]const u8, reason: []const u8, words: usize };
const Job = struct {
    draft: []const u8 = "", // Lab ranges refer to this unnumbered snapshot
    pass: ?lab.Pass = null,
    hits: ?std.ArrayList(Hit) = null,
    owner: id = null, // unique value of this session's proposed ghosts and Keep marks
    current: usize = 0,
    words: usize = 0,
    arena: std.heap.ArenaAllocator, // owns everything below but the answer
    seq: u32,
    settings: ai.Settings = .{},
    system: []const u8 = "",
    question: []const u8 = "",
    answer: ai.Answer = undefined,

    fn deinit(job: *Job) void {
        msg(void, job.owner, "release", .{});
        job.arena.deinit();
        gpa.destroy(job);
    }
};

/// Ctrl+Shift+G, and "AI alternatives forโ€ฆ" on a right-click.
fn aiAlternative(_: id, _: SEL, _: id) callconv(.c) void {
    if (!aimHere()) return NSBeep();
    if (!msg(bool, alts, "isEditable", .{}) or askRow() != null) return;
    newRow();
    insert(alts, "??", msg(NSRange, alts, "selectedRange", .{}));
}

fn askRow() ?NSRange {
    var it = Rows.init();
    while (it.next()) |row| if (row.asks) return row.range;
    return null;
}

fn wanted(scope: doc.Scope) usize {
    return if (scope == .word) 5 else 3;
}

/// The paragraph `r` is in, without its comments unless `r` is in one or runs over one.
fn proseAround(arena: std.mem.Allocator, r: NSRange) []const u8 {
    const para = paragraphOf(page, r);
    if (commentIn(r)) return textOf(para);
    var out: std.ArrayList(u8) = .empty;
    var at = para.location;
    var it: Runs = .{ .key = key_comment, .at = at };
    while (it.next()) |run| {
        if (run.range.location >= end(para)) break;
        out.appendSlice(arena, textOf(markdownRange(at, run.range.location))) catch {};
        at = @min(end(run.range), end(para));
    }
    out.appendSlice(arena, textOf(markdownRange(at, end(para)))) catch {};
    return out.items;
}

/// Send the question the panel's "??" row is asking.
fn askAI() void {
    const g = groups.getPtr(target) orelse return;
    const r = groupRange(target) orelse return;
    asking = target;
    const job = gpa.create(Job) catch return unask("Out of memory.");
    ask_seq += 1;
    job.* = .{ .arena = .init(gpa), .seq = ask_seq };
    const arena = job.arena.allocator();
    job.settings = loadSettings(arena);
    if (!job.settings.ready()) {
        job.deinit();
        // The dialog, but not from inside the change to the text that brought us here.
        return msg(void, ctl, "performSelector:withObject:afterDelay:", .{ objc.sel("needInference:"), @as(id, null), @as(f64, 0) });
    }
    const what = switch (g.scope) {
        .word => "word or phrase",
        .sentence => "sentence",
        .paragraph => "paragraph",
    };
    var q: std.ArrayList(u8) = .empty;
    q.print(arena, "The paragraph it stands in:\n{s}\n\nThe {s} to say another way:\n{s}\n\nAlready tried:\n", .{
        std.mem.trim(u8, proseAround(arena, r), "\n"), what, g.shown(),
    }) catch {};
    for (g.variants.items) |v| q.print(arena, "{s}\n", .{v}) catch {};
    q.print(arena, "\nGive {d} alternatives.", .{wanted(g.scope)}) catch {};
    job.question = q.items;
    job.system =
        \\You help a writer find other ways to say one part of their own piece: a word or short
        \\phrase, a sentence, or a paragraph. Answer with the alternatives alone, one to a line:
        \\no numbering, no quotation marks, no comments. Each must be able to take the original's
        \\place exactly as it stands, so match its grammar, tense, capitalization and closing
        \\punctuation, and keep to the tone of the writing around it. Go by what the passage means
        \\where it stands: a list of dictionary synonyms is not what is wanted. Offer nothing that
        \\has already been tried.
    ;
    const thread = std.Thread.spawn(.{}, work, .{job}) catch {
        job.deinit();
        return unask("The question could not be sent.");
    };
    thread.detach();
    hint("askingโ€ฆ");
}

// --- Lab: one reading of one immutable draft ------------------------------------------------

fn disposeJob(job: *Job) void {
    switch (job.answer) {
        inline else => |bytes| gpa.free(bytes),
    }
    job.deinit();
}

fn finishReview(note: []const u8) void {
    lab_message.clearRetainingCapacity();
    lab_message.appendSlice(gpa, note) catch {};
    if (reading) |job| {
        reading = null;
        if (job.hits != null) {
            // An edit ends the review without reviving anything. Undo can bring back
            // old tokens too; without the owning session those are just saved ghosts.
            if (job.owner != null) {
                msg(void, storage, "beginEditing", .{});
                var it: Runs = .{ .key = key_ghost };
                while (it.next()) |run| if (run.value == job.owner) {
                    msg(void, storage, "addAttribute:value:range:", .{ key_ghost, yes, run.range });
                };
                it = .{ .key = key_lab_keep };
                while (it.next()) |run| if (run.value == job.owner) {
                    msg(void, storage, "removeAttribute:range:", .{ key_lab_keep, run.range });
                };
                msg(void, storage, "endEditing", .{});
            }
            disposeJob(job);
        } // if still in flight, landed() disposes it
    }
    showLab();
}

fn showLab() void {
    lab_ui.pending = if (reading) |job| if (job.pass.?.isTrim()) @intFromEnum(job.pass.?) else null else null;
    const j = reading orelse return lab_ui.update(tools, lab_message.items, false, false);
    const p = j.pass.?;
    var buf: [512]u8 = undefined;
    const hits = (j.hits orelse return lab_ui.update(tools, std.fmt.bufPrint(&buf, "{s} ยท Reading the draftโ€ฆ", .{p.title()}) catch "Readingโ€ฆ", false, false)).items;
    if (hits.len == 0) return lab_ui.update(tools, std.fmt.bufPrint(&buf, "{s} ยท No cuts to review", .{p.title()}) catch p.title(), false, false);
    const h = hits[j.current];
    const line = if (p.isTrim()) note: {
        var cut: usize = 0;
        for (hits) |v| cut += v.words;
        break :note std.fmt.bufPrint(&buf, "{s} ยท {d} โ†’ โ‰ˆ{d} words ยท cut {d} of {d}", .{ p.title(), j.words, j.words -| cut, j.current + 1, hits.len }) catch p.title();
    } else if (h.replacement) |s| std.fmt.bufPrint(&buf, "Fix {d}/{d}: โ€œ{s}โ€ โ†’ โ€œ{s}โ€", .{ j.current + 1, hits.len, textOf(h.range), s }) catch "Proposed correction" else std.fmt.bufPrint(&buf, "{s} ยท {d}/{d}  {s}", .{ p.title(), j.current + 1, hits.len, h.reason }) catch p.title();
    lab_ui.update(tools, line, true, p.isTrim() or p == .typos);
}

fn labMenu(_: id, _: SEL, _: id) callconv(.c) void {
    if (!tools) {
        tools = true;
        panels();
        refresh();
    }
    lab_ui.togglePanel();
}

fn validateMenuItem(_: id, _: SEL, menu_item: id) callconv(.c) bool {
    const action = msg(SEL, menu_item, "action", .{});
    if (action == objc.sel("labOriginal:")) return tools and reading != null;
    if (action == objc.sel("labNext:") or action == objc.sel("labKeep:") or action == objc.sel("labApply:")) {
        if (!tools) return false;
        const j = reading orelse return false;
        const hits = j.hits orelse return false;
        if (hits.items.len == 0) return false;
        return action != objc.sel("labApply:") or j.pass.?.isTrim() or j.pass.? == .typos;
    }
    return true;
}

fn labPass(_: id, _: SEL, sender: id) callconv(.c) void {
    const tag = msg(isize, sender, "tag", .{});
    if (tag < 0 or tag >= std.meta.fields(lab.Pass).len) return;
    const pass: lab.Pass = @enumFromInt(tag);
    if (len() == 0) return NSBeep();
    if (target != 0) closePanel();
    // All trim strengths use the same draft, response, and Keep marks.
    if (pass.isTrim()) if (reading) |old| if (old.pass.?.isTrim()) {
        if (old.pass.? == pass) return;
        if (old.hits == null) {
            old.pass = pass;
            return showLab();
        }
        _ = propose(old, pass, old.answer.text);
        return;
    };
    const job = gpa.create(Job) catch return;
    job.* = .{ .arena = .init(gpa), .seq = 0, .pass = pass };
    const a = job.arena.allocator();
    job.settings = loadSettings(a);
    if (!job.settings.ready()) {
        if (!configure()) return job.deinit();
        job.settings = loadSettings(a);
        if (!job.settings.ready()) return job.deinit();
    }
    job.draft = a.dupe(u8, objc.utf8(string(page))) catch return job.deinit();
    job.question = lab.question(a, pass, job.draft) catch return job.deinit();
    if (job.question.len == 0) {
        job.deinit();
        return alert("Nothing to read yet.", "Add a paragraph to the draft first.");
    }
    job.words = doc.countWords(job.draft);
    job.system = pass.prompt();
    labOriginal(null, null, null);
    reading = job;
    const thread = std.Thread.spawn(.{}, work, .{job}) catch {
        finishReview("Could not start the reading.");
        return job.deinit();
    };
    thread.detach();
    showLab();
}

/// On success ownership of the answer and its arena moves from the worker to the review.
fn receiveReview(j: *Job) bool {
    if (!std.mem.eql(u8, j.draft, objc.utf8(string(page)))) {
        finishReview("");
        return false;
    }
    const answer = switch (j.answer) {
        .text => |s| s,
        .failed => |s| {
            finishReview(s);
            return false;
        },
    };
    if (propose(j, j.pass.?, answer)) |note| {
        finishReview(note);
        return false;
    }
    return true;
}

/// Parse first, then replace only our own ghosts, in one undo step when switching strength.
fn propose(j: *Job, pass: lab.Pass, answer: []const u8) ?[]const u8 {
    var scratch: std.heap.ArenaAllocator = .init(gpa);
    defer scratch.deinit();
    const trim = pass.isTrim();
    const a = if (trim) scratch.allocator() else j.arena.allocator();
    const found = lab.parse(a, pass, j.draft, answer) catch return "Could not match the response to this draft.";
    var mapped: std.ArrayList(Hit) = .empty;
    findings: for (found) |f| {
        const r = utf16Range(j.draft, f.at, f.text.len);
        // Skip the whole cut if it intersects a comment, a manual ghost or a kept span.
        if (commentIn(r)) continue;
        var it: Runs = .{ .key = key_ghost, .at = r.location };
        while (it.next()) |run| {
            if (run.range.location >= end(r)) break;
            if (run.value != j.owner) continue :findings;
        }
        if (j.owner != null) {
            it = .{ .key = key_lab_keep, .at = r.location };
            while (it.next()) |run| {
                if (run.range.location >= end(r)) break;
                if (run.value == j.owner) continue :findings;
            }
        }
        mapped.append(a, .{ .range = r, .replacement = f.replacement, .reason = f.reason, .words = doc.countWords(f.text) }) catch return "Not enough memory to review the draft.";
    }
    if (mapped.items.len == 0 and j.hits == null) return "No matching passages to review.";
    j.pass = pass;
    j.current = 0;
    if (trim) {
        if (j.hits == null) j.hits = .empty;
        if (j.owner == null) j.owner = objc.new("NSUUID");
        lab_changing = true;
        defer lab_changing = false;
        const um = msg(id, page, "undoManager", .{});
        msg(void, page, "breakUndoCoalescing", .{});
        msg(void, um, "beginUndoGrouping", .{});
        defer msg(void, um, "endUndoGrouping", .{});
        clearProposal(j.owner);
        for (mapped.items) |h| mark(h.range, key_ghost, j.owner);
    } else j.hits = mapped;
    revealHit();
    return null;
}

fn clearProposal(owner: id) void {
    var it: Runs = .{ .key = key_ghost };
    while (it.next()) |run| if (run.value == owner) mark(run.range, key_ghost, null);
}

fn validateReading() void {
    if (lab_changing) return;
    const j = reading orelse return;
    if (!std.mem.eql(u8, j.draft, objc.utf8(string(page)))) return finishReview("");
    const hits = if (j.hits) |*h| h else return;
    if (j.owner == null) {
        for (hits.items) |h| if (ghostIn(h.range)) return finishReview("");
        return;
    }
    // Cocoa undo restores attributes, not the card's list. Derive that list from the
    // live proposal runs so an undone Keep (or redone one) is immediately reflected.
    var it: Runs = .{ .key = key_ghost };
    var n: usize = 0;
    var changed = false;
    while (it.next()) |run| {
        if (run.value != j.owner) continue;
        if (n == hits.items.len) {
            hits.append(j.arena.allocator(), undefined) catch return finishReview("Not enough memory to review the draft.");
        } else if (std.meta.eql(hits.items[n].range, run.range)) {
            n += 1;
            continue;
        }
        hits.items[n] = .{ .range = run.range, .replacement = null, .reason = "", .words = doc.countWords(textOf(run.range)) };
        changed = true;
        n += 1;
    }
    changed = changed or n != hits.items.len;
    hits.shrinkRetainingCapacity(n);
    j.current = if (n == 0) 0 else j.current % n;
    if (changed) showLab();
}

fn drawReview() void {
    const j = reading orelse return;
    const hits = (j.hits orelse return).items;
    if (!tools or lab_changing) return;
    for (hits, 0..) |h, i| {
        if (!j.pass.?.isTrim()) {
            tint(NSUnderlineStyleAttributeName, number(1), h.range);
            tint(NSUnderlineColorAttributeName, color.sentence, h.range);
        }
        if (i == j.current) tint(NSBackgroundColorAttributeName, color.hover, h.range);
    }
}

fn revealHit() void {
    refresh();
    showLab();
    const j = reading orelse return;
    const hits = (j.hits orelse return).items;
    if (hits.len == 0) return;
    const range = hits[j.current].range;
    const container = msg(id, page, "textContainer", .{});
    msg(void, layout, "ensureLayoutForCharacterRange:", .{range});
    const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ range, @as(?*NSRange, null) });
    const rect = msg(NSRect, layout, "boundingRectForGlyphRange:inTextContainer:", .{ glyphs, container });
    const top = rect.origin.y + msg(NSPoint, page, "textContainerOrigin", .{}).y;
    const visible = msg(NSRect, page, "visibleRect", .{});
    // The Lab card starts 12 points above the scroll view's foot, and is 80 high.
    const clearance: f64 = if (tools) 12 + 80 + 4 else 0;
    const height = @max(1, visible.size.height - clearance);
    const y = @min(top, @max(visible.origin.y, top + rect.size.height - height));
    if (y != visible.origin.y) msg(void, page, "scrollPoint:", .{NSPoint{ .x = visible.origin.x, .y = y }});
}

fn labNext(_: id, _: SEL, _: id) callconv(.c) void {
    const j = reading orelse return;
    const hits = (j.hits orelse return).items;
    if (hits.len == 0) return;
    j.current = (j.current + 1) % hits.len;
    revealHit();
}

fn labKeep(_: id, _: SEL, _: id) callconv(.c) void {
    const j = reading orelse return;
    const hits = if (j.hits) |*h| h else return;
    if (hits.items.len == 0) return;
    if (j.owner != null) {
        const r = hits.items[j.current].range;
        // One attributed undo entry: Undo both restores the ghost and unskips its span.
        msg(void, page, "breakUndoCoalescing", .{});
        if (!msg(bool, page, "shouldChangeTextInRange:replacementString:", .{ r, @as(id, null) })) return;
        msg(void, storage, "beginEditing", .{});
        msg(void, storage, "removeAttribute:range:", .{ key_ghost, r });
        msg(void, storage, "addAttribute:value:range:", .{ key_lab_keep, j.owner, r });
        msg(void, storage, "endEditing", .{});
        msg(void, page, "didChangeText", .{});
    } else {
        _ = hits.orderedRemove(j.current);
        if (hits.items.len == 0) {
            finishReview("");
        } else j.current %= hits.items.len;
    }
    revealHit();
}

fn labOriginal(_: id, _: SEL, _: id) callconv(.c) void {
    if (reading) |j| if (j.owner != null) {
        const um = msg(id, page, "undoManager", .{});
        msg(void, page, "breakUndoCoalescing", .{});
        msg(void, um, "beginUndoGrouping", .{});
        lab_changing = true;
        clearProposal(j.owner);
        lab_changing = false;
        msg(void, um, "endUndoGrouping", .{});
    };
    finishReview("");
    refresh();
}

fn labApply(_: id, _: SEL, _: id) callconv(.c) void {
    validateReading();
    const j = reading orelse return;
    const hits = (j.hits orelse return).items;
    if (hits.len == 0 or (!j.pass.?.isTrim() and j.pass.? != .typos)) return;
    reading = null; // the first edit invalidates the review; keep the ranges until we're done
    const um = msg(id, page, "undoManager", .{});
    msg(void, page, "breakUndoCoalescing", .{});
    msg(void, um, "beginUndoGrouping", .{});
    var i = hits.len;
    while (i > 0) {
        i -= 1;
        replace(hits[i].range, hits[i].replacement orelse "", null);
    }
    msg(void, um, "endUndoGrouping", .{});
    reading = j;
    finishReview("");
    refresh();
}

/// Both model features share one worker path and the same inference settings.
fn work(job: *Job) void {
    job.answer = ai.ask(gpa, io, job.settings, job.system, job.question);
    dispatch_async_f(&_dispatch_main_q, job, &landed);
}

fn landed(context: ?*anyopaque) callconv(.c) void {
    const job: *Job = @ptrCast(@alignCast(context));
    if (job.pass != null) {
        if (reading == job and receiveReview(job)) return; // the review now owns this job
        return disposeJob(job);
    }
    defer job.deinit();
    defer switch (job.answer) {
        inline else => |bytes| gpa.free(bytes),
    };
    if (job.seq != ask_seq or asking != target) return; // the panel has moved on
    land(job.answer);
}

/// The AI's answer goes into the panel where the "??" was, one suggestion to a row. What
/// the page shows does not change: these are only more to choose from. The answer stays
/// the caller's.
fn land(answer: ai.Answer) void {
    asking = 0;
    const g = groups.getPtr(target) orelse return;
    const row = askRow() orelse return hint("");
    const text = switch (answer) {
        .text => |t| t,
        .failed => |why| return unask(if (why.len > 0) why else "The AI did not answer."),
    };
    var rows: std.ArrayList(u8) = .empty;
    defer rows.deinit(gpa);
    var added: usize = 0;
    var lines = std.mem.splitScalar(u8, text, '\n');
    while (lines.next()) |line| {
        const s = doc.suggestion(line) orelse continue;
        if (added == wanted(g.scope)) break;
        if (g.isAI(s)) continue; // twice in one answer, or suggested before and thrown out
        var have = false;
        for (g.variants.items) |v| have = have or std.mem.eql(u8, v, s);
        if (have) continue;
        g.markAI(gpa, s) catch continue;
        rows.print(gpa, "{s}{s}", .{ if (added > 0) "\n" else "", s }) catch continue;
        added += 1;
    }
    if (added == 0) return unask("The AI had nothing to add.");

    var above: usize = 0; // variants over the "??" row
    var it = Rows.init();
    while (it.next()) |r| {
        if (r.asks) break;
        if (r.variant != null) above += 1;
    }
    const showing = g.active + (if (g.active >= above) added else 0);
    filling = true;
    insert(alts, rows.items, row);
    if (rowOf(showing)) |r| msg(void, alts, "setSelectedRange:", .{NSRange{ .location = end(r) }});
    filling = false;
    hint("");
    pull();
}

/// Take the "??" out of its row, and say why at the foot of the panel.
fn unask(note: []const u8) void {
    asking = 0;
    if (askRow()) |row| {
        filling = true;
        insert(alts, "", row);
        filling = false;
    }
    hint(note);
}

/// "??" with no model to ask: offer the dialog, then ask, or take the "??" away.
fn needInference(_: id, _: SEL, _: id) callconv(.c) void {
    asking = 0;
    if (configure()) pull() else unask("No model to ask. See Write_Away โ–ธ Inferenceโ€ฆ");
}

fn inference(_: id, _: SEL, _: id) callconv(.c) void {
    _ = configure();
}

fn supportDir(arena: std.mem.Allocator) []const u8 {
    return std.fmt.allocPrint(arena, "{s}/Library/Application Support/Write_Away", .{objc.utf8(NSHomeDirectory())}) catch "";
}

/// Which model to ask is in the user defaults. The key is not: see `ai.loadKey`.
fn loadSettings(arena: std.mem.Allocator) ai.Settings {
    const d = msg(id, objc.class("NSUserDefaults"), "standardUserDefaults", .{});
    const get = struct {
        fn f(a: std.mem.Allocator, defaults: id, key: []const u8) []const u8 {
            return a.dupe(u8, objc.utf8(msg(id, defaults, "stringForKey:", .{str(key)}))) catch "";
        }
    }.f;
    const style = std.meta.stringToEnum(ai.Style, get(arena, d, "InferenceStyle")) orelse .anthropic_messages;
    const url = get(arena, d, "InferenceBaseURL");
    return .{
        .style = style,
        .base_url = if (url.len > 0) url else ai.style_urls[@intFromEnum(style)],
        .model = get(arena, d, "InferenceModel"),
        .api_key = ai.loadKey(arena, io, supportDir(arena)),
    };
}

/// Write_Away โ–ธ Inferenceโ€ฆ: which model the AI features ask, and the key to ask it with.
/// True if it was saved with everything an asking needs.
fn configure() bool {
    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const s = loadSettings(arena);

    const a = msg(id, objc.new("NSAlert"), "autorelease", .{});
    msg(void, a, "setMessageText:", .{str("Inference")});
    msg(void, a, "setInformativeText:", .{str("The AI features ask this model, and nothing leaves the Mac until you ask. The key is kept in a file only your account can read, in ~/Library/Application Support/Write_Away.")});
    for ([_][]const u8{ "Save", "Cancel" }) |title| _ = msg(id, a, "addButtonWithTitle:", .{str(title)});

    const row = 30;
    const label_w = 76;
    const field: NSRect = .{ .origin = .{ .x = label_w + 8 }, .size = .{ .width = 300, .height = 22 } };
    const box = msg(id, msg(id, msg(id, objc.class("NSView"), "alloc", .{}), "initWithFrame:", .{NSRect{ .size = .{ .width = end_x(field), .height = 4 * row } }}), "autorelease", .{});
    inf_style = msg(id, msg(id, msg(id, objc.class("NSPopUpButton"), "alloc", .{}), "initWithFrame:pullsDown:", .{ field, false }), "autorelease", .{});
    for (ai.style_names) |name| msg(void, inf_style, "addItemWithTitle:", .{str(name)});
    msg(void, inf_style, "selectItemAtIndex:", .{@as(isize, @intFromEnum(s.style))});
    msg(void, inf_style, "setTarget:", .{ctl});
    msg(void, inf_style, "setAction:", .{objc.sel("styleChanged:")});
    inf_url = msg(id, objc.class("NSTextField"), "textFieldWithString:", .{str(s.base_url)});
    const model = msg(id, objc.class("NSTextField"), "textFieldWithString:", .{str(s.model)});
    msg(void, model, "setPlaceholderString:", .{str("the provider's name for the model")});
    const key = msg(id, msg(id, msg(id, objc.class("NSSecureTextField"), "alloc", .{}), "initWithFrame:", .{field}), "autorelease", .{});
    msg(void, key, "setStringValue:", .{str(s.api_key)});
    for ([_]id{ inf_style, inf_url, model, key }, [_][]const u8{ "API style", "Base URL", "Model", "API key" }, 0..) |view, name, i| {
        const y: f64 = @floatFromInt((3 - i) * row);
        const label = msg(id, objc.class("NSTextField"), "labelWithString:", .{str(name)});
        msg(void, label, "setFrame:", .{NSRect{ .origin = .{ .y = y + 3 }, .size = .{ .width = label_w, .height = 18 } }});
        msg(void, view, "setFrame:", .{NSRect{ .origin = .{ .x = field.origin.x, .y = y }, .size = field.size }});
        msg(void, box, "addSubview:", .{label});
        msg(void, box, "addSubview:", .{view});
    }
    msg(void, a, "setAccessoryView:", .{box});
    const saved: isize = 1000; // the first button
    if (msg(isize, a, "runModal", .{}) != saved) return false;

    const style: ai.Style = @enumFromInt(msg(isize, inf_style, "indexOfSelectedItem", .{}));
    const new: ai.Settings = .{
        .style = style,
        .base_url = std.mem.trim(u8, objc.utf8(msg(id, inf_url, "stringValue", .{})), " /"),
        .model = std.mem.trim(u8, objc.utf8(msg(id, model, "stringValue", .{})), " "),
        .api_key = std.mem.trim(u8, objc.utf8(msg(id, key, "stringValue", .{})), " \n"),
    };
    const d = msg(id, objc.class("NSUserDefaults"), "standardUserDefaults", .{});
    msg(void, d, "setObject:forKey:", .{ str(@tagName(new.style)), str("InferenceStyle") });
    msg(void, d, "setObject:forKey:", .{ str(new.base_url), str("InferenceBaseURL") });
    msg(void, d, "setObject:forKey:", .{ str(new.model), str("InferenceModel") });
    ai.saveKey(gpa, io, supportDir(arena), new.api_key) catch |err| {
        alert("The key could not be saved.", @errorName(err));
        return false;
    };
    return new.ready();
}

fn end_x(r: NSRect) f64 {
    return r.origin.x + r.size.width;
}

/// Another dialect in the inference dialog: its own provider's URL, unless one was typed.
fn styleChanged(_: id, _: SEL, _: id) callconv(.c) void {
    const typed = objc.utf8(msg(id, inf_url, "stringValue", .{}));
    for (ai.style_urls) |url| if (typed.len == 0 or std.mem.eql(u8, typed, url)) {
        const style: usize = @intCast(msg(isize, inf_style, "indexOfSelectedItem", .{}));
        return msg(void, inf_url, "setStringValue:", .{str(ai.style_urls[style])});
    };
}

// --- Files ----------------------------------------------------------------------------------

fn load(bytes: []const u8) void {
    finishReview("");
    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    defer arena_state.deinit();
    const f = doc.parse(arena_state.allocator(), bytes) catch doc.File{ .body = bytes };

    for (groups.values()) |*g| g.deinit(gpa);
    groups.clearRetainingCapacity();
    msg(void, pictures, "removeAllObjects", .{}); // opening again reads them again
    hover = 0;
    target = 0;
    home.clearRetainingCapacity();

    msg(void, page, "setString:", .{str(f.body)});
    msg(void, storage, "setAttributes:range:", .{ base_attrs, NSRange{ .length = len() } });
    for (f.groups) |rec| {
        var g = doc.Group.init(gpa, rec.scope, rec.variants, rec.active) catch continue;
        if (rec.ai) |suggested| for (suggested) |text| g.markAI(gpa, text) catch {};
        groups.put(gpa, next_id, g) catch {
            g.deinit(gpa);
            continue;
        };
        msg(void, storage, "addAttribute:value:range:", .{ key_group, number(next_id), utf16Range(f.body, rec.at, g.shown().len) });
        next_id += 1;
    }
    for (f.ghosts) |rec| msg(void, storage, "addAttribute:value:range:", .{ key_ghost, yes, utf16Range(f.body, rec.at, rec.text.len) });
    msg(void, over, "setString:", .{str(f.overflow)});

    msg(void, msg(id, page, "undoManager", .{}), "removeAllActions", .{});
    select(.{});
    msg(void, page, "scrollPoint:", .{NSPoint{}});
    // A ghost that went to Overflow goes there in the file too, with the next save.
    setDirty(f.displaced);
    if (f.displaced) {
        overflow_open = true;
        tools = true;
        finishReview(displaced_note);
    }
    panels();
    typing();
    refresh();
}

const displaced_note = "The file was edited elsewhere: ghosts with no clear place are now in Overflow";

fn utf16Range(body: []const u8, at: usize, byte_len: usize) NSRange {
    return .{ .location = doc.utf16Len(body[0..at]), .length = doc.utf16Len(body[at..][0..byte_len]) };
}

/// The file as Save would write it.
fn snapshot(arena: std.mem.Allocator) ![]u8 {
    const body = objc.utf8(string(page));
    var recs: std.ArrayList(doc.GroupRec) = .empty;
    var it: Runs = .{ .key = key_group };
    while (it.next()) |run| {
        const g = groups.getPtr(idOf(run.value)) orelse continue;
        if (g.variants.items.len < 2) continue; // a group of one is just text
        var suggested: std.ArrayList([]const u8) = .empty;
        for (g.variants.items) |v| if (g.isAI(v)) try suggested.append(arena, v);
        try recs.append(arena, .{
            .scope = g.scope,
            .at = doc.utf8Index(body, run.range.location),
            .active = g.active,
            .variants = g.variants.items,
            .ai = if (suggested.items.len > 0) suggested.items else null,
        });
    }
    var ghosts: std.ArrayList(doc.GhostRec) = .empty;
    it = .{ .key = key_ghost };
    while (it.next()) |run| {
        try ghosts.append(arena, .{ .at = doc.utf8Index(body, run.range.location), .text = try arena.dupe(u8, textOf(run.range)) });
    }
    return doc.serialize(arena, .{ .body = body, .overflow = objc.utf8(string(over)), .groups = recs.items, .ghosts = ghosts.items });
}

fn setPath(path: ?[]const u8) void {
    const moved = if (path) |p| (if (file_path) |old| !std.mem.eql(u8, old, p) else true) else file_path != null;
    defer if (moved) { // pictures are found from where the piece is
        markdown_dirty = .{ .length = len() };
        markdownRefresh();
    };
    const new = if (path) |p| gpa.dupe(u8, p) catch null else null;
    if (file_path) |old| gpa.free(old);
    file_path = new;
    if (new) |p| {
        msg(void, window, "setTitleWithRepresentedFilename:", .{str(p)});
        msg(void, document_defaults, "setObject:forKey:", .{ str(p), str(last_document) });
    } else {
        msg(void, document_defaults, "removeObjectForKey:", .{str(last_document)});
        msg(void, window, "setRepresentedFilename:", .{str("")});
        msg(void, window, "setTitle:", .{str("Untitled")});
    }
}

fn readPath(path: []const u8) error{ Unreadable, NotUtf8 }!void {
    const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)}) orelse return error.Unreadable;
    const n = msg(usize, data, "length", .{});
    const bytes: []const u8 = if (n == 0) "" else msg([*]const u8, data, "bytes", .{})[0..n];
    if (!std.unicode.utf8ValidateSlice(bytes)) return error.NotUtf8;
    load(bytes);
    setPath(path);
}

fn openPath(path: []const u8) bool {
    readPath(path) catch |err| {
        alert(switch (err) {
            error.Unreadable => "That file could not be read.",
            error.NotUtf8 => "That file is not UTF-8 text.",
        }, path);
        return false;
    };
    return true;
}

fn startDraft() void {
    // An explicit Open is authoritative, even if AppKit delivered it during launch.
    if (!received_open) {
        const path = objc.utf8(msg(id, document_defaults, "stringForKey:", .{str(last_document)}));
        if (path.len != 0) {
            if (readPath(path)) return else |_| {} // A stale preference isn't an Open error.
        }
    } else if (file_path != null) return;
    load("");
    setPath(null);
}

fn save(ask: bool) bool {
    var to: []const u8 = file_path orelse "";
    if (ask or to.len == 0) {
        const panel = msg(id, objc.class("NSSavePanel"), "savePanel", .{});
        if (to.len == 0) msg(void, panel, "setNameFieldStringValue:", .{str("Untitled.md")});
        const ok: isize = 1;
        if (msg(isize, panel, "runModal", .{}) != ok) return false;
        to = objc.utf8(msg(id, msg(id, panel, "URL", .{}), "path", .{}));
    }
    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    defer arena_state.deinit();
    const bytes = snapshot(arena_state.allocator()) catch {
        alert("The piece could not be saved.", "Out of memory.");
        return false;
    };
    const data = msg(id, objc.class("NSData"), "dataWithBytes:length:", .{ bytes.ptr, bytes.len });
    if (!msg(bool, data, "writeToFile:atomically:", .{ str(to), true })) {
        alert("The piece could not be saved.", to);
        return false;
    }
    setPath(to);
    setDirty(false);
    if (std.mem.eql(u8, lab_message.items, displaced_note)) finishReview("");
    return true;
}

/// Unsaved work is never dropped without asking.
fn mayDiscard() bool {
    if (!msg(bool, window, "isDocumentEdited", .{})) return true;
    const a = msg(id, objc.new("NSAlert"), "autorelease", .{});
    msg(void, a, "setMessageText:", .{str("Save the changes to this piece?")});
    msg(void, a, "setInformativeText:", .{str("They will be lost if you don't.")});
    for ([_][]const u8{ "Save", "Cancel", "Don't Save" }) |title| _ = msg(id, a, "addButtonWithTitle:", .{str(title)});
    switch (msg(isize, a, "runModal", .{})) {
        1000 => return save(false),
        1002 => {
            setDirty(false);
            return true;
        },
        else => return false,
    }
}

fn newDoc(_: id, _: SEL, _: id) callconv(.c) void {
    if (!mayDiscard()) return;
    load("");
    setPath(null);
}

fn openDoc(_: id, _: SEL, _: id) callconv(.c) void {
    if (!mayDiscard()) return;
    const panel = msg(id, objc.class("NSOpenPanel"), "openPanel", .{});
    const ok: isize = 1;
    if (msg(isize, panel, "runModal", .{}) != ok) return;
    _ = openPath(objc.utf8(msg(id, msg(id, panel, "URL", .{}), "path", .{})));
}

fn saveDoc(_: id, _: SEL, _: id) callconv(.c) void {
    _ = save(false);
}

fn saveDocAs(_: id, _: SEL, _: id) callconv(.c) void {
    _ = save(true);
}

// --- Delegates ------------------------------------------------------------------------------

fn textDidChange(_: id, _: SEL, note: id) callconv(.c) void {
    const view = msg(id, note, "object", .{});
    if (view == alts) return pull();
    setDirty(true);
    if (view != page) return;
    refresh();
    rehome(); // undo heard this one
}

fn selectionDidChange(_: id, _: SEL, note: id) callconv(.c) void {
    const view = msg(id, note, "object", .{});
    if (view == alts) return pull();
    if (view != page) return;
    markdownRefresh();
    typing();
    status();
}

/// The keyboard has left the alternatives panel: the page's undo hears what the visit did.
fn editingEnded(_: id, _: SEL, note: id) callconv(.c) void {
    if (msg(id, note, "object", .{}) == alts) settle();
}

/// Return and Esc in the alternatives panel.
fn doCommand(_: id, _: SEL, view: id, command: SEL) callconv(.c) bool {
    if (view != alts) return false;
    if (command == objc.sel("insertNewline:")) {
        newRow();
    } else if (command == objc.sel("cancelOperation:") or command == objc.sel("complete:")) {
        closePanel();
    } else return false;
    return true;
}

fn undoFor(_: id, _: SEL, view: id) callconv(.c) id {
    return if (view == alts) alts_undo else null; // null: the window's, as ever
}

/// Keep the 65-character column centered in whatever width there is. It narrows, and the
/// text reflows, only when the window is too small for it, and it steps aside only when
/// the alternatives panel would otherwise lie over it.
fn resized(_: id, _: SEL, _: id) callconv(.c) void {
    const w = msg(NSSize, scroll, "contentSize", .{}).width;
    const least: f64 = if (target != 0) panel_w + margin else margin;
    const column = @max(200, @min(column_w, w - least - margin));
    const container = msg(id, page, "textContainer", .{});
    const inset: NSSize = .{ .width = @max(least, (w - column) / 2), .height = top_inset };
    const reflow = msg(NSSize, container, "containerSize", .{}).width != column;
    if (!reflow and std.meta.eql(inset, msg(NSSize, page, "textContainerInset", .{}))) return;
    if (reflow) {
        msg(void, container, "setContainerSize:", .{NSSize{ .width = column, .height = 1e7 }});
        refitPictures();
    }
    msg(void, page, "setTextContainerInset:", .{inset});
    // Moving the column does not move AppKit's blinking insertion indicator with it.
    msg(void, page, "updateInsertionPointStateAndRestartTimer:", .{false});
}

fn windowShouldClose(_: id, _: SEL, _: id) callconv(.c) bool {
    return mayDiscard();
}

fn shouldTerminate(_: id, _: SEL, _: id) callconv(.c) usize {
    return @intFromBool(mayDiscard()); // NSTerminateNow, or NSTerminateCancel
}

fn quitWithWindow(_: id, _: SEL, _: id) callconv(.c) bool {
    return true;
}

/// Finder, `open` and a path on the command line all arrive here, the last by AppKit's own
/// reading of the arguments. A path with no file yet starts a piece that will save there.
fn openFile(_: id, _: SEL, _: id, path: id) callconv(.c) bool {
    received_open = true;
    if (!mayDiscard()) return false;
    const full = msg(id, msg(id, objc.class("NSURL"), "fileURLWithPath:", .{path}), "path", .{});
    if (msg(bool, msg(id, objc.class("NSFileManager"), "defaultManager", .{}), "fileExistsAtPath:", .{full})) return openPath(objc.utf8(full));
    load("");
    setPath(objc.utf8(full));
    return true;
}

// --- The page's own behavior ----------------------------------------------------------------

fn keyDown(self: id, _: SEL, event: id) callconv(.c) void {
    const key = msg(u16, event, "keyCode", .{});
    const plain = msg(usize, event, "modifierFlags", .{}) & (Mod.shift | Mod.ctrl | Mod.opt | Mod.cmd) == 0;
    const Key = struct {
        const enter = 36;
        const backspace = 51;
        const escape = 53;
        const delete = 117;
        const left = 123;
        const right = 124;
        const down = 125;
        const up = 126;
    };

    const sel = selection();
    if (target != 0 and plain and key == Key.escape) return closePanel();
    if (armed and hover != 0 and plain and sel.length == 0) switch (key) {
        Key.left, Key.up => return flip(hover, -1),
        Key.right, Key.down => return flip(hover, 1),
        Key.backspace, Key.delete => return removeShown(hover),
        else => {},
    };
    if (armed) { // typing takes the arrow keys back for the caret
        armed = false;
        if (hover != 0) refresh();
    }
    objc.msgSuper(void, self, "NSTextView", "keyDown:", .{event});
}

/// While the alternatives panel is open, a click on the page moves it to what was clicked.
fn mouseDown(self: id, _: SEL, event: id) callconv(.c) void {
    objc.msgSuper(void, self, "NSTextView", "mouseDown:", .{event}); // returns when the button is let go
    if (target != 0 and selection().length == 0) _ = aimHere();
}

/// The right-click menu. A click inside the selection is about the selection; anywhere
/// else it puts the caret there and is about the word under it.
fn contextMenu(self: id, _: SEL, event: id) callconv(.c) id {
    if (!tools) return objc.msgSuper(id, self, "NSTextView", "menuForEvent:", .{event});
    if (!lab_ui.canOpenWritingMenu()) return null;
    const point = msg(NSPoint, event, "locationInWindow", .{});
    const hit = charUnder(event);
    const before = selection();
    if (hit == null or hit.? < before.location or hit.? >= end(before)) {
        const local = msg(NSPoint, self, "convertPoint:fromView:", .{ point, @as(id, null) });
        select(.{ .location = hit orelse msg(usize, self, "characterIndexForInsertionAtPoint:", .{local}) });
    }
    const subject = selection();
    var buf: [2][160]u8 = undefined;
    lab_ui.openWritingMenu(point, .{
        menuTitle(&buf[0], "Alternatives"),
        menuTitle(&buf[1], "AI alternatives"),
        if (ghostIn(ghostable()) or commentIn(ghostable())) "Revive it" else "Ghost it",
        "Stash this in Overflow",
    });
    // Leaving an edited alternatives panel can settle it and move the page selection.
    if (!std.meta.eql(selection(), subject)) select(subject);
    return null;
}

fn menuTitle(buf: []u8, lead: []const u8) []const u8 {
    const sel = selection();
    if (sel.length > 0) return std.fmt.bufPrint(buf, "{s} for selection", .{lead}) catch lead;
    return std.fmt.bufPrint(buf, "{s} for โ€œ{s}โ€", .{ lead, textOf(trimmed(wordAt(sel.location))) }) catch lead;
}

fn mouseMoved(self: id, _: SEL, event: id) callconv(.c) void {
    objc.msgSuper(void, self, "NSTextView", "mouseMoved:", .{event});
    const was = if (armed) hover else 0;
    hover = if (tools) groupUnder(event) else 0;
    armed = true;
    if (hover == was) return;
    if (tick_gid != target) tick_gid = 0; // the pointer has left what it was playing with
    refresh();
}

fn groupUnder(event: id) u32 {
    const run = runAt(key_group, charUnder(event) orelse return 0) orelse return 0;
    return idOf(run.value);
}

/// The character the pointer is on, if it is on one.
fn charUnder(event: id) ?usize {
    if (len() == 0) return null;
    var p = msg(NSPoint, page, "convertPoint:fromView:", .{ msg(NSPoint, event, "locationInWindow", .{}), @as(id, null) });
    const origin = msg(NSPoint, page, "textContainerOrigin", .{});
    p.x -= origin.x;
    p.y -= origin.y;
    const container = msg(id, page, "textContainer", .{});
    const glyph = msg(usize, layout, "glyphIndexForPoint:inTextContainer:", .{ p, container });
    const box = msg(NSRect, layout, "boundingRectForGlyphRange:inTextContainer:", .{ NSRange{ .location = glyph, .length = 1 }, container });
    if (p.x < box.origin.x or p.x > box.origin.x + box.size.width or p.y < box.origin.y or p.y > box.origin.y + box.size.height) return null;
    return msg(usize, layout, "characterIndexForGlyphAtIndex:", .{glyph});
}

fn paste(self: id, _: SEL, sender: id) callconv(.c) void {
    msg(void, self, "pasteAsPlainText:", .{sender});
}

/// Under the text: a bar beside each paragraph group, and a dot for every variant of every
/// group, the showing one filled in.
fn drawBackground(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
    objc.msgSuper(void, self, "NSTextView", "drawViewBackgroundInRect:", .{dirty});
    const origin = msg(NSPoint, self, "textContainerOrigin", .{});
    const container = msg(id, self, "textContainer", .{});
    // Behind each fenced block, from its opening fence to its closing one, a panel as wide
    // as the column. The fences' own lines are its padding while they are out of sight.
    var fences: Runs = .{ .key = key_fence };
    while (fences.next()) |run| {
        const stop = end(paragraphOf(page, .{ .location = end(run.range) }));
        const lines = linesOf(markdownRange(run.range.location, stop)) orelse continue;
        const pad = 14;
        const box: NSRect = .{
            .origin = .{ .x = lines.origin.x - pad, .y = lines.origin.y - line_gap / 2 },
            .size = .{ .width = lines.size.width + 2 * pad, .height = lines.size.height },
        };
        msg(void, color.code, "setFill", .{});
        msg(void, msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ box, @as(f64, 8), @as(f64, 8) }), "fill", .{});
    }
    // Where a rule's source is out of sight, a line across the column at the height of its text. And
    // down the side of quoted lines a bar, where each ">" would be.
    msg(void, color.ring, "setFill", .{});
    const padding = msg(f64, container, "lineFragmentPadding", .{});
    var rules: Runs = .{ .key = key_rule };
    while (rules.next()) |run| {
        var at = run.range.location;
        while (at < end(run.range)) {
            const para = paragraphOf(page, .{ .location = at });
            at = end(para);
            const line = linesOf(para) orelse continue;
            NSRectFill(.{
                .origin = .{ .x = line.origin.x + padding, .y = line.origin.y + @floor((line.size.height - line_gap) / 2) },
                .size = .{ .width = line.size.width - 2 * padding, .height = 1 },
            });
        }
    }
    var quotes: Runs = .{ .key = key_quote };
    while (quotes.next()) |run| {
        const lines = linesOf(run.range) orelse continue;
        NSRectFill(.{ .origin = .{ .x = lines.origin.x + padding + 2, .y = lines.origin.y }, .size = .{ .width = 3, .height = lines.size.height - line_gap } });
    }
    // Each picture, in the room its line was given: see `pictureStyle`.
    var shown: Runs = .{ .key = key_picture };
    while (shown.next()) |run| {
        var at = run.range.location; // the same picture twice running is one run
        while (at < end(run.range)) {
            const para = paragraphOf(page, .{ .location = at });
            at = end(para);
            const line = linesOf(para) orelse continue;
            const box: NSRect = .{ .origin = .{ .x = line.origin.x + padding, .y = line.origin.y }, .size = pictureSize(run.value) };
            if (box.origin.y > dirty.origin.y + dirty.size.height or box.origin.y + box.size.height < dirty.origin.y) continue;
            const source_over: usize = 2;
            msg(void, run.value, "drawInRect:fromRect:operation:fraction:respectFlipped:hints:", .{ box, NSRect{}, source_over, @as(f64, 1), true, @as(id, null) });
        }
    }
    if (!tools) return;
    var it: Runs = .{ .key = key_group };
    while (it.next()) |run| {
        const g = groups.getPtr(idOf(run.value)) orelse continue;
        const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ run.range, @as(?*NSRange, null) });
        var box = msg(NSRect, layout, "boundingRectForGlyphRange:inTextContainer:", .{ glyphs, container });
        box.origin.x += origin.x;
        box.origin.y += origin.y;

        const pitch = 6;
        const span = pitch * @as(f64, @floatFromInt(g.variants.items.len)) - 3;
        var last = box; // the part of it on its last line
        var line_y: f64 = 0;
        if (g.scope == .paragraph) {
            msg(void, color.bar, "setFill", .{});
            NSRectFill(.{ .origin = .{ .x = box.origin.x - 19, .y = box.origin.y }, .size = .{ .width = 2, .height = box.size.height - line_gap } });
        } else {
            // The pen line, under each line the group runs over. A sentence's is lower, and
            // stops short of its dots.
            var at = glyphs.location;
            while (at < end(glyphs)) {
                var line: NSRange = .{};
                _ = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ at, &line });
                const piece: NSRange = .{ .location = at, .length = @min(end(line), end(glyphs)) - at };
                at = end(piece);
                last = msg(NSRect, layout, "boundingRectForGlyphRange:inTextContainer:", .{ piece, container });
                last.origin.x += origin.x;
                last.origin.y += origin.y;
                line_y = last.origin.y + last.size.height - line_gap + @as(f64, if (g.scope == .sentence) 5 else -1);
                const short: f64 = if (g.scope == .sentence and at == end(glyphs)) span + 3 else 0;
                pen(last.origin.x, last.origin.x + last.size.width - short, line_y, idOf(run.value), if (g.scope == .sentence) color.sentence_line else color.word_line);
            }
        }
        // Dots: beside the bar for a paragraph, centered under a word, and at the end of a
        // sentence's line.
        for (0..g.variants.items.len) |i| {
            const step = pitch * @as(f64, @floatFromInt(i));
            const at: NSPoint = switch (g.scope) {
                .paragraph => .{ .x = box.origin.x - 28, .y = box.origin.y + (box.size.height - line_gap - span) / 2 + step },
                .sentence => .{ .x = last.origin.x + last.size.width - span + step, .y = line_y - 2 },
                .word => .{ .x = last.origin.x + (last.size.width - span) / 2 + step, .y = line_y + 4 },
            };
            msg(void, if (i == g.active) scopeColor(g.scope) else color.ring, "setFill", .{});
            const dot = msg(id, objc.class("NSBezierPath"), "bezierPathWithOvalInRect:", .{NSRect{ .origin = at, .size = .{ .width = 3, .height = 3 } }});
            msg(void, dot, "fill", .{});
        }
    }
}

/// The lines of the page that `r` runs over, as one box in the page's coordinates.
fn linesOf(r: NSRange) ?NSRect {
    const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ r, @as(?*NSRange, null) });
    if (glyphs.length == 0) return null;
    const origin = msg(NSPoint, page, "textContainerOrigin", .{});
    const top = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ glyphs.location, @as(?*NSRange, null) });
    const bottom = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ end(glyphs) - 1, @as(?*NSRange, null) });
    return .{
        .origin = .{ .x = origin.x + top.origin.x, .y = origin.y + top.origin.y },
        .size = .{ .width = top.size.width, .height = bottom.origin.y + bottom.size.height - top.origin.y },
    };
}

/// Beside each row of the alternatives panel, its marker: a disc for the variant showing,
/// a speck for the others, a box for one the AI wrote.
fn drawRows(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
    objc.msgSuper(void, self, "NSTextView", "drawViewBackgroundInRect:", .{dirty});
    const g = groups.getPtr(target) orelse return;
    const lm = msg(id, self, "layoutManager", .{});
    const origin = msg(NSPoint, self, "textContainerOrigin", .{});
    const n = msg(usize, string(self), "length", .{});
    const NSBezierPath = objc.class("NSBezierPath");
    // Not the fragment's height: the last row has no spacing under it, the others do.
    const tall = msg(f64, lm, "defaultLineHeightForFont:", .{msg(id, self, "font", .{})});
    var it = Rows.init();
    while (it.next()) |row| {
        const line = if (row.range.location < n)
            msg(NSRect, lm, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ msg(usize, lm, "glyphIndexForCharacterAtIndex:", .{row.range.location}), @as(?*NSRange, null) })
        else
            msg(NSRect, lm, "extraLineFragmentRect", .{});
        const showing = row.variant == g.active;
        const bot = if (row.variant) |v| v < g.variants.items.len and g.isAI(g.variants.items[v]) else false;
        const size: f64 = if (bot) 7 else if (showing) 6 else 3;
        const box: NSRect = .{
            .origin = .{ .x = origin.x - 11 - size / 2, .y = origin.y + line.origin.y + (tall - size) / 2 },
            .size = .{ .width = size, .height = size },
        };
        const ink = if (showing) color.word else color.ring;
        if (bot) {
            msg(void, ink, "setStroke", .{});
            msg(void, msg(id, NSBezierPath, "bezierPathWithRoundedRect:xRadius:yRadius:", .{ box, @as(f64, 2), @as(f64, 2) }), "stroke", .{});
            msg(void, ink, "setFill", .{});
            for ([_]f64{ 1.5, 4.25 }) |dx| {
                const eye: NSRect = .{ .origin = .{ .x = box.origin.x + dx, .y = box.origin.y + 3 }, .size = .{ .width = 1.3, .height = 1.3 } };
                msg(void, msg(id, NSBezierPath, "bezierPathWithRect:", .{eye}), "fill", .{});
            }
        } else {
            msg(void, ink, "setFill", .{});
            msg(void, msg(id, NSBezierPath, if (showing) "bezierPathWithOvalInRect:" else "bezierPathWithRect:", .{box}), "fill", .{});
        }
    }
}

/// An underline as an editor's pen would draw it: not quite straight, and for the same
/// group the same every time.
fn pen(x0: f64, x1: f64, y: f64, seed: u32, ink: id) void {
    if (x1 <= x0) return;
    const phase: f64 = @floatFromInt(seed % 13);
    const path = msg(id, objc.class("NSBezierPath"), "bezierPath", .{});
    msg(void, path, "setLineWidth:", .{@as(f64, 1.3)});
    var x = x0;
    while (true) : (x = @min(x + 5, x1)) {
        const p: NSPoint = .{ .x = x, .y = y + 0.5 * @sin(x / 19.0 + phase) + 0.25 * @sin(x / 6.1 + 2 * phase) };
        msg(void, path, if (x == x0) "moveToPoint:" else "lineToPoint:", .{p});
        if (x == x1) break;
    }
    msg(void, ink, "setStroke", .{});
    msg(void, path, "stroke", .{});
}

const line_gap = 12; // the space under each line of text, where the dots go
const row_gap = 8; // and under each row of the alternatives panel
const top_inset = 96; // down to the first line of the page, and of the panel's rows
const status_h = 40;

// --- Setup ----------------------------------------------------------------------------------

fn markdownFont(ns_font: id, name: []const u8, size: f64, fallback: id) id {
    return msg(id, msg(id, ns_font, "fontWithName:size:", .{ str(name), size }) orelse fallback, "retain", .{});
}

fn setup(app: id) void {
    const NSObject = "NSObject";
    const action = "v@:@";
    const draws = "v@:{CGRect={CGPoint=dd}{CGSize=dd}}";
    _ = objc.subclass(NSObject, "ROController", &.{
        .{ .name = "alternative:", .imp = @ptrCast(&alternative), .types = action },
        .{ .name = "nextAlt:", .imp = @ptrCast(&nextAlt), .types = action },
        .{ .name = "prevAlt:", .imp = @ptrCast(&prevAlt), .types = action },
        .{ .name = "ghost:", .imp = @ptrCast(&ghost), .types = action },
        .{ .name = "stash:", .imp = @ptrCast(&stash), .types = action },
        .{ .name = "useOverflow:", .imp = @ptrCast(&useOverflow), .types = action },
        .{ .name = "toggleTools:", .imp = @ptrCast(&toggleTools), .types = action },
        .{ .name = "toggleOverflow:", .imp = @ptrCast(&toggleOverflow), .types = action },
        .{ .name = "newDoc:", .imp = @ptrCast(&newDoc), .types = action },
        .{ .name = "openDoc:", .imp = @ptrCast(&openDoc), .types = action },
        .{ .name = "saveDoc:", .imp = @ptrCast(&saveDoc), .types = action },
        .{ .name = "saveDocAs:", .imp = @ptrCast(&saveDocAs), .types = action },
        .{ .name = "retab:", .imp = @ptrCast(&retab), .types = action },
        .{ .name = "aiAlternative:", .imp = @ptrCast(&aiAlternative), .types = action },
        .{ .name = "inference:", .imp = @ptrCast(&inference), .types = action },
        .{ .name = "needInference:", .imp = @ptrCast(&needInference), .types = action },
        .{ .name = "validateMenuItem:", .imp = @ptrCast(&validateMenuItem), .types = "B@:@" },
        .{ .name = "labMenu:", .imp = @ptrCast(&labMenu), .types = action },
        .{ .name = "labPass:", .imp = @ptrCast(&labPass), .types = action },
        .{ .name = "labOriginal:", .imp = @ptrCast(&labOriginal), .types = action },
        .{ .name = "labNext:", .imp = @ptrCast(&labNext), .types = action },
        .{ .name = "labKeep:", .imp = @ptrCast(&labKeep), .types = action },
        .{ .name = "labApply:", .imp = @ptrCast(&labApply), .types = action },
        .{ .name = "styleChanged:", .imp = @ptrCast(&styleChanged), .types = action },
        .{ .name = "resized:", .imp = @ptrCast(&resized), .types = action },
        .{ .name = "textStorage:didProcessEditing:range:changeInLength:", .imp = @ptrCast(&markdownEdited), .types = "v@:@Q{_NSRange=QQ}q" },
        .{ .name = "textDidChange:", .imp = @ptrCast(&textDidChange), .types = action },
        .{ .name = "textDidEndEditing:", .imp = @ptrCast(&editingEnded), .types = action },
        .{ .name = "textView:doCommandBySelector:", .imp = @ptrCast(&doCommand), .types = "B@:@:" },
        .{ .name = "undoManagerForTextView:", .imp = @ptrCast(&undoFor), .types = "@@:@" },
        .{ .name = "textViewDidChangeSelection:", .imp = @ptrCast(&selectionDidChange), .types = action },
        .{ .name = "windowShouldClose:", .imp = @ptrCast(&windowShouldClose), .types = "B@:@" },
        .{ .name = "applicationShouldTerminate:", .imp = @ptrCast(&shouldTerminate), .types = "Q@:@" },
        .{ .name = "applicationShouldTerminateAfterLastWindowClosed:", .imp = @ptrCast(&quitWithWindow), .types = "B@:@" },
        .{ .name = "applicationDidFinishLaunching:", .imp = @ptrCast(&didLaunch), .types = action },
        .{ .name = "application:openFile:", .imp = @ptrCast(&openFile), .types = "B@:@@" },
    });
    _ = objc.subclass("NSTextView", "ROPage", &.{
        .{ .name = "keyDown:", .imp = @ptrCast(&keyDown), .types = action },
        .{ .name = "mouseMoved:", .imp = @ptrCast(&mouseMoved), .types = action },
        .{ .name = "mouseDown:", .imp = @ptrCast(&mouseDown), .types = action },
        .{ .name = "menuForEvent:", .imp = @ptrCast(&contextMenu), .types = "@@:@" },
        .{ .name = "paste:", .imp = @ptrCast(&paste), .types = action },
        .{ .name = "drawViewBackgroundInRect:", .imp = @ptrCast(&drawBackground), .types = draws },
    });
    _ = objc.subclass("NSTextView", "ROAlts", &.{
        .{ .name = "paste:", .imp = @ptrCast(&paste), .types = action },
        .{ .name = "drawViewBackgroundInRect:", .imp = @ptrCast(&drawRows), .types = draws },
    });
    ctl = objc.new("ROController");
    msg(void, app, "setDelegate:", .{ctl});

    // The palette is the one measured from the Write_On clips by joeysim/write-on-replica.
    color = .{
        .bg = rgb(0x050a1c, 1),
        .panel = rgb(0x0a0f1f, 1),
        .text = rgb(0xf5d1c0, 1),
        .near = rgb(0xf5d1c0, 0.66), // the rest of the paragraph the panel's target is in
        .far = rgb(0xf5d1c0, 0.36), // and every other paragraph
        .ghost = rgb(0xf5d1c0, 0.11),
        .clear = rgb(0, 0),
        .dim = rgb(0x857b82, 1),
        .word = rgb(0x817cd4, 1),
        .word_line = rgb(0x817cd4, 0.5),
        .sentence = rgb(0xc29abe, 1),
        .sentence_line = rgb(0xc29abe, 0.45),
        .paragraph = rgb(0xc88d6c, 1),
        .bar = rgb(0x805448, 1),
        .ring = rgb(0x6c6879, 1),
        .hover = rgb(0x98a8e2, 0.14),
        .selection = rgb(0x817cd4, 0.28),
        .code = rgb(0x121522, 1),
        .link = rgb(0x98a8e2, 1),
    };
    const regular: f64 = 0;
    const heavy: f64 = 0.4;
    const NSFont = objc.class("NSFont");
    font = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 20), regular }), "retain", .{});
    bold = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 20), heavy }), "retain", .{});
    small = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 11), regular }), "retain", .{});
    hidden = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 0.1), regular }), "retain", .{});
    italic = markdownFont(NSFont, "Menlo-Italic", 20, font);
    bold_italic = markdownFont(NSFont, "Menlo-BoldItalic", 20, bold);
    code_font = markdownFont(NSFont, "Monaco", 18, font);
    markdown_line = msg(id, number(1), "retain", .{});
    script = msg(id, msg(id, NSFont, "fontWithName:size:", .{ str("BradleyHandITCTT-Bold"), @as(f64, 17) }) orelse small, "retain", .{});
    tones = .{ makeTone(1900), makeTone(1500) };
    key_group = msg(id, str("WriteAwayGroup"), "retain", .{});
    key_ghost = msg(id, str("WriteAwayGhost"), "retain", .{});
    key_lab_keep = msg(id, str("WriteAwayLabKeep"), "retain", .{});
    key_fence = msg(id, str("WriteAwayFence"), "retain", .{});
    key_comment = msg(id, str("WriteAwayComment"), "retain", .{});
    key_rule = msg(id, str("WriteAwayRule"), "retain", .{});
    key_quote = msg(id, str("WriteAwayQuote"), "retain", .{});
    key_picture = msg(id, str("WriteAwayPicture"), "retain", .{});
    pictures = objc.new("NSMutableDictionary");
    yes = msg(id, msg(id, objc.class("NSNumber"), "numberWithBool:", .{true}), "retain", .{});
    spaced = objc.new("NSMutableParagraphStyle");
    msg(void, spaced, "setLineSpacing:", .{@as(f64, line_gap)});
    // A heading with nothing after its marker yet is still a line of full height.
    msg(void, spaced, "setMinimumLineHeight:", .{msg(f64, msg(id, objc.new("NSLayoutManager"), "autorelease", .{}), "defaultLineHeightForFont:", .{font})});
    // A quote's text stands where its source has it, so nothing moves when the "> " shows.
    const quote_indent = msg(NSSize, str("> "), "sizeWithAttributes:", .{dict(&.{.{ NSFontAttributeName, font }})}).width;
    quote_shown = msg(id, spaced, "mutableCopy", .{});
    msg(void, quote_shown, "setHeadIndent:", .{quote_indent});
    quote_hidden = msg(id, quote_shown, "mutableCopy", .{});
    msg(void, quote_hidden, "setFirstLineHeadIndent:", .{quote_indent});
    base_attrs = msg(id, dict(&.{
        .{ NSFontAttributeName, font },
        .{ NSForegroundColorAttributeName, color.text },
        .{ NSParagraphStyleAttributeName, spaced },
    }), "retain", .{});

    // Keep content views out of the title bar: AppKit owns its drag and double-clicks.
    const titled_closable_mini_resizable: usize = 1 | 2 | 4 | 8;
    const buffered: usize = 2;
    window = msg(id, msg(id, objc.class("NSWindow"), "alloc", .{}), "initWithContentRect:styleMask:backing:defer:", .{
        NSRect{ .size = .{ .width = 1440, .height = 900 } }, // wide enough for the alternatives panel to clear the column
        titled_closable_mini_resizable,
        buffered,
        false,
    });
    msg(void, window, "setReleasedWhenClosed:", .{false});
    msg(void, window, "setBackgroundColor:", .{color.bg});
    msg(void, window, "setAppearance:", .{msg(id, objc.class("NSAppearance"), "appearanceNamed:", .{NSAppearanceNameDarkAqua})});
    msg(void, window, "setAcceptsMouseMovedEvents:", .{true});
    msg(void, window, "setDelegate:", .{ctl});
    msg(void, window, "center", .{});
    _ = msg(bool, window, "setFrameAutosaveName:", .{str("WriteAwayWindow")});

    const content = msg(id, window, "contentView", .{});
    const bounds = msg(NSRect, content, "bounds", .{});
    const height_sizable: usize = 16;
    const max_x_margin: usize = 4;
    const min_y_margin: usize = 8;

    scroll = textArea("ROPage", bounds, color.bg, &page);
    msg(void, page, "setRichText:", .{true});
    msg(void, msg(id, page, "textContainer", .{}), "setWidthTracksTextView:", .{false}); // see `resized`
    msg(void, page, "setUsesFontPanel:", .{false});
    msg(void, page, "setFont:", .{font});
    msg(void, page, "setDefaultParagraphStyle:", .{spaced});
    msg(void, page, "setSelectedTextAttributes:", .{dict(&.{.{ NSBackgroundColorAttributeName, color.selection }})});
    storage = msg(id, page, "textStorage", .{});
    msg(void, storage, "setDelegate:", .{ctl});
    layout = msg(id, page, "layoutManager", .{});
    const strip: NSRect = .{ .size = .{ .width = 280, .height = bounds.size.height } };
    over_scroll = textArea("NSTextView", strip, color.panel, &over);
    msg(void, over, "setRichText:", .{false});
    msg(void, over, "setFont:", .{msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 14), regular })});
    msg(void, over, "setTextContainerInset:", .{NSSize{ .width = 18, .height = 48 }});
    const split_class = objc.subclass("NSSplitViewController", "ROSplitController", &.{.{
        .name = "splitView:effectiveRect:forDrawnRect:ofDividerAtIndex:",
        .imp = @ptrCast(&dividerHitRect),
        .types = "{CGRect={CGPoint=dd}{CGSize=dd}}@:@{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}q",
    }});
    const controller = msg(id, msg(id, split_class, "alloc", .{}), "init", .{});
    const panes = msg(id, controller, "view", .{});
    split = msg(id, controller, "splitView", .{});
    msg(void, split, "setVertical:", .{true});
    msg(void, split, "setDividerStyle:", .{@as(isize, 2)}); // thin, with a wider hit area
    msg(void, content, "addSubview:", .{panes});
    msg(void, panes, "setTranslatesAutoresizingMaskIntoConstraints:", .{false});
    for ([_][*:0]const u8{ "leadingAnchor", "trailingAnchor", "topAnchor", "bottomAnchor" }, [_]f64{ 0, 0, 0, -status_h }) |edge, offset| {
        const pin = msg(id, msg(id, panes, edge, .{}), "constraintEqualToAnchor:constant:", .{ msg(id, content, edge, .{}), offset });
        msg(void, pin, "setActive:", .{true});
    }
    draft_item = splitItem(scroll);
    overflow_item = splitItem(over_scroll);
    msg(void, overflow_item, "setMinimumThickness:", .{@as(f64, 200)});
    msg(void, overflow_item, "setMaximumThickness:", .{@as(f64, 600)});
    msg(void, overflow_item, "setHoldingPriority:", .{@as(f32, 251)}); // the draft absorbs window resizes first
    msg(void, overflow_item, "setCollapseBehavior:", .{@as(isize, 2)}); // resize siblings, not the window
    msg(void, overflow_item, "setCollapsed:", .{true});
    msg(void, controller, "addSplitViewItem:", .{draft_item});
    msg(void, controller, "addSplitViewItem:", .{overflow_item});

    // The alternatives panel, over the page's left margin: tabs, rows, and a hint.
    const left: NSRect = .{ .origin = .{ .y = status_h }, .size = .{ .width = panel_w, .height = bounds.size.height - status_h } };
    alts_scroll = textArea("ROAlts", left, color.panel, &alts);
    msg(void, alts_scroll, "setAutoresizingMask:", .{max_x_margin | height_sizable});
    msg(void, alts, "setRichText:", .{false});
    msg(void, alts, "setFont:", .{msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 15), regular })});
    msg(void, alts, "setTextColor:", .{color.dim});
    msg(void, alts, "setInsertionPointColor:", .{color.word});
    const rows = objc.new("NSMutableParagraphStyle");
    msg(void, rows, "setLineSpacing:", .{@as(f64, row_gap)});
    msg(void, alts, "setDefaultParagraphStyle:", .{rows});
    msg(void, alts, "setTextContainerInset:", .{NSSize{ .width = 30, .height = top_inset }});
    alts_undo = objc.new("NSUndoManager");
    msg(void, content, "addSubview:", .{alts_scroll});
    var x: f64 = 16;
    for (&tabs, tab_names, 0..) |*tab, name, i| {
        tab.* = msg(id, objc.class("NSButton"), "buttonWithTitle:target:action:", .{ str(name), ctl, objc.sel("retab:") });
        msg(void, tab.*, "setBordered:", .{false});
        msg(void, tab.*, "setTag:", .{@as(isize, @intCast(i))});
        msg(void, tab.*, "setAttributedTitle:", .{styled(name, script, color.dim)});
        msg(void, tab.*, "sizeToFit", .{});
        msg(void, tab.*, "setFrameOrigin:", .{NSPoint{ .x = x, .y = bounds.size.height - top_inset + 10 }});
        msg(void, tab.*, "setAutoresizingMask:", .{max_x_margin | min_y_margin});
        msg(void, content, "addSubview:", .{tab.*});
        x += msg(NSRect, tab.*, "frame", .{}).size.width + 6;
    }
    alts_hint = msg(id, objc.class("NSTextField"), "wrappingLabelWithString:", .{str("")}); // room for the reason an asking failed
    msg(void, alts_hint, "setFrame:", .{NSRect{ .origin = .{ .x = 16, .y = status_h + 8 }, .size = .{ .width = panel_w - 32, .height = 64 } }});
    msg(void, content, "addSubview:", .{alts_hint});
    hint("");

    count = msg(id, objc.class("NSButton"), "buttonWithTitle:target:action:", .{ str(""), ctl, objc.sel("toggleTools:") });
    msg(void, count, "setBordered:", .{false});
    msg(void, count, "setFrameOrigin:", .{NSPoint{ .x = 22, .y = bounds.size.height - 28 }});
    msg(void, count, "setAutoresizingMask:", .{max_x_margin | min_y_margin});
    msg(void, content, "addSubview:", .{count});

    const clip = msg(id, scroll, "contentView", .{});
    msg(void, clip, "setPostsFrameChangedNotifications:", .{true});
    msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ ctl, objc.sel("resized:"), NSViewFrameDidChangeNotification, clip });

    lab_ui.setup(content, ctl, page, small, color.dim, color.word, color.text);
    menus(app);
    panels();
    resized(null, null, null);
}

/// Give the thin divider at least six points of purchase on either side.
fn dividerHitRect(_: id, _: SEL, _: id, proposed: NSRect, drawn: NSRect, _: isize) callconv(.c) NSRect {
    var hit = proposed;
    hit.origin.x = @min(proposed.origin.x, drawn.origin.x - 6);
    hit.size.width = @max(proposed.origin.x + proposed.size.width, drawn.origin.x + drawn.size.width + 6) - hit.origin.x;
    return hit;
}

fn splitItem(view: id) id {
    const vc = msg(id, objc.new("NSViewController"), "autorelease", .{});
    msg(void, vc, "setView:", .{view});
    return msg(id, objc.class("NSSplitViewItem"), "splitViewItemWithViewController:", .{vc});
}

/// A scrolling NSTextView (or subclass) in the house colors.
fn textArea(class_name: [*:0]const u8, frame: NSRect, background: id, out: *id) id {
    const overlay: isize = 1;
    const width_sizable: usize = 2;
    const far: f64 = 1e7;
    const sv = msg(id, msg(id, objc.class("NSScrollView"), "alloc", .{}), "initWithFrame:", .{frame});
    msg(void, sv, "setHasVerticalScroller:", .{true});
    msg(void, sv, "setScrollerStyle:", .{overlay});
    msg(void, sv, "setBackgroundColor:", .{background});
    msg(void, sv, "setAutomaticallyAdjustsContentInsets:", .{false}); // the views pad themselves clear of the title bar
    const size = msg(NSSize, sv, "contentSize", .{});
    const view = msg(id, msg(id, objc.class(class_name), "alloc", .{}), "initWithFrame:", .{NSRect{ .size = size }});
    msg(void, view, "setMinSize:", .{NSSize{ .height = size.height }});
    msg(void, view, "setMaxSize:", .{NSSize{ .width = far, .height = far }});
    msg(void, view, "setVerticallyResizable:", .{true});
    msg(void, view, "setHorizontallyResizable:", .{false});
    msg(void, view, "setAutoresizingMask:", .{width_sizable});
    const container = msg(id, view, "textContainer", .{});
    msg(void, container, "setContainerSize:", .{NSSize{ .width = size.width, .height = far }});
    msg(void, container, "setWidthTracksTextView:", .{true});
    msg(void, view, "setBackgroundColor:", .{background});
    msg(void, view, "setTextColor:", .{color.text});
    msg(void, view, "setInsertionPointColor:", .{color.text});
    msg(void, view, "setAllowsUndo:", .{true});
    msg(void, view, "setAutomaticQuoteSubstitutionEnabled:", .{false}); // Markdown wants its quotes and dashes straight
    msg(void, view, "setAutomaticDashSubstitutionEnabled:", .{false});
    msg(void, view, "setDelegate:", .{ctl});
    msg(void, sv, "setDocumentView:", .{view});
    out.* = view;
    return sv;
}

fn menus(app: id) void {
    const bar = objc.new("NSMenu");
    const cs = Mod.ctrl | Mod.shift;

    const m_app = submenu(bar, "Write_Away");
    item(m_app, "About Write_Away", "orderFrontStandardAboutPanel:", "", 0, null); // Info.plist has the version
    msg(void, m_app, "addItem:", .{msg(id, objc.class("NSMenuItem"), "separatorItem", .{})});
    item(m_app, "Inferenceโ€ฆ", "inference:", ",", Mod.cmd, ctl);
    item(m_app, "Hide Write_Away", "hide:", "h", Mod.cmd, null);
    item(m_app, "Quit Write_Away", "terminate:", "q", Mod.cmd, null);

    const file = submenu(bar, "File");
    item(file, "New", "newDoc:", "n", Mod.cmd, ctl);
    item(file, "Openโ€ฆ", "openDoc:", "o", Mod.cmd, ctl);
    item(file, "Save", "saveDoc:", "s", Mod.cmd, ctl);
    item(file, "Save Asโ€ฆ", "saveDocAs:", "s", Mod.cmd | Mod.shift, ctl);

    const edit = submenu(bar, "Edit");
    item(edit, "Undo", "undo:", "z", Mod.cmd, null);
    item(edit, "Redo", "redo:", "z", Mod.cmd | Mod.shift, null);
    item(edit, "Cut", "cut:", "x", Mod.cmd, null);
    item(edit, "Copy", "copy:", "c", Mod.cmd, null);
    item(edit, "Paste", "paste:", "v", Mod.cmd, null);
    item(edit, "Select All", "selectAll:", "a", Mod.cmd, null);

    // As in Write_On, the writing commands are on Control, on the Mac too.
    const write = submenu(bar, "Write");
    item(write, "Alternatives", "alternative:", "a", cs, ctl);
    item(write, "AI Alternatives", "aiAlternative:", "g", cs, ctl);
    item(write, "Next Alternative", "nextAlt:", "]", Mod.ctrl, ctl);
    item(write, "Previous Alternative", "prevAlt:", "[", Mod.ctrl, ctl);
    item(write, "Ghost or Revive", "ghost:", "/", Mod.ctrl, ctl);
    item(write, "Stash in Overflow", "stash:", "x", cs, ctl);
    item(write, "Use from Overflow", "useOverflow:", "\r", Mod.ctrl, ctl);
    item(write, "Labโ€ฆ", "labMenu:", "l", cs, ctl);
    item(write, "Lab: Next", "labNext:", "n", cs, ctl);
    item(write, "Lab: Keep", "labKeep:", "k", cs, ctl);
    item(write, "Lab: Apply rest", "labApply:", "p", cs, ctl);
    item(write, "Lab: Discard / Original", "labOriginal:", "o", cs, ctl);

    const view = submenu(bar, "View");
    item(view, "Tools", "toggleTools:", "r", cs, ctl);
    item(view, "Overflow", "toggleOverflow:", "d", cs, ctl);
    item(view, "Enter Full Screen", "toggleFullScreen:", "f", Mod.ctrl | Mod.cmd, null);

    msg(void, app, "setMainMenu:", .{bar});
}

fn submenu(bar: id, title: []const u8) id {
    const menu = msg(id, msg(id, objc.class("NSMenu"), "alloc", .{}), "initWithTitle:", .{str(title)});
    const holder = objc.new("NSMenuItem");
    msg(void, holder, "setSubmenu:", .{menu});
    msg(void, bar, "addItem:", .{holder});
    return menu;
}

fn item(menu: id, title: []const u8, action: [*:0]const u8, key: []const u8, mods: usize, to: id) void {
    const it = msg(id, msg(id, objc.class("NSMenuItem"), "alloc", .{}), "initWithTitle:action:keyEquivalent:", .{ str(title), objc.sel(action), str(key) });
    msg(void, it, "setKeyEquivalentModifierMask:", .{mods});
    msg(void, it, "setTarget:", .{to});
    msg(void, menu, "addItem:", .{it});
    msg(void, it, "release", .{}); // the menu has it
}

pub fn main() void {
    _ = objc.new("NSAutoreleasePool"); // never drained: what setup makes lasts for the run
    const app = msg(id, objc.class("NSApplication"), "sharedApplication", .{});
    threaded = .init(gpa, .{});
    io = threaded.io();
    ai.init(gpa, io);
    setup(app);

    const process = msg(id, objc.class("NSProcessInfo"), "processInfo", .{});
    if (msg(id, msg(id, process, "environment", .{}), "objectForKey:", .{str("WRITE_AWAY_SELFTEST")}) != null) return selftest();

    document_defaults = msg(id, objc.class("NSUserDefaults"), "standardUserDefaults", .{});
    const regular: isize = 0;
    _ = msg(bool, app, "setActivationPolicy:", .{regular});
    msg(void, app, "run", .{});
}

fn didLaunch(_: id, _: SEL, note: id) callconv(.c) void {
    startDraft();
    msg(void, window, "makeKeyAndOrderFront:", .{@as(id, null)});
    _ = msg(bool, window, "makeFirstResponder:", .{page});
    msg(void, msg(id, note, "object", .{}), "activateIgnoringOtherApps:", .{true});
}

// --- The check ------------------------------------------------------------------------------

/// `zig build test` runs this: the real views, driven through the real commands, with no
/// window on screen. It is the check on every Objective-C signature above.
fn selftest() void {
    const t = struct {
        fn expect(ok: bool, what: []const u8) void {
            if (ok) return;
            std.debug.print("selftest FAILED: {s}\n", .{what});
            std.process.exit(1);
        }
    };
    const um = msg(id, page, "undoManager", .{});

    // Use an isolated defaults suite and temporary draft, never the writer's last file.
    const unique = msg(id, msg(id, objc.class("NSUUID"), "UUID", .{}), "UUIDString", .{});
    document_defaults = msg(id, msg(id, objc.class("NSUserDefaults"), "alloc", .{}), "initWithSuiteName:", .{unique});
    startDraft();
    t.expect(len() == 0 and file_path == null and std.mem.eql(u8, objc.utf8(msg(id, window, "title", .{})), "Untitled"), "a first launch is empty and Untitled");
    const fm = msg(id, objc.class("NSFileManager"), "defaultManager", .{});
    const path = msg(id, msg(id, msg(id, fm, "temporaryDirectory", .{}), "URLByAppendingPathComponent:", .{unique}), "path", .{});
    t.expect(openFile(null, null, null, path), "an explicit new path starts a draft");
    startDraft();
    t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and len() == 0, "a launch file takes precedence even when it does not exist yet");
    insert(page, "Remember this.", .{});
    t.expect(save(false), "save the named piece");
    received_open = false;
    load("");
    startDraft();
    t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and std.mem.eql(u8, objc.utf8(string(page)), "Remember this."), "the next launch restores the last file from disk");
    t.expect(msg(bool, fm, "removeItemAtPath:error:", .{ path, @as(?*id, null) }), "remove the temporary piece");
    startDraft();
    t.expect(len() == 0 and file_path == null and msg(id, document_defaults, "objectForKey:", .{str(last_document)}) == null and !msg(bool, window, "isDocumentEdited", .{}), "a missing piece leaves a clean unnamed draft and no stale path");
    msg(void, document_defaults, "removePersistentDomainForName:", .{unique});

    load(@embedFile("welcome.md"));
    t.expect(groups.count() == 3, "the welcome piece has three groups");

    // Use the native divider's drag constraints. Reopening shouldn't reset the user's width.
    const content = msg(id, window, "contentView", .{});
    const content_frame = msg(NSRect, content, "frame", .{});
    t.expect(msg(bool, window, "isMovable", .{}) and content_frame.size.height < msg(NSRect, window, "frame", .{}).size.height and !msg(bool, window, "titlebarAppearsTransparent", .{}), "the window owns its draggable title bar");
    toggleOverflow(null, null, null);
    const total = msg(NSRect, split, "bounds", .{}).size.width;
    const thick = msg(f64, split, "dividerThickness", .{});
    const max_over = @min(600, total - thick - 320);
    for ([_]f64{ total, 0, total - thick - 415 }, [_]f64{ 200, max_over, @min(415, max_over) }) |pos, expected| {
        msg(void, split, "setPosition:ofDividerAtIndex:", .{ pos, @as(isize, 0) });
        msg(void, content, "layoutSubtreeIfNeeded", .{});
        t.expect(@abs(msg(NSRect, over_scroll, "frame", .{}).size.width - expected) < 1, "the divider moves and clamps at either end");
    }
    const chosen = msg(NSRect, over_scroll, "frame", .{}).size.width;
    toggleOverflow(null, null, null);
    t.expect(@abs(msg(NSRect, scroll, "frame", .{}).size.width - total) < 1, "closing restores the full writing area");
    toggleOverflow(null, null, null);
    t.expect(@abs(msg(NSRect, over_scroll, "frame", .{}).size.width - chosen) < 1, "reopening remembers the divider");
    toggleOverflow(null, null, null);

    // Moving into the heading reveals its source without changing the styled title.
    select(.{ .location = len() });
    t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "an inactive heading's marker is hidden");
    select(.{ .location = 1 });
    t.expect(selection().location == 1 and msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == font, "the caret can enter and reveal the heading marker");
    t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "the heading title remains bold");

    // Flip a group in place, and undo it.
    const gid = groups.keys()[0];
    const first = gpa.dupe(u8, textOf(groupRange(gid).?)) catch unreachable;
    flip(gid, 1);
    t.expect(!std.mem.eql(u8, first, textOf(groupRange(gid).?)), "flip changes the text");
    t.expect(groups.get(gid).?.active == 1, "flip moves to the next variant");
    t.expect(tick_gid == gid and std.mem.eql(u8, first, tick_home.items), "and the tones know where the playing began");
    t.expect(msg(f64, tones[0], "duration", .{}) > 0.04 and msg(f64, tones[1], "duration", .{}) > 0.04, "and are sounds that can be played");
    t.expect(std.mem.eql(u8, "is a ", textOf(.{ .location = groupRange(gid).?.location - 5, .length = 5 })), "the article follows the word: a negotiation");
    msg(void, um, "undo", .{});
    t.expect(std.mem.eql(u8, "is an ", textOf(.{ .location = groupRange(gid).?.location - 6, .length = 6 })), "and back: an argument");
    t.expect(std.mem.eql(u8, first, textOf(groupRange(gid).?)), "undo puts the text back");
    t.expect(groups.get(gid).?.active == 0, "undo puts the active variant back");

    // Delete the showing variant, and undo that.
    const before = groups.get(gid).?.variants.items.len;
    removeShown(gid);
    t.expect(groups.get(gid).?.variants.items.len == before - 1, "delete removes a variant");
    msg(void, um, "undo", .{});
    t.expect(groups.get(gid).?.variants.items.len == before, "undo restores the variant");
    t.expect(std.mem.eql(u8, first, textOf(groupRange(gid).?)), "and shows it again");

    // The pointer on a group gives it the arrow keys, until something is typed.
    const container = msg(id, page, "textContainer", .{});
    const glyph = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ groupRange(gid).?, @as(?*NSRange, null) });
    const box = msg(NSRect, layout, "boundingRectForGlyphRange:inTextContainer:", .{ NSRange{ .location = glyph.location, .length = 1 }, container });
    const origin = msg(NSPoint, page, "textContainerOrigin", .{});
    const on_word: NSPoint = .{ .x = origin.x + box.origin.x + 2, .y = origin.y + box.origin.y + box.size.height / 2 };
    const zero: usize = 0;
    const no_time: f64 = 0;
    const no_window: isize = 0;
    const mouse_moved: usize = 5;
    const key_down: usize = 10;
    const NSEvent = objc.class("NSEvent");
    mouseMoved(page, null, msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{
        mouse_moved, msg(NSPoint, page, "convertPoint:toView:", .{ on_word, @as(id, null) }), zero, no_time, no_window, @as(id, null), no_window, no_window, @as(f32, 0),
    }));
    t.expect(armed and hover == gid, "the pointer finds the group under it");
    select(.{}); // undo left the restored word selected, and a selection keeps the arrows
    const right_arrow: u16 = 124;
    const arrow = msg(id, NSEvent, "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{
        key_down, NSPoint{}, zero, no_time, no_window, @as(id, null), str(""), str(""), false, right_arrow,
    });
    keyDown(page, null, arrow);
    t.expect(groups.get(gid).?.active == 1, "an arrow key flips the hovered group");
    msg(void, um, "undo", .{});
    armed = false;

    // A right-click on the word: what can be done with it.
    select(.{}); // undo left the word selected again, and then the menu would be about the selection
    const right_down: usize = 3;
    _ = msg(bool, window, "makeFirstResponder:", .{page});
    const click = msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{
        right_down, msg(NSPoint, page, "convertPoint:toView:", .{ on_word, @as(id, null) }), zero, no_time, no_window, @as(id, null), no_window, no_window, @as(f32, 0),
    });
    msg(void, page, "rightMouseDown:", .{click});
    const first_row = msg(id, window, "firstResponder", .{});
    const writing_card = msg(id, first_row, "superview", .{});
    t.expect(msg(usize, msg(id, writing_card, "subviews", .{}), "count", .{}) == 5, "the writing menu has four rows and the hidden Lab scroll view");
    t.expect(std.mem.find(u8, objc.utf8(msg(id, first_row, "title", .{})), first) != null, "the first row names the word under the pointer");
    const menu_key = struct {
        fn send(code: u16, mods: usize, chars: []const u8) void {
            const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{
                @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(chars), str(chars), false, code,
            });
            if (!msg(bool, window, "performKeyEquivalent:", .{event}))
                msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event});
        }
    };
    menu_key.send(53, 0, "");
    t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape restores editor focus");
    const selected = groupRange(gid).?;
    select(selected);
    t.expect(contextMenu(page, null, click) == null, "writing mode does not create a system menu");
    t.expect(std.mem.eql(u8, objc.utf8(msg(id, first_row, "title", .{})), "Alternatives for selection"), "a click inside a selection keeps it");
    menu_key.send(125, 0, "");
    t.expect(std.mem.eql(u8, objc.utf8(msg(id, msg(id, window, "firstResponder", .{}), "title", .{})), "AI alternatives for selection"), "the down arrow moves focus to the next action");
    menu_key.send(44, Mod.ctrl, "/");
    t.expect(msg(id, window, "firstResponder", .{}) == page and std.meta.eql(selection(), selected) and ghostIn(selected), "the popup shortcut ghosts the selected text and returns focus");
    msg(void, um, "undo", .{});
    _ = contextMenu(page, null, click);
    menu_key.send(36, 0, "\r");
    t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "Return opens alternatives for the clicked group");
    _ = contextMenu(page, null, click);
    menu_key.send(53, 0, "");
    t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "dismissing the popup leaves the alternatives panel and its focus alone");
    closePanel();

    // Ghost and revive. (Each undo so far has had one command to undo: outside the run
    // loop nothing closes an undo group but undo itself.)
    select(wordAt(len() - 3));
    const word = selection();
    ghost(null, null, null);
    t.expect(runAt(key_ghost, word.location) != null, "ghost marks the word");
    msg(void, um, "undo", .{});
    t.expect(runAt(key_ghost, word.location) == null, "undo revives it");
    ghost(null, null, null);
    select(.{ .location = word.location + 1 });
    ghost(null, null, null);
    t.expect(runAt(key_ghost, word.location) == null, "ghost on ghosted text revives it");

    // The alternatives panel, on the heading's first word.
    const caret = struct {
        fn at(i: usize) void {
            msg(void, alts, "setSelectedRange:", .{NSRange{ .location = i }});
        }
        fn here() NSRange {
            return msg(NSRange, alts, "selectedRange", .{});
        }
    };
    select(.{ .location = 3 });
    alternative(null, null, null);
    const lone = target;
    t.expect(lone != 0 and std.mem.eql(u8, "Say\n", objc.utf8(string(alts))), "the panel opens on the word, with an empty row under it");
    retab(null, null, tabs[1]);
    t.expect(target != lone and groups.get(target).?.scope == .sentence, "the Sentence tab moves the panel");
    t.expect(std.mem.eql(u8, "Say it another way", textOf(groupRange(target).?)), "to the sentence around the same spot");
    t.expect(!groups.contains(lone), "and a word nothing was added to is plain text again");
    retab(null, null, tabs[0]);
    const made = target;
    t.expect(std.mem.eql(u8, "Say", textOf(groupRange(made).?)), "the Word tab moves it back");
    insert(alts, "Write", caret.here());
    t.expect(std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "what is typed on the empty row shows on the page");
    t.expect(groups.get(made).?.variants.items.len == 2, "and is the second variant");
    caret.at(1);
    t.expect(std.mem.eql(u8, "Say", textOf(groupRange(made).?)), "the row the caret is on is the one that shows");
    caret.at(9);
    t.expect(std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "either way");

    // Asking the AI, without the AI: the question is taken as sent, and an answer lands.
    asking = made;
    newRow();
    insert(alts, "??", caret.here());
    t.expect(groups.get(made).?.variants.items.len == 2, "the ?? row is not a variant");
    land(.{ .text = @constCast("1. Put\n- \"Phrase\"\nWrite\n") });
    const asked = groups.get(made).?;
    t.expect(asked.variants.items.len == 4 and asked.isAI("Put") and asked.isAI("Phrase"), "the AI's suggestions take the row's place, cleaned up");
    t.expect(std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "and what shows goes on showing");
    asking = made;
    newRow();
    insert(alts, "??", caret.here());
    land(.{ .failed = @constCast("no") });
    t.expect(askRow() == null and groups.get(made).?.variants.items.len == 4, "a failed asking takes the ?? away and nothing else");

    // The whole visit to the panel is one step for the page's undo.
    closePanel();
    t.expect(target == 0 and std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "closing the panel leaves the page as it is");
    msg(void, um, "undo", .{});
    t.expect(std.mem.eql(u8, "Say", textOf(groupRange(made).?)) and groups.get(made).?.active == 0, "one undo takes back what the visit did to the page");
    msg(void, um, "redo", .{});
    t.expect(std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "and redo does it again");
    select(.{ .location = end(groupRange(made).?) });
    insert(page, "!", selection());
    t.expect(std.mem.eql(u8, "Write", textOf(groupRange(made).?)), "typing at a group's edge lands outside it");

    // Stash, and use.
    const words = doc.countWords(objc.utf8(string(page)));
    const stashed = doc.countWords(objc.utf8(string(over)));
    select(.{ .location = len() - 3 });
    stash(null, null, null);
    t.expect(doc.countWords(objc.utf8(string(page))) < words, "stash takes the paragraph out of the page");
    t.expect(doc.countWords(objc.utf8(string(over))) > stashed, "and puts it in Overflow");
    msg(void, over, "setSelectedRange:", .{NSRange{ .location = msg(usize, string(over), "length", .{}) }});
    select(.{ .location = len() });
    useOverflow(null, null, null);
    t.expect(doc.countWords(objc.utf8(string(page))) == words, "use brings it back");

    // What Save writes, loads back the same.
    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    const arena = arena_state.allocator();
    const saved = snapshot(arena) catch unreachable;
    const n_groups = groups.count();
    load(saved);
    t.expect(groups.count() == n_groups and n_groups == 4, "every group survives a save");
    var kept = false;
    for (groups.values()) |g| kept = kept or g.isAI("Put");
    t.expect(kept, "and so does whose idea a variant was");
    t.expect(std.mem.eql(u8, saved, snapshot(arena) catch unreachable), "save, load, save is stable");

    // Exercise the same main-queue path as a completed inference request, without a key.
    const stub = struct {
        fn reply(p: lab.Pass, response: []const u8) *Job {
            const j = gpa.create(Job) catch unreachable;
            j.* = .{ .arena = .init(gpa), .pass = p, .seq = 0 };
            j.draft = j.arena.allocator().dupe(u8, objc.utf8(string(page))) catch unreachable;
            j.words = doc.countWords(j.draft);
            j.answer = .{ .text = gpa.dupe(u8, response) catch unreachable };
            reading = j;
            return j;
        }
        fn key(code: u16, mods: usize) void {
            const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{
                @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(""), str(""), false, code,
            });
            msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event});
        }
        fn strength(pass: lab.Pass) void {
            labMenu(null, null, null);
            // Shift-Tab wraps from the guide around the trim buttons, strongest first.
            for (0..10 - @intFromEnum(pass)) |_| key(48, Mod.shift);
            key(36, 0);
        }
        fn ghostValue(at: usize) id {
            return if (runAt(key_ghost, at)) |run| run.value else null;
        }
        fn command(action: *const fn (id, SEL, id) callconv(.c) void) void {
            beginEvent();
            defer endEvent();
            action(null, null, null);
        }
        fn beginEvent() void {
            msg(void, msg(id, page, "undoManager", .{}), "beginUndoGrouping", .{});
        }
        fn endEvent() void {
            msg(void, msg(id, page, "undoManager", .{}), "endUndoGrouping", .{});
        }
    };
    const cut = "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":5}]";
    const trim_draft = "We really need this today. Keep my note.";
    load(trim_draft);
    _ = msg(bool, window, "makeFirstResponder:", .{page});
    const shared = msg(id, objc.class("NSApplication"), "sharedApplication", .{});
    const app_menu = msg(id, msg(id, msg(id, shared, "mainMenu", .{}), "itemAtIndex:", .{@as(isize, 0)}), "submenu", .{});
    const about = msg(id, app_menu, "itemWithTitle:", .{str("About Write_Away")});
    t.expect(about != null and msg(bool, shared, "respondsToSelector:", .{msg(SEL, about, "action", .{})}), "the app answers About Write_Away");
    const write_menu = msg(id, msg(id, msg(id, shared, "mainMenu", .{}), "itemAtIndex:", .{@as(isize, 3)}), "submenu", .{});
    const next_item = msg(id, write_menu, "itemWithTitle:", .{str("Lab: Next")});
    t.expect(next_item != null and !validateMenuItem(null, null, next_item), "Lab review menu is disabled without a review");
    toggleTools(null, null, null);
    labMenu(null, null, null);
    t.expect(tools and msg(id, window, "firstResponder", .{}) != page, "Lab opens from read mode");
    stub.key(53, 0);
    labMenu(null, null, null);
    const guide_control = msg(id, window, "firstResponder", .{});
    t.expect(guide_control != page, "Lab focuses the guide first");
    stub.key(36, 0);
    t.expect(msg(id, window, "firstResponder", .{}) != guide_control and reading == null, "Return opens the in-window guide without running a pass");
    stub.key(53, 0);
    t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape from the guide restores editor focus");
    labMenu(null, null, null);
    const shield = msg(id, msg(id, window, "contentView", .{}), "hitTest:", .{NSPoint{ .x = 1, .y = 1 }});
    msg(void, shield, "mouseDown:", .{@as(id, null)});
    t.expect(msg(id, window, "firstResponder", .{}) == page, "An outside click dismisses Lab and restores focus");
    // The test has no event loop to close undo groups between commands.
    msg(void, um, "setGroupsByEvent:", .{false});
    select(.{ .location = 10, .length = 4 }); // manual ghost immediately after "really "
    stub.command(&ghost);
    const trim = stub.reply(.slight, cut);
    landed(trim);
    t.expect(trim.owner != null and stub.ghostValue(3) == trim.owner and stub.ghostValue(10) == yes, "Lab and adjacent manual ghosts have distinct ownership");
    t.expect(validateMenuItem(null, null, next_item), "Lab review menu is enabled for a review");
    const saved_review = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable;
    t.expect(saved_review.ghosts.len == 2, "save captures Lab and manual ghosts");

    stub.command(&labKeep);
    t.expect(stub.ghostValue(3) == null and stub.ghostValue(10) == yes, "Keep restores only the proposed ghost");
    msg(void, um, "undo", .{});
    t.expect(stub.ghostValue(3) == trim.owner and trim.hits.?.items.len == 1, "Undo Keep restores the proposed ghost and its hit");
    msg(void, um, "redo", .{});
    t.expect(stub.ghostValue(3) == null and trim.hits.?.items.len == 0, "Redo Keep skips the cut again");
    msg(void, um, "undo", .{});
    select(.{ .location = 10, .length = 4 });
    stub.command(&ghost);
    t.expect(stub.ghostValue(3) == trim.owner and stub.ghostValue(10) == null, "Ctrl+/ on a manual ghost leaves the adjacent proposal alone");
    msg(void, um, "undo", .{});
    select(.{ .location = 3, .length = 11 });
    stub.command(&ghost);
    t.expect(stub.ghostValue(3) == null and stub.ghostValue(10) == yes, "Ctrl+/ on a proposal skips it without reviving an adjacent manual ghost");
    msg(void, um, "undo", .{});
    labOriginal(null, null, null);
    t.expect(reading == null and stub.ghostValue(3) == null and stub.ghostValue(10) == yes, "Discard clears proposals restored by Undo but not manual ghosts");
    msg(void, um, "undo", .{});
    t.expect(reading == null and stub.ghostValue(3) != null and stub.ghostValue(10) == yes, "Undo Discard restores ghosts without reopening the review");

    load(trim_draft);
    select(.{ .location = 10, .length = 4 });
    stub.command(&ghost);
    landed(stub.reply(.slight, cut));
    labApply(null, null, null);
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), "We need this today. Keep my note.") and stub.ghostValue(3) == yes, "Apply deletes only proposal text, preserving the adjacent manual ghost");
    msg(void, um, "undo", .{});
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), trim_draft) and stub.ghostValue(10) == yes, "Undo Apply restores the cut without disturbing manual ghosts");

    const strength_draft = "We really need this today. Birds quietly cross the open field. A long passage stays right where it is.";
    const cuts = "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":2},{\"sentence\":2,\"shortened\":\"Birds cross the open field.\",\"importance\":5}]";
    load(strength_draft);
    const session = stub.reply(.slight, cuts);
    landed(session);
    const second = std.mem.indexOf(u8, strength_draft, "quietly").?;
    const larger = lab.parse(arena, .half, strength_draft, cuts) catch unreachable;
    t.expect(larger[0].at == 0 and larger[0].text.len > 10, "the stronger trim proposes a larger cut across the first hit");
    t.expect(session.hits.?.items.len == 2 and stub.ghostValue(3) == session.owner, "the slight trim proposes two padding cuts");
    stub.command(&labKeep);
    stub.strength(.half);
    t.expect(reading == session and session.pass.? == .half and stub.ghostValue(0) == null and stub.ghostValue(3) == null and stub.ghostValue(second) == session.owner, "switching strength skips a larger cut that overlaps a kept span");
    stub.strength(.slight);
    t.expect(reading == session and stub.ghostValue(3) == null and stub.ghostValue(second) == session.owner, "switching back does not re-ghost the kept cut");
    stub.command(&labKeep);
    stub.strength(.half);
    t.expect(reading == session and session.hits.?.items.len == 0 and stub.ghostValue(second) == null, "keeping the last cut still preserves choices across strengths");

    load(trim_draft);
    landed(stub.reply(.slight, cut));
    stub.beginEvent();
    insert(page, "!", .{ .location = len() });
    stub.endEvent();
    t.expect(reading == null and stub.ghostValue(3) == yes, "editing ends the review and leaves its ghosts ordinary");
    labOriginal(null, null, null);
    const after_edit = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable;
    t.expect(std.mem.eql(u8, after_edit.body, trim_draft ++ "!") and after_edit.ghosts.len == 1, "ending the review neither deletes ghost text nor stops saving it");
    msg(void, um, "undo", .{});
    t.expect(reading == null and stub.ghostValue(3) == yes, "Undo editing does not reopen the review");

    load("The first hedge.\n" ++ "A line of filler.\n" ** 120 ++ "The last hedge.");
    landed(stub.reply(.hedges, "[{\"paragraph\":1,\"text\":\"first\"},{\"paragraph\":122,\"text\":\"last\"}]"));
    const last = reading.?.hits.?.items[1].range;
    msg(void, layout, "ensureLayoutForCharacterRange:", .{last});
    const last_glyph = msg(usize, layout, "glyphIndexForCharacterAtIndex:", .{last.location});
    const line = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ last_glyph, @as(?*NSRange, null) });
    const bottom = msg(NSPoint, page, "textContainerOrigin", .{}).y + line.origin.y + line.size.height;
    const viewport = msg(NSRect, page, "visibleRect", .{}).size.height;
    msg(void, page, "scrollPoint:", .{NSPoint{ .y = bottom - viewport + 16 }});
    labNext(null, null, null);
    const visible = msg(NSRect, page, "visibleRect", .{});
    t.expect(reading.?.current == 1 and bottom <= visible.origin.y + visible.size.height - 92, "Next scrolls the last hit clear of the bottom card");

    msg(void, um, "setGroupsByEvent:", .{true});
    load("We teh writers have words.");
    landed(stub.reply(.typos, "[{\"paragraph\":1,\"text\":\"teh\",\"replacement\":\"the\"}]"));
    t.expect(std.mem.startsWith(u8, objc.utf8(string(page)), "We teh"), "a correction is only a proposal");
    labApply(null, null, null);
    t.expect(std.mem.startsWith(u8, objc.utf8(string(page)), "We the"), "explicit Apply fixes the typo");
    const obsolete = stub.reply(.hedges, "[]");
    load("A different piece.");
    landed(obsolete);
    t.expect(reading == null and !msg(bool, window, "isDocumentEdited", .{}), "a late reading cannot change a new document");

    // Keep the second occurrence hidden across a length-changing swap, UTF-16 edits,
    // and reopening. A mixed span must never silently publish its hidden substring.
    const repeated = "echo echo end";
    const rec = doc.GroupRec{ .at = 5, .variants = &.{ "echo", "different" } };
    load(doc.serialize(arena, .{ .body = repeated, .groups = &.{rec}, .ghosts = &.{.{ .at = 5, .text = "echo" }} }) catch unreachable);
    flip(groups.keys()[0], 1);
    select(.{ .length = 4 });
    insert(page, "๐Ÿ’ครฉ", selection());
    const moved_file = snapshot(arena) catch unreachable;
    t.expect(std.mem.endsWith(u8, moved_file, "\n\n๐Ÿ’ครฉ  end"), "a fully ghosted replacement stays out of published text");
    load(moved_file);
    const moved_ghost = runAt(key_ghost, doc.utf16Len("๐Ÿ’ครฉ ")).?;
    t.expect(std.mem.eql(u8, textOf(moved_ghost.range), "different"), "the ghost follows the edited second occurrence through save/load");
    load(doc.serialize(arena, .{ .body = repeated, .groups = &.{rec}, .ghosts = &.{.{ .at = 6, .text = "ch" }} }) catch unreachable);
    const mixed = groups.keys()[0];
    flip(mixed, 1);
    removeShown(mixed);
    t.expect(groups.get(mixed).?.active == 0 and groups.get(mixed).?.variants.items.len == 2 and !msg(bool, alts, "isEditable", .{}), "a mixed ghost cannot be overwritten by flipping, removing, or typing a variant");
    t.expect(std.mem.endsWith(u8, snapshot(arena) catch unreachable, "\n\necho eo end"), "a blocked swap leaves the original ghost intact");

    // A ghost whose place was edited away goes to Overflow, and the next save makes that so.
    const placed = doc.serialize(arena, .{ .body = "The tension is real. Maybe cut this. And more to come.", .ghosts = &.{.{ .at = 21, .text = "Maybe cut this. " }} }) catch unreachable;
    load(std.mem.replaceOwned(u8, arena, placed, "\n\nThe tension", "\n\nThe whole tension") catch unreachable);
    t.expect(std.mem.eql(u8, textOf(runAt(key_ghost, 27).?.range), "Maybe cut this. ") and !msg(bool, window, "isDocumentEdited", .{}), "a ghost keeps its place through an edit elsewhere in the file");
    const away = std.mem.replaceOwned(u8, arena, placed, "The tension is real. And more to come.", "Something else altogether.") catch unreachable;
    load(away);
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), "Something else altogether.") and std.mem.eql(u8, objc.utf8(string(over)), "Maybe cut this. "), "one with no place left is in Overflow, and the rest opens as usual");
    t.expect(overflow_open and msg(bool, window, "isDocumentEdited", .{}) and std.mem.eql(u8, lab_message.items, displaced_note), "in sight, and waiting to be saved");
    const resaved = snapshot(arena) catch unreachable;
    const healed = std.mem.replaceOwned(u8, arena, resaved, "Something else altogether.", "The tension is real. And more to come.") catch unreachable;
    load(healed);
    t.expect(std.mem.eql(u8, objc.utf8(string(over)), "Maybe cut this. ") and std.mem.eql(u8, objc.utf8(string(page)), "The tension is real. And more to come.") and runAt(key_ghost, 21) == null, "once saved it stays there, though its place comes back");
    t.expect(!msg(bool, window, "isDocumentEdited", .{}) and lab_message.items.len == 0 and std.mem.eql(u8, healed, snapshot(arena) catch unreachable), "as any stashed text does");
    toggleOverflow(null, null, null);
    _ = msg(bool, window, "makeFirstResponder:", .{page});

    // Markdown changes display attributes without changing the draft or its annotations.
    const raw_md = "๐Ÿ’ค **bold _and italic_** `*code*` ~~cut~~\n__second__\n\\*literal*";
    const bold_at = doc.utf16Len("๐Ÿ’ค **");
    const italic_at = doc.utf16Len("๐Ÿ’ค **bold _");
    const code_at = doc.utf16Len("๐Ÿ’ค **bold _and italic_** `");
    const cut_at = doc.utf16Len("๐Ÿ’ค **bold _and italic_** `*code*` ~~");
    const second_at = doc.utf16Len("๐Ÿ’ค **bold _and italic_** `*code*` ~~cut~~\n__");
    const md_style = struct {
        fn at(key: id, i: usize) id {
            return msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key, i, @as(?*NSRange, null) });
        }
    };
    const md_rec = doc.GroupRec{ .at = "๐Ÿ’ค **".len, .variants = &.{ "bold", "strong" } };
    load(doc.serialize(arena, .{ .body = raw_md, .groups = &.{md_rec}, .ghosts = &.{.{ .at = "๐Ÿ’ค **".len, .text = "bold" }} }) catch unreachable);
    t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and md_style.at(NSFontAttributeName, bold_at) == bold, "strong markup stays in storage while its delimiters hide");
    t.expect(md_style.at(NSFontAttributeName, italic_at) == bold_italic and md_style.at(NSFontAttributeName, code_at) == code_font and md_style.at(NSStrikethroughStyleAttributeName, cut_at) == markdown_line, "nested emphasis, code and strike have distinct styling");
    t.expect(md_style.at(NSFontAttributeName, second_at) == bold and md_style.at(NSFontAttributeName, len() - 1) == font, "Markdown handles other paragraphs and leaves escaped delimiters literal");
    select(.{ .location = bold_at + 1 });
    t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == font and selection().location == bold_at + 1, "moving inside inline markup reveals its source without moving the caret");
    const typed_attrs = msg(id, page, "typingAttributes", .{});
    t.expect(msg(id, typed_attrs, "objectForKey:", .{NSFontAttributeName}) == font and msg(id, typed_attrs, "objectForKey:", .{key_group}) != null and msg(id, typed_attrs, "objectForKey:", .{key_ghost}) == yes, "Markdown does not replace typing or metadata attributes");
    select(.{ .location = len() });
    t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and !msg(bool, um, "canUndo", .{}), "leaving a span hides its markers without an Undo step");
    const saved_md = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable;
    t.expect(std.mem.eql(u8, saved_md.body, raw_md) and saved_md.groups.len == 1 and saved_md.ghosts.len == 1, "save retains raw Markdown, group and ghost");
    const close_strong = doc.utf16Len("๐Ÿ’ค **bold _and italic_");
    stub.beginEvent();
    insert(page, "", .{ .location = close_strong, .length = 2 });
    stub.endEvent();
    t.expect(md_style.at(NSFontAttributeName, bold_at) == font and md_style.at(NSFontAttributeName, italic_at) == italic and md_style.at(NSFontAttributeName, second_at - 2) == bold, "breaking a pair clears old styling without touching another paragraph");
    msg(void, um, "undo", .{});
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), raw_md) and md_style.at(NSFontAttributeName, bold_at) == bold, "Undo restores both source and rendered formatting");
    msg(void, um, "redo", .{});
    t.expect(md_style.at(NSFontAttributeName, bold_at) == font, "Redo recalculates formatting instead of restoring a style operation");
    load("## Two\n###### Six");
    select(.{ .location = len() });
    t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 7) == font, "the caret at the end of the last heading reveals just that heading's hashes");
    select(.{ .location = 5 });
    t.expect(md_style.at(NSFontAttributeName, 0) == font and md_style.at(NSFontAttributeName, 7) == hidden, "moving between heading titles switches the visible prefix");

    // Fenced code: nothing in it is Markdown, and the fences show only with the caret in the block.
    load("```zig\n# **raw**\n```\n**after**");
    select(.{ .location = len() });
    t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 17) == hidden, "a code block's fences are out of sight while the caret is elsewhere");
    t.expect(md_style.at(NSFontAttributeName, 7) == code_font and md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "what is fenced is code, hashes and stars and all, and what follows is not");
    select(.{ .location = 8 });
    t.expect(md_style.at(NSFontAttributeName, 0) == code_font and md_style.at(NSFontAttributeName, 17) == code_font, "the caret in the block shows both fences");
    msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }});
    stub.beginEvent();
    insert(page, "", .{ .length = 1 });
    stub.endEvent();
    t.expect(md_style.at(NSFontAttributeName, 10) == bold and md_style.at(NSFontAttributeName, 16) == hidden and md_style.at(NSFontAttributeName, 22) == code_font, "breaking a fence restyles all that follows: the old closing fence now opens");
    msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }});
    t.expect(msg(u16, layout, "CGGlyphAtIndex:", .{@as(usize, 22)}) == msg(u32, code_font, "glyphWithName:", .{str("a")}), "in the code font's own glyphs, not the ones laid out before");
    msg(void, um, "undo", .{});
    t.expect(md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "and Undo puts the block back");
    t.expect(std.mem.eql(u8, snapshot(arena) catch unreachable, "```zig\n# **raw**\n```\n**after**"), "none of which is in the file");

    // Frontmatter, rules, quotes and links show as what they mean until the caret is on them.
    const blocks = "---\ntitle: a_b_c\n---\n\n---\n\n> quoted **loud**\n\ntext\n---\nsee [the _docs_](https://a.b/c_d_e) and ![img](x)";
    const find = struct {
        fn at(comptime text: []const u8, comptime what: []const u8) usize {
            return comptime std.mem.indexOf(u8, text, what).?;
        }
    }.at;
    const rule_at = find(blocks, "\n\n---\n\n") + 2;
    const quote_at = find(blocks, "> quoted");
    const link_at = find(blocks, "[the");
    const target_at = find(blocks, "c_d_e") + 2;
    const img_at = find(blocks, "[img");
    load(blocks);
    select(.{ .location = len() });
    t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 17) == hidden and md_style.at(key_rule, 0) == null and md_style.at(NSFontAttributeName, find(blocks, "b_c")) == code_font, "frontmatter is a block of code between delimiters that are not rules");
    t.expect(md_style.at(key_rule, rule_at) == yes and md_style.at(NSFontAttributeName, rule_at) == hidden, "a line of hyphens is a rule, its hyphens out of sight");
    t.expect(md_style.at(key_rule, find(blocks, "text\n---") + 5) == null and md_style.at(NSFontAttributeName, find(blocks, "text\n---") + 5) == font, "but not right under a line of text, where it would make a heading");
    t.expect(md_style.at(key_quote, quote_at) == yes and md_style.at(NSFontAttributeName, quote_at) == hidden and md_style.at(NSFontAttributeName, find(blocks, "loud")) == bold, "a quoted line has a bar for its marker, and its own formatting");
    t.expect(msg(bool, md_style.at(NSParagraphStyleAttributeName, quote_at), "isEqual:", .{quote_hidden}) and msg(bool, md_style.at(NSParagraphStyleAttributeName, rule_at), "isEqual:", .{spaced}), "and it alone is indented");
    t.expect(md_style.at(NSFontAttributeName, link_at) == hidden and md_style.at(NSFontAttributeName, target_at) == hidden and md_style.at(NSFontAttributeName, find(blocks, "docs")) == italic, "a link shows as its text, formatted, and its target's underscores are not emphasis");
    t.expect(md_style.at(NSUnderlineStyleAttributeName, link_at + 1) == markdown_line and msg(bool, md_style.at(NSForegroundColorAttributeName, link_at + 1), "isEqual:", .{color.link}) and md_style.at(NSUnderlineStyleAttributeName, link_at - 1) == null, "underlined, in a color of its own");
    t.expect(md_style.at(NSFontAttributeName, img_at) == font and md_style.at(NSUnderlineStyleAttributeName, img_at + 1) == null, "an image is left as written");
    select(.{ .location = rule_at + 1 });
    t.expect(md_style.at(key_rule, rule_at) == null and md_style.at(NSFontAttributeName, rule_at) == font, "the caret on a rule shows its hyphens");
    select(.{ .location = quote_at + 3 });
    t.expect(md_style.at(key_rule, rule_at) == yes and md_style.at(key_quote, quote_at) == null and md_style.at(NSFontAttributeName, quote_at) == font, "and on a quoted line its marker");
    t.expect(msg(bool, md_style.at(NSParagraphStyleAttributeName, quote_at), "isEqual:", .{quote_shown}), "with the text left standing where it was");
    select(.{ .location = link_at + 2 });
    t.expect(md_style.at(key_quote, quote_at) == yes and md_style.at(NSFontAttributeName, link_at) == font and md_style.at(NSFontAttributeName, target_at) == font and md_style.at(NSUnderlineStyleAttributeName, link_at + 1) == markdown_line, "and in a link its brackets and its target");
    t.expect(!msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, blocks), "none of which is an edit, or in the file");
    msg(void, over, "setString:", .{str("Kept.")});
    const fronted = snapshot(arena) catch unreachable;
    t.expect(std.mem.startsWith(u8, fronted, "---\ntitle: a_b_c\n---\n<!-- overflow\n(Kept.)-->\n\n\n---\n"), "the file's comments go after its frontmatter");
    load(fronted);
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), blocks) and std.mem.eql(u8, objc.utf8(string(over)), "Kept."), "and it opens as it was");

    load("text\n***\n_ _ _\ntext\n---");
    t.expect(md_style.at(key_rule, 5) == yes and md_style.at(key_rule, 9) == yes and md_style.at(NSFontAttributeName, 5) == hidden and md_style.at(key_rule, 20) == null, "asterisks and underscores rule the page off too, under text as only hyphens cannot");

    // Frontmatter needs the line that closes it. Without one its first line is only a rule.
    load("---\ntitle: x\n---\nbody");
    select(.{ .location = len() });
    t.expect(md_style.at(NSFontAttributeName, 4) == code_font and md_style.at(key_rule, 0) == null, "closed frontmatter is code");
    stub.beginEvent();
    insert(page, "", .{ .location = 13, .length = 4 });
    stub.endEvent();
    t.expect(md_style.at(NSFontAttributeName, 4) == font and md_style.at(key_fence, 4) == null and md_style.at(key_rule, 0) == yes, "taking its closing line away restyles it from the top");
    msg(void, um, "undo", .{});
    t.expect(md_style.at(NSFontAttributeName, 4) == code_font and md_style.at(key_rule, 0) == null and md_style.at(NSFontAttributeName, 0) == hidden, "and Undo makes frontmatter of it again");

    // A comment shows as a ghost does, its delimiters out of sight, and the file keeps it as it is.
    const noted = "Live **text** <!-- aside --> here, `<!-- code -->`.\n\n<!--\n## Cut _part_\n\n```\n> said\n---\n-->\nAfter.\n";
    const ink = struct {
        fn at(i: usize) id {
            return msg(id, layout, "temporaryAttribute:atCharacterIndex:effectiveRange:", .{ NSForegroundColorAttributeName, i, @as(?*NSRange, null) });
        }
    };
    const aside_at = find(noted, "aside");
    const open_at = find(noted, "<!--\n");
    const cut_head = find(noted, "Cut");
    const shut_at = find(noted, "-->\nAfter");
    load(noted);
    select(.{ .location = len() });
    t.expect(ink.at(aside_at) == color.ghost and ink.at(cut_head) == color.ghost and ink.at(0) == null and ink.at(shut_at + 4) == null, "a comment is as dim as a ghost, and what is around it is not");
    t.expect(md_style.at(NSFontAttributeName, aside_at - 3) == hidden and md_style.at(NSFontAttributeName, open_at) == hidden and md_style.at(NSFontAttributeName, shut_at) == hidden, "its delimiters are out of sight");
    t.expect(md_style.at(NSFontAttributeName, cut_head) == bold and md_style.at(NSFontAttributeName, find(noted, "part")) == bold_italic and md_style.at(NSFontAttributeName, find(noted, "## Cut")) == hidden, "it is formatted");
    t.expect(md_style.at(key_fence, find(noted, "```")) == null and md_style.at(key_quote, find(noted, "> said")) == null and md_style.at(key_rule, find(noted, "---\n-->")) == null and md_style.at(NSFontAttributeName, find(noted, "---\n-->")) == font, "but opens no code, and draws no bar or rule");
    t.expect(md_style.at(NSFontAttributeName, find(noted, "<!-- code")) == code_font, "one in code is code");
    select(.{ .location = cut_head });
    t.expect(md_style.at(NSFontAttributeName, open_at) == font and md_style.at(NSFontAttributeName, shut_at) == font and ink.at(open_at) == null and md_style.at(NSFontAttributeName, aside_at - 3) == hidden, "the caret anywhere in one shows both its delimiters, and no other's");
    select(.{ .location = shut_at + 3 });
    t.expect(md_style.at(NSFontAttributeName, open_at) == font, "as it does against one");
    t.expect(!msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, noted), "none of which is an edit, or in the file");
    t.expect(std.mem.eql(u8, proseAround(arena, .{ .length = 4 }), "Live **text**  here, `<!-- code -->`.\n") and std.mem.indexOf(u8, proseAround(arena, .{ .location = aside_at, .length = 5 }), "aside") != null, "a question about other text leaves it out");
    stub.beginEvent();
    insert(page, "x", .{ .location = cut_head });
    stub.endEvent();
    t.expect(ink.at(cut_head) == color.ghost, "what is typed in one is in it");
    msg(void, um, "undo", .{});
    stub.beginEvent();
    insert(page, "", .{ .location = shut_at, .length = 3 });
    stub.endEvent();
    t.expect(ink.at(cut_head) == null and md_style.at(key_comment, cut_head) == null and md_style.at(NSFontAttributeName, open_at) == font and md_style.at(NSFontAttributeName, cut_head) == bold and md_style.at(key_fence, find(noted, "> said")) != null, "one that is not closed is only text, all the way back");
    msg(void, um, "undo", .{});
    select(.{ .location = len() });
    t.expect(ink.at(cut_head) == color.ghost and md_style.at(NSFontAttributeName, open_at) == hidden and md_style.at(key_fence, find(noted, "> said")) == null, "and Undo makes a comment of it again");
    select(.{ .location = cut_head + 1 });
    ghost(null, null, null);
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), "Live **text** <!-- aside --> here, `<!-- code -->`.\n\n## Cut _part_\n\n```\n> said\n---\nAfter.\n") and runAt(key_ghost, open_at) == null, "reviving one takes its delimiters away, and their lines");
    msg(void, um, "undo", .{});
    t.expect(std.mem.eql(u8, objc.utf8(string(page)), noted) and ink.at(cut_head) == color.ghost, "and one Undo puts both back");
    select(.{ .location = aside_at, .length = 12 }); // on past the end of it
    ghost(null, null, null);
    t.expect(std.mem.startsWith(u8, objc.utf8(string(page)), "Live **text** aside here, ") and runAt(key_ghost, 0) == null and runAt(key_ghost, aside_at) == null, "in a line, only the spaces that set it off go too, and nothing is ghosted");
    for ([_][2][]const u8{ .{ "a<!---->b", "ab" }, .{ "a<!-- -->b", "ab" }, .{ "<!-->", "" }, .{ "<!--\r\nA\r\n-->\r\nB", "A\r\nB" }, .{ "<!--\n-->", "" }, .{ "<!--\nA\n-->", "A\n" }, .{ "<!-- A\nB -->C", "A\nBC" } }) |c| {
        load(c[0]);
        select(.{ .length = len() });
        ghost(null, null, null);
        t.expect(std.mem.eql(u8, objc.utf8(string(page)), c[1]), c[0]);
    }
    load("We really <!-- note --> need this today. Keep my note.");
    landed(stub.reply(.slight, "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":5}]"));
    t.expect(runAt(key_ghost, find("We really", "really")) == null, "a cut that would run over a comment is not proposed");

    // A line that is all one image is its picture, in a line made tall enough to hold it.
    t.expect(msg(bool, fm, "createDirectoryAtPath:withIntermediateDirectories:attributes:error:", .{ path, false, @as(id, null), @as(?*id, null) }), "a folder for a piece and its picture");
    const bitmap = msg(id, msg(id, objc.class("NSBitmapImageRep"), "alloc", .{}), "initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:", .{
        @as(?*anyopaque, null), @as(isize, 1560), @as(isize, 780), @as(isize, 8), @as(isize, 4), true, false, NSDeviceRGBColorSpace, @as(isize, 0), @as(isize, 0),
    });
    const png = msg(id, bitmap, "representationUsingType:properties:", .{ @as(usize, 4), dict(&.{}) });
    t.expect(msg(bool, png, "writeToFile:atomically:", .{ msg(id, path, "stringByAppendingPathComponent:", .{str("a wide one.png")}), true }), "with a picture twice as wide as the column");
    const piece = "![wide](a%20wide%20one.png)\n\nsee ![it](a%20wide%20one.png)\n\n![gone](missing.png)\n";
    const tall = struct {
        fn height() f64 {
            return msg(f64, msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSParagraphStyleAttributeName, @as(usize, 0), @as(?*NSRange, null) }), "minimumLineHeight", .{});
        }
    }.height;
    setPath(null);
    load(piece);
    select(.{ .location = len() });
    t.expect(md_style.at(key_picture, 0) == null and md_style.at(NSFontAttributeName, 0) == font, "an unsaved piece has nowhere to look for a picture from");
    setPath(objc.utf8(msg(id, path, "stringByAppendingPathComponent:", .{str("piece.md")})));
    const room = msg(NSSize, container, "containerSize", .{}).width - 2 * msg(f64, container, "lineFragmentPadding", .{});
    t.expect(md_style.at(key_picture, 0) != null and md_style.at(NSFontAttributeName, 0) == hidden and tall() == @ceil(room / 2), "saved beside it, the line is its picture, fitted to the column");
    t.expect(md_style.at(key_picture, find(piece, "see")) == null and md_style.at(key_picture, find(piece, "![gone")) == null and md_style.at(NSFontAttributeName, find(piece, "![gone")) == font, "an image among text, or with no file, stays as written");
    const frame = linesOf(.{ .length = 1 }).?;
    const clicked = msg(usize, page, "characterIndexForInsertionAtPoint:", .{NSPoint{ .x = frame.origin.x + room / 2, .y = frame.origin.y + frame.size.height / 2 }});
    t.expect(frame.size.height >= tall() and clicked <= find(piece, "\n"), "a click anywhere on the picture lands in its line");
    select(.{ .location = clicked });
    t.expect(md_style.at(key_picture, 0) == null and md_style.at(NSFontAttributeName, 0) == font and msg(bool, md_style.at(NSParagraphStyleAttributeName, 0), "isEqual:", .{spaced}), "and the caret there puts its source back");
    select(.{ .location = len() });
    msg(void, container, "setContainerSize:", .{NSSize{ .width = room / 2 + 2 * msg(f64, container, "lineFragmentPadding", .{}), .height = 1e7 }});
    refitPictures();
    t.expect(tall() == @ceil(room / 4), "a narrower column has a shorter picture");
    resized(null, null, null);
    t.expect(tall() == @ceil(room / 2) and !msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, piece), "and none of it is an edit, or in the file");
    setPath(null);
    t.expect(md_style.at(key_picture, 0) == null and msg(bool, fm, "removeItemAtPath:error:", .{ path, @as(?*id, null) }), "remove the folder");
    msg(void, document_defaults, "removePersistentDomainForName:", .{unique});
    std.debug.print("selftest ok\n", .{});
}