summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: e1adb05f9416d3dd9f966b74e1256cef4043d2e8 (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
//! 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 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 NSUnderlineColorAttributeName: id;
extern const NSBackgroundColorAttributeName: id;
extern const NSParagraphStyleAttributeName: id;
extern const NSViewFrameDidChangeNotification: id;
extern const NSAppearanceNameDarkAqua: 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 yes: id = null;
var font: id = null;
var bold: id = null;
var small: id = null;
var hidden: id = null; // the font of a heading's marker: too small to see
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 } = undefined;

var groups: std.AutoArrayHashMapUnmanaged(u32, doc.Group) = .empty;
var next_id: u32 = 1;
var file_path: ?[]u8 = null;
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 last_caret: usize = 0;

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 });
    };
    headings();

    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);

    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,
    };
}

/// The only Markdown rendered so far: a line that opens with "# " is a heading, in bold,
/// and its marker is out of sight. The marker stays in the text, in a font too small to
/// see. A font cannot be a temporary attribute, so these go into the storage, and only
/// where they are wrong.
fn headings() void {
    const n = len();
    var i: usize = 0;
    while (i < n) {
        const para = paragraphOf(page, .{ .location = i });
        const mark_r: NSRange = .{ .location = para.location, .length = marker(para) };
        setFont(mark_r, hidden);
        setFont(.{ .location = end(mark_r), .length = para.length - mark_r.length }, if (mark_r.length > 0) bold else font);
        if (mark_r.length > 0) tint(NSForegroundColorAttributeName, color.clear, mark_r);
        i = end(para);
    }
}

fn setFont(r: NSRange, want: id) void {
    if (r.length == 0) return;
    var run: NSRange = .{};
    const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ NSFontAttributeName, r.location, &run, r });
    if (have != want or run.length < r.length) msg(void, storage, "addAttribute:value:range:", .{ NSFontAttributeName, want, r });
}

/// How much of a paragraph is a heading's marker: three characters of "## Title".
fn marker(para: NSRange) usize {
    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, 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 revive = 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 (!revive) mark(r, key_ghost, yes);
}

/// 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 gap = if (have.len == 0 or std.mem.endsWith(u8, have, "\n\n")) "" else if (have[have.len - 1] == '\n') "\n" else "\n\n";
    const entry = std.mem.concat(gpa, u8, &.{ gap, 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;
}

/// 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, textOf(paragraphOf(page, 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, sender: id) callconv(.c) void {
    lab_ui.openMenu(sender);
}

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 manual ghost or a kept span.
        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();
    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(.{});
    keepOut();
    msg(void, page, "scrollPoint:", .{NSPoint{}});
    setDirty(false);
    panels();
    typing();
    refresh();
}

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 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)});
    } else {
        msg(void, window, "setRepresentedFilename:", .{str("")});
        msg(void, window, "setTitle:", .{str("Untitled")});
    }
}

fn openPath(path: []const u8) bool {
    const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)});
    if (data == null) {
        alert("That file could not be read.", path);
        return false;
    }
    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)) {
        alert("That file is not UTF-8 text.", path);
        return false;
    }
    load(bytes);
    setPath(path);
    return true;
}

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);
    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;
    keepOut();
    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
}

/// A heading's marker is out of sight, and the caret stays out of it. Stepping left from a
/// heading's first letter goes to the end of the line above.
fn keepOut() void {
    defer last_caret = selection().location;
    const sel = selection();
    if (sel.length > 0) return;
    const para = paragraphOf(page, sel);
    const first = para.location + marker(para);
    if (sel.location >= first) return;
    const stepped_left = last_caret == first and sel.location + 1 == first and para.location > 0;
    select(.{ .location = if (stepped_left) para.location - 1 else first });
}

/// 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 }});
    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 {
    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();
    }
    if (plain and key == Key.backspace and sel.length == 0) { // before a heading's first letter: no longer a heading
        const para = paragraphOf(page, sel);
        const m = marker(para);
        if (m > 0 and sel.location == para.location + m) return insert(page, "", .{ .location = para.location, .length = m });
    }
    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});
    const sel = selection();
    if (charUnder(event)) |i| if (i < sel.location or i >= end(sel)) select(.{ .location = i });
    const cs = Mod.ctrl | Mod.shift;
    const menu = msg(id, objc.new("NSMenu"), "autorelease", .{});
    var buf: [2][160]u8 = undefined;
    item(menu, menuTitle(&buf[0], "Alternatives"), "alternative:", "a", cs, ctl);
    item(menu, menuTitle(&buf[1], "AI alternatives"), "aiAlternative:", "g", cs, ctl);
    item(menu, if (ghostIn(ghostable())) "Revive it" else "Ghost it", "ghost:", "/", Mod.ctrl, ctl);
    item(menu, "Stash this in Overflow", "stash:", "x", cs, ctl);
    return menu;
}

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});
    if (!tools) return;
    const origin = msg(NSPoint, self, "textContainerOrigin", .{});
    const container = msg(id, self, "textContainer", .{});
    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", .{});
        }
    }
}

/// 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 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 = "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 = "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 = "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),
    };
    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", .{});
    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", .{});
    yes = msg(id, msg(id, objc.class("NSNumber"), "numberWithBool:", .{true}), "retain", .{});
    const 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})});
    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", .{});
    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, 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, "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);

    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();

    load(@embedFile("welcome.md")); // until `openFile` is handed something else
    setPath(null);

    const regular: isize = 0;
    _ = msg(bool, app, "setActivationPolicy:", .{regular});
    msg(void, window, "makeKeyAndOrderFront:", .{@as(id, null)});
    _ = msg(bool, window, "makeFirstResponder:", .{page});
    msg(void, app, "activateIgnoringOtherApps:", .{true});
    msg(void, app, "run", .{});
}

// --- 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", .{});

    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);

    // The heading's marker is in the text and out of sight, and the caret keeps out of it.
    t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "a heading's marker is hidden");
    t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "and the heading is bold");
    t.expect(selection().location == 2, "the caret starts after the marker");
    select(.{ .location = 1 });
    t.expect(selection().location == 2, "and cannot be put inside it");

    // 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;
    const menu = contextMenu(page, null, 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),
    }));
    t.expect(msg(isize, menu, "numberOfItems", .{}) == 4, "the right-click menu has four commands");
    const title = objc.utf8(msg(id, msg(id, menu, "itemAtIndex:", .{@as(isize, 0)}), "title", .{}));
    t.expect(std.mem.find(u8, title, first) != null, "and the first names the word under the pointer");

    // 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 strength(pass: lab.Pass) void {
            const item_ = objc.new("NSMenuItem");
            defer msg(void, item_, "release", .{});
            msg(void, item_, "setTag:", .{@as(isize, @intFromEnum(pass))});
            labPass(null, null, item_);
        }
        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);
    // 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");
    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");
    std.debug.print("selftest ok\n", .{});
}