summaryrefslogtreecommitdiff
path: root/core/jj.zig
blob: 618f363e310bafa5ae600e9b3bcc84feba9e718b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
//! A file at a revision, as jj shows it (PARDES.md "Changes on the source
//! view"): the address `path@rev`, with a place `path@rev:line`, which a
//! Look resolves anywhere, and `At <rev>` in a file's pane.
//!
//! What jj says is the session machine's: it is run out of the turn as a
//! site of the step's tape (`Site.jj`), its answer recorded; a replica
//! replays the answer and never runs jj. A revision's pane is an output
//! (`Output.Origin.revision`, its argument the revision), named
//! `path@rev`, coloured as its file (File.langPath), read-only (File.edit
//! refuses its text a change; a bare Save says why).
const std = @import("std");
const pardes = @import("root.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const File = pardes.panes.File;
const Output = pardes.panes.Output;
const look = @import("look.zig");
const layout = @import("layout.zig");
const diff = @import("diff.zig");
const syntax = @import("syntax.zig");

/// What jj answered: why not, in its own words (its first line, without
/// `Error: `), or the file's bytes. The caller's, in the allocator the site
/// was given.
pub const Shown = union(enum) { refused: []u8, bytes: []u8 };

/// The longest text a revision's pane takes.
const bytes_max = 256 << 20;

/// `text`, not a file of its own, read as `path@rev`: the text before its
/// first `@` the path, the rest the revision (`main`, `@-`, `main@origin`).
pub fn split(text: []const u8) ?struct { path: []const u8, rev: []const u8 } {
    const at = std.mem.indexOfScalar(u8, text, '@') orelse return null;
    if (at == 0 or at + 1 == text.len or text[at - 1] == '/') return null;
    return .{ .path = text[0..at], .rev = text[at + 1 ..] };
}

/// The file at `path` (absolute) at revision `rev`, as jj shows it.
pub fn show(p: *Pardes, path: []const u8, rev: []const u8) Shown {
    const set = fileset(p.scratch.allocator(), path) catch return refusal(p.gpa, "out of memory");
    return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "show", "-r", rev, "--", set }) });
}

fn dirOf(path: []const u8) []const u8 {
    return std.Io.Dir.path.dirname(path) orelse "/";
}

/// The name of `path` as a fileset of that one file in its directory,
/// taken literally whatever it is called.
fn fileset(arena: std.mem.Allocator, path: []const u8) ![]u8 {
    var set: std.ArrayList(u8) = .empty;
    try set.appendSlice(arena, "file:\"");
    for (std.Io.Dir.path.basename(path)) |c| {
        if (c == '"' or c == '\\') try set.append(arena, '\\');
        try set.append(arena, c);
    }
    try set.append(arena, '"');
    return set.toOwnedSlice(arena);
}

/// jj with `args`, run in `dir`: what it printed, or its refusal. The
/// working copy is left alone (`--ignore-working-copy`): an editor's read
/// makes no operation, and `@` is the working copy as jj last saw it.
fn runHost(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown {
    // The tape's io spawns nothing (its allocator fails, its environment is
    // empty): one of its own, with this process's environment.
    var threaded: std.Io.Threaded = .init_single_threaded;
    threaded.allocator = gpa;
    threaded.environ = .{ .process_environ = .{ .block = .{ .slice = std.mem.span(std.c.environ) } } };
    threaded.environ_initialized = false;
    const io = threaded.io();
    var argv: std.ArrayList([]const u8) = .empty;
    defer argv.deinit(gpa);
    argv.appendSlice(gpa, &.{ "jj", "--ignore-working-copy", "--color=never", "--no-pager" }) catch return refusal(gpa, "out of memory");
    argv.appendSlice(gpa, args) catch return refusal(gpa, "out of memory");
    // As Stream's children: this thread's mask is the child's.
    const none = std.posix.sigemptyset();
    var kept: std.posix.sigset_t = undefined;
    std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept);
    var child = std.process.spawn(io, .{ .argv = argv.items, .cwd = .{ .path = dir }, .stdin = .ignore, .stdout = .pipe, .stderr = .pipe }) catch |err| {
        std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null);
        return refusal(gpa, if (err == error.FileNotFound) "no jj" else @errorName(err));
    };
    std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null);
    defer child.kill(io);
    // One after the other, on an io with no thread to read both at once:
    // jj says a refusal in a line and nothing on stdout.
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(gpa);
    var err: std.ArrayList(u8) = .empty;
    defer err.deinit(gpa);
    for ([_]std.Io.File{ child.stdout.?, child.stderr.? }, [_]*std.ArrayList(u8){ &out, &err }, [_]usize{ bytes_max, 64 << 10 }) |from, to, cap| {
        var chunk: [64 * 1024]u8 = undefined;
        while (to.items.len <= cap) {
            const n = from.readStreaming(io, &.{&chunk}) catch break;
            if (n == 0) break;
            to.appendSlice(gpa, chunk[0..n]) catch return refusal(gpa, "out of memory");
        }
    }
    const term = child.wait(io) catch |e| return refusal(gpa, @errorName(e));
    if (out.items.len > bytes_max) return refusal(gpa, "too much to show");
    if (term == .exited and term.exited == 0) return .{ .bytes = out.toOwnedSlice(gpa) catch return refusal(gpa, "out of memory") };
    var first = std.mem.trim(u8, err.items[0 .. std.mem.indexOfScalar(u8, err.items, '\n') orelse err.items.len], " \t\r");
    if (std.mem.startsWith(u8, first, "Error: ")) first = first["Error: ".len..];
    return refusal(gpa, if (first.len > 0) first else "jj failed");
}

fn refusal(gpa: std.mem.Allocator, why: []const u8) Shown {
    return .{ .refused = gpa.dupe(u8, why) catch &.{} };
}

/// A revision's pane: the file it is of (its name without `@rev`) and the
/// revision. Null for any other pane.
pub fn of(f: *const File.State) ?struct { path: []const u8, rev: []const u8 } {
    // The pane's own, not a copy: the revision is a slice of it.
    const o = if (f.output) |*o| o else return null;
    if (o.from != .revision) return null;
    return .{ .path = f.path[0 .. f.path.len - o.arg().len - 1], .rev = o.arg() };
}

/// `path` (absolute) at `rev` in a pane: the one showing it focused, else
/// one made beside pane `near` (or, with `replace`, in its place: it goes),
/// wearing `near`'s layers; its cursor on line `line` (0: the first). Said
/// at `near` when jj refuses. The pane's id.
pub fn open(p: *Pardes, near: usize, path: []const u8, rev: []const u8, at: look.Spot, replace: bool) ?usize {
    const name = std.fmt.allocPrint(p.scratch.allocator(), "{s}@{s}", .{ path, rev }) catch return null;
    for (p.panes, 0..) |slot, i| if (slot) |shown| if (shown.file) |*f| if (of(f) != null and std.mem.eql(u8, f.path, name)) {
        look.focusPaneLine(p, i, at, .center);
        return i;
    };
    if (rev.len > Output.max_arg) return refused(p, near, "a revision that long");
    const free = p.freeSlot() orelse {
        p.reportError(.at(near), "At", error.NoPaneSlots);
        return null;
    };
    const bytes = switch (show(p, path, rev)) {
        .refused => |why| {
            defer p.gpa.free(why);
            return refused(p, near, why);
        },
        .bytes => |b| b,
    };
    const pane = Output.open(p, free, std.Io.Dir.path.dirname(path) orelse "/", .revision, rev, bytes) catch |err| {
        p.gpa.free(bytes);
        p.reportError(.at(near), "At", err);
        return null;
    };
    const f = &pane.file.?;
    const owned = p.gpa.dupe(u8, name) catch {
        p.removePane(free, near) catch {};
        return null;
    };
    p.gpa.free(f.path);
    f.path = owned;
    if (p.panes[near]) |from| pane.layers = from.layers;
    layout.placeNew(p, near, near, free, .doc);
    if (replace) p.removePane(near, free) catch |err| p.reportError(.at(free), "At", err);
    layout.compute(p);
    // Sized for its place before it is centred there.
    p.layOut();
    look.focusPaneLine(p, free, at, .center);
    return free;
}

fn refused(p: *Pardes, id: usize, why: []const u8) ?usize {
    var line: pardes.Kind.Buf(512) = .{};
    p.reportFailure(id, line.print("At: {s}", .{why[0..@min(why.len, 480)]}));
    return null;
}

/// The `At` word (builtins.zig registers it): in a file's pane, that file
/// at revision `rev` beside it; in a revision's pane, the same file at
/// `rev` in its place, its cursor's line kept; bare there, the file.
pub fn word(c: pardes.builtins.Ctx) void {
    const p = c.p;
    const f = if (c.pane.file) |*file| file else return p.reportFailure(c.id, "At: only a file's pane takes it");
    const rev = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    const at: look.Spot = .{ .line = @intCast(@max(0, c.pane.body.cur_row) + 1) };
    if (of(f)) |r| {
        if (rev.len == 0) return look.lookAt(p, c.id, r.path);
        const path = p.scratch.allocator().dupe(u8, r.path) catch return;
        _ = open(p, c.id, path, rev, at, true);
        return;
    }
    if (f.output != null or pardes.filesystem.localPath(f.path) == null) return p.reportFailure(c.id, "At: only a file's pane takes it");
    if (rev.len == 0) return p.reportFailure(c.id, "At: which revision?");
    _ = open(p, c.id, f.path, rev, at, false);
}

/// A Look at `text` (a path relative to `dir`, then `@rev`) that names no
/// file: a file at a revision, if the path is a file. False when it is not
/// one, for the look to go on.
pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look.Spot) bool {
    const r = split(text) orelse return false;
    const path = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, r.path }) catch return false;
    if (pardes.filesystem.localPath(path) == null or pardes.exec.kindOf(p.tape, path) != .file) return false;
    _ = open(p, id, path, r.rev, at, false);
    return true;
}

// ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj
// answers for it, kept as flat arrays, the session's ----

/// What jj answered for a pane's `Changes`: replicated state, the
/// session's (`Pardes.changes`, by the pane's serial: a client never runs
/// jj; one that joins late has it in the dump), its revset with it. Shown,
/// its ghosts are lines of the pane's buffer, read-only (File.layer.lines,
/// `showLayer`), so the layer is the pane's: every view of it shows it or
/// none does. From two jj runs off the loop (`Ask`): the changes
/// with their diffs of the file (`jj log -p --git`, the diffs read with
/// diff.zig's walk), and who wrote each line of the shown revision (`jj
/// file annotate`).
pub const Changes = struct {
    pub const replica = .{ .len = .{.{ "revset", "revset_len" }} };
    /// The pane's (its serial).
    serial: u32,
    revset: [revset_max]u8 = undefined,
    revset_len: u8 = 0,
    /// The revset's changes that touch the file, oldest first.
    pins: []Pin = &.{},
    /// A value a line of the shown revision.
    lines: []Line = &.{},
    /// Each pin's hunks in the file, a pin's together, each in place order.
    hunks: []Hunk = &.{},
    /// The ghosts' text: the lines the hunks took away, hunk after hunk,
    /// each with its `\n`; then each pin's description.
    ghost_text: []u8 = &.{},
    /// The lines the layer puts in the buffer, the text has not, in `at`
    /// order (shown, the buffer's read-only lines in this order).
    ghosts: []Ghost = &.{},
    /// The words a changed line changed: byte ranges of a line (`Line`), or
    /// of `ghost_text` (`Ghost`), each `.{ from, to }`.
    marks: [][2]u32 = &.{},

    pub fn deinit(c: *Changes, gpa: std.mem.Allocator) void {
        gpa.free(c.pins);
        gpa.free(c.lines);
        gpa.free(c.hunks);
        gpa.free(c.ghost_text);
        gpa.free(c.ghosts);
        gpa.free(c.marks);
        c.* = .{ .serial = c.serial };
    }

    pub fn pinned(c: *const Changes) []const u8 {
        return c.revset[0..c.revset_len];
    }

    pub const revset_max = 64;
};

/// What jj answered for pane `serial`'s `Changes` (`Pardes.changes`), if anything.
pub fn answered(p: *Pardes, serial: u32) ?*Changes {
    for (p.changes.answers.items) |*c| if (c.serial == serial) return c;
    return null;
}

/// What jj answered for pane `serial`'s `Churn` (`Pardes.changes`), counted.
pub fn churned(p: *Pardes, serial: u32) ?*Heat {
    for (p.changes.heats.items) |*h| if (h.serial == serial) return h;
    return null;
}

/// Pane `serial`'s answers let go (the pane's end); a twin showing its
/// layer, its lines out.
pub fn forget(p: *Pardes, serial: u32) void {
    for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| if (f.layer.owner == serial and pane.serial != serial) {
        hideLayer(p, f);
        setLanes(p, f, false);
    };
    for (p.changes.answers.items, 0..) |*c, i| if (c.serial == serial) {
        c.deinit(p.gpa);
        _ = p.changes.answers.swapRemove(i);
        break;
    };
    forgetHeat(p, serial);
}

fn forgetHeat(p: *Pardes, serial: u32) void {
    for (p.changes.heats.items, 0..) |*h, i| if (h.serial == serial) {
        h.deinit(p.gpa);
        _ = p.changes.heats.swapRemove(i);
        return;
    };
}

/// A pane's `Churn [window]` (PARDES.md "Changes on the source view":
/// churn per declaration): for each line, how many of the window's changes
/// touched the declaration it is in (tree-sitter's innermost, as
/// TreeContext finds them; 0 outside any), counted in every process from
/// jj's raw answer (`heatOf`), replicated state as `Changes` is, riding
/// with the lines through edits.
pub const Heat = struct {
    pub const replica = .{ .len = .{.{ "revset", "revset_len" }} };
    serial: u32,
    /// The window as jj was asked it.
    revset: [Changes.revset_max]u8 = undefined,
    revset_len: u8 = 0,
    lines: []u16 = &.{},
    /// The file's hottest declaration's count, the gradient's top.
    hottest: u16 = 0,
    /// jj's raw answer until it is counted (`parsed`): its log, then its
    /// text of the revision from `pending_was` on.
    pending: []u8 = &.{},
    pending_was: u32 = 0,

    pub fn deinit(h: *Heat, gpa: std.mem.Allocator) void {
        gpa.free(h.lines);
        gpa.free(h.pending);
    }

    pub fn window(h: *const Heat) []const u8 {
        return h.revset[0..h.revset_len];
    }
};

/// A pinned change, as `jj log` says it.
pub const Pin = struct {
    pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } };
    id: [8]u8,
    /// Its author's time, in seconds since the epoch.
    time: i64,
    author: [32]u8 = undefined,
    author_len: u8 = 0,
    /// Its description's first line, cut to fit.
    title: [96]u8 = undefined,
    title_len: u8 = 0,
};

/// A line of the shown revision: which pin wrote it (its place in
/// `Changes.pins`) or none, and whether that pin added it whole (no line
/// it took away stood in its place) or changed one.
pub const Line = struct {
    pin: PinIndex,
    whole: bool = false,
    /// The pins whose lanes run down it, outermost (oldest) first (`nest`).
    lanes: [levels]PinIndex = @splat(.none),
    /// A changed line's words that came (`Changes.marks[marks..][0..nmarks]`,
    /// byte ranges of the line).
    marks: u32 = 0,
    nmarks: u16 = 0,
    /// The pin ahead of the shown revision that takes it away: a line
    /// going (`going`).
    going: PinIndex = .none,
};

/// The lanes a row shows at most (a window's strips the same).
pub const levels = pardes.Lane.levels;

pub const PinIndex = enum(u16) {
    none = std.math.maxInt(u16),
    _,
};

/// The changes a `Changes` takes at most.
pub const pins_max = 64;

/// A run of lines a pin took away and wrote in their place, in its own
/// revisions' numbers (from 1; `old_len` 0: it only wrote, after old line
/// `old_start`).
pub const Hunk = struct {
    /// Its pin, or `carrier`: a change between the pins the revset does
    /// not pin (its hunks only carry places, `carried`).
    pin: u16,
    /// Its change's place in jj's answer, oldest first.
    step: u16,
    /// Its change is ahead of the shown revision (a descendant): its
    /// `removed` text is what it adds (`carriedBack` carries its places).
    ahead: bool = false,
    old_start: u32,
    old_len: u32,
    new_start: u32,
    new_len: u32,
    /// Its removed lines' text: `Changes.ghost_text[removed..][0..removed_len]`.
    removed: u32,
    removed_len: u32,

    pub const carrier = std.math.maxInt(u16);
};

/// A line the layer puts in the buffer that the file has not (PARDES.md
/// "Changes on the source view": a ghost line): a line a pin took away
/// whole, where it stood, red across; or a pin's description (`id title
/// author age`, whole), after its last line, its lane an arrow to it. A
/// line a pin CHANGED has one too: its old text right above the line, the
/// words that went in red, the line with the words that came in green.
/// Shown, it is regular text, read-only (File.ReadOnly): no number, the
/// cursor goes onto it, a search finds in it, a Look looks at its word, on
/// a description's id its change's patch (`lookGhost`).
pub const Ghost = struct {
    /// The line of the shown text it stands before (`lines.len`: after the
    /// last). It rides with the text as the lines' values do (`splice`).
    at: u32,
    pin: u16,
    kind: Kind,
    /// Its line, from 1: a line taken away, in its pin's parent; a
    /// description, its pin's first line written, in the pin's revision.
    line: u32,
    /// Its text, `Changes.ghost_text[text..][0..len]`, no `\n`.
    text: u32,
    len: u32,
    /// A changed line's: the words that went (`Changes.marks`).
    marks: u32 = 0,
    nmarks: u16 = 0,
    /// A description's: where its author starts in its text.
    author: u32 = 0,

    /// A line taken away whole; a line's old text, the line that took its
    /// place right below it; a pin's description; a line a pin ahead of the
    /// shown revision will write, after the lines it will take away.
    pub const Kind = enum(u8) { deleted, changed, description, added };
};

/// The `Changes` word (builtins.zig registers it): in a file's pane (or a
/// revision's), the changes `revset` names pinned on the pane and shown,
/// in every view of it (its lines are its buffer's); another revset
/// replaces them. Bare: shown or not, the pane's pinned ones (none yet:
/// `@`, the change against its parent). What jj refuses is said in its
/// words.
pub fn changesWord(c: pardes.builtins.Ctx) void {
    pinWord(c, .changes);
}

/// The `Compare` word (builtins.zig registers it): in a file's pane (or a
/// revision's), between each two of its points (revisions, a blank
/// between, each one commit: a commit or change id, a bookmark, `@`), in
/// their order, the whole difference of the file, however many changes lie
/// between the two, pinned as `Changes` pins a change (`pairsAnswer`): a
/// lane, the lines it wrote and took away, its row `from..to  N changes
/// dates`. Bare: as bare `Changes`. One set a pane: the last of the two
/// words asked replaces the other's.
pub fn compareWord(c: pardes.builtins.Ctx) void {
    pinWord(c, .compare);
}

/// `Changes`' and `Compare`'s one road (`kind`): a revset, or two points
/// or more, asked of jj for the pane; bare, the pane's set hidden or shown
/// (in every view of it: its lines are its buffer's).
fn pinWord(c: pardes.builtins.Ctx, kind: Ask.Kind) void {
    const p = c.p;
    const pane = c.pane;
    var said: pardes.Kind.Buf(128) = .{};
    const f = if (pane.file) |*file| file else return p.reportFailure(c.id, said.print("{s}: only a file's pane takes it", .{kind.word()}));
    const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    if (arg.len == 0 and pane.layers.lanes > 0) {
        hideLayer(p, f);
        setLanes(p, f, false);
        return;
    }
    if (arg.len == 0 and answered(p, pane.serial) != null) {
        setLanes(p, f, true);
        showLayer(p, f, pane.serial);
        return;
    }
    const revset = if (arg.len == 0) "@" else arg;
    if (kind == .compare) {
        var points = std.mem.tokenizeAny(u8, arg, " \t");
        _ = points.next();
        if (points.next() == null) return p.reportFailure(c.id, said.print("{s}: two points or more, each one revision", .{kind.word()}));
    }
    if (revset.len > Changes.revset_max) return p.reportFailure(c.id, said.print("{s}: a revset that long", .{kind.word()}));
    const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r|
        .{ .path = r.path, .rev = r.rev }
    else if (f.output == null and pardes.filesystem.localPath(f.path) != null)
        .{ .path = f.path, .rev = "@" }
    else
        return p.reportFailure(c.id, said.print("{s}: only a file's pane takes it", .{kind.word()}));
    setLanes(p, f, true);
    ask(p, kind, c.id, pane.serial, shown.path, shown.rev, revset);
}

/// The layer shown in every view of every pane on `f`'s buffer, or in
/// none: its lines are the buffer's (File.layer.lines). A view's lanes take
/// cells by its frontend (File.Layers.lanes).
fn setLanes(p: *Pardes, f: *const File.State, on: bool) void {
    for (p.panes) |slot| {
        const pane = slot orelse continue;
        const tf = if (pane.file) |*file| file else continue;
        if (tf.content.ptr != f.content.ptr) continue;
        for (0..pardes.views.max) |k| {
            const v = p.views[k] orelse continue;
            const cells: u8 = if (!on) 0 else if (v.frontend.windowed) 2 else levels;
            if (k == p.live) pane.layers.lanes = cells else pane.pv[k].layers.lanes = cells;
        }
    }
}

/// The `Churn` word (builtins.zig registers it): in a file's pane (or a
/// revision's), how many changes in `window` touched each declaration,
/// shown in this view as a heat lane after the line number and a strip by
/// the scroll thumb. The window: a revset, or a span of time back from now
/// (`3d`, `2w`, `6m`, `1y`: what the file's history has in it); bare, shown
/// here or not, and with none counted yet the file's whole history (`::`
/// the revision shown).
pub fn churnWord(c: pardes.builtins.Ctx) void {
    const p = c.p;
    const pane = c.pane;
    const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Churn: only a file's pane takes it");
    const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    if (arg.len == 0 and pane.layers.heat > 0) {
        pane.layers.heat = 0;
        return;
    }
    if (arg.len == 0 and churned(p, pane.serial) != null) {
        pane.layers.heat = 1;
        return;
    }
    const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r|
        .{ .path = r.path, .rev = r.rev }
    else if (f.output == null and pardes.filesystem.localPath(f.path) != null)
        .{ .path = f.path, .rev = "@" }
    else
        return p.reportFailure(c.id, "Churn: only a file's pane takes it");
    var buf: [Changes.revset_max]u8 = undefined;
    const window = spanOf(&buf, shown.rev, arg) orelse arg;
    if (window.len > Changes.revset_max) return p.reportFailure(c.id, "Churn: a window that long");
    pane.layers.heat = 1;
    ask(p, .churn, c.id, pane.serial, shown.path, shown.rev, window);
}

/// `arg` as a revset: bare, every change of the revision's history; a span
/// of time (a count and `h`, `d`, `w`, `m` or `y`), its changes since then
/// (jj's `author_date`); null for a revset.
fn spanOf(buf: []u8, rev: []const u8, arg: []const u8) ?[]const u8 {
    if (arg.len == 0) return std.fmt.bufPrint(buf, "::({s})", .{rev}) catch null;
    const n = std.fmt.parseInt(u16, arg[0 .. arg.len - 1], 10) catch return null;
    const unit: []const u8 = switch (arg[arg.len - 1]) {
        'h' => "hours",
        'd' => "days",
        'w' => "weeks",
        'm' => "months",
        'y' => "years",
        else => return null,
    };
    return std.fmt.bufPrint(buf, "::({s}) & author_date(after:\"{d} {s} ago\")", .{ rev, n, unit }) catch null;
}

// ---- jj off the loop (Stream.zig's model) ----

/// A `Changes` asked of jj: the pane (by serial), the file it shows and the
/// revision whose lines are annotated, the revset. Its two runs go on a
/// worker where the host has one (the `search` effect: Stream.start), their
/// raw answers back as one input (`Event.search`) stamped
/// with its generation, which the step takes (`receive`): a replica replays
/// that input and never runs jj. With no worker (a test), on the loop, each
/// run a site of the step's tape.
pub const Ask = struct {
    gpa: std.mem.Allocator,
    kind: Kind = .changes,
    /// What its answer is made with: the shell's, which frees a batch.
    out: std.mem.Allocator,
    gen: u32,
    serial: u32,
    path: []u8,
    rev: []u8,
    revset: []u8,

    /// `Changes`' (with who wrote each line), `Churn`'s (with jj's text
    /// of the revision, which the counts are lined up with), or `Compare`'s
    /// (its pairs as `Changes`' changes, with jj's text of the revision:
    /// `pairsAnswer`).
    pub const Kind = enum(u8) {
        changes,
        churn,
        compare,

        /// The word that asks it, as its notices name it.
        pub fn word(k: Kind) []const u8 {
            return switch (k) {
                .changes => "Changes",
                .churn => "Churn",
                .compare => "Compare",
            };
        }
    };

    fn make(gpa: std.mem.Allocator, kind: Kind, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask {
        const a = try gpa.create(Ask);
        errdefer gpa.destroy(a);
        const owned = try std.mem.concat(gpa, u8, &.{ path, rev, revset });
        a.* = .{ .gpa = gpa, .kind = kind, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] };
        return a;
    }

    pub fn deinit(a: *Ask) void {
        a.gpa.free(a.path.ptr[0 .. a.path.len + a.rev.len + a.revset.len]);
        a.gpa.destroy(a);
    }
};

/// The session's `Changes` (`Pardes.changes`): jj's answers, a pane's by
/// its serial; the `Changes` jj runs for, one at a time, the one asked
/// while it runs (only the last asked is pinned), and how many were asked
/// (the generation). In every digest of the session: nothing until a
/// `Changes` is asked, then one update while nothing is asked of jj.
pub const Session = struct {
    answers: std.ArrayList(Changes) = .empty,
    heats: std.ArrayList(Heat) = .empty,
    task: ?Task = null,
    next: ?*Ask = null,
    count: u32 = 0,

    pub fn digest(c: *const Session, h: *pardes.walk.Hasher) void {
        if (c.count == 0) return;
        const bits: u64 = c.count | @as(u64, @intFromBool(c.task != null)) << 32 | @as(u64, @intFromBool(c.next != null)) << 33;
        h.update(std.mem.asBytes(&bits));
        pardes.walk.hash(std.ArrayList(Changes), &c.answers, h);
        pardes.walk.hash(std.ArrayList(Heat), &c.heats, h);
        if (c.task) |*t| pardes.walk.hash(Task, t, h);
        if (c.next) |n| pardes.walk.hash(Ask, n, h);
    }

    /// The session's end: the worker canceled, the asks and the answers
    /// let go.
    pub fn deinit(c: *Session, gpa: std.mem.Allocator) void {
        if (c.task) |t| {
            c.task = null;
            if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel);
            t.ask.deinit();
        }
        if (c.next) |a| {
            c.next = null;
            a.deinit();
        }
        for (c.answers.items) |*a| a.deinit(gpa);
        c.answers.deinit(gpa);
        for (c.heats.items) |*h| h.deinit(gpa);
        c.heats.deinit(gpa);
    }
};

/// The `Changes` jj runs for, and its worker.
pub const Task = struct {
    // The worker the host started for it, live: a replica has none.
    pub const replica = .{ .authority = .{ "future", "io" } };
    ask: *Ask,
    future: ?std.Io.Future(void) = null,
    io: ?std.Io = null,
};

/// A `Changes` generation has this bit (a search's and a parse's count
/// from 0; a paint's has the top one).
pub const gen_bit: u32 = 1 << 29;

fn liveGen(c: *const Session) u32 {
    return gen_bit | (c.count & (gen_bit - 1));
}

/// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs):
/// what the pane shows stays until the answer lands.
fn ask(p: *Pardes, kind: Ask.Kind, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void {
    p.changes.count +%= 1;
    const a = Ask.make(p.gpa, kind, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory");
    var said: pardes.Kind.Buf(32) = .{};
    p.setStatus(.at(id), said.print("{s}: jj\u{2026}", .{kind.word()}));
    if (p.changes.task != null) {
        if (p.changes.next) |old| old.deinit();
        p.changes.next = a;
        return;
    }
    go(p, a);
}

fn go(p: *Pardes, a: *Ask) void {
    p.changes.task = .{ .ask = a };
    if (p.tape.has(p, .search)) return p.emit(.{ .search = .{ .gen = a.gen } });
    runHere(p, a.gen, false);
}

/// The host's `search` effect for a `Changes` generation (Stream.start):
/// its runs on a worker that sends to `sink`.
pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void {
    const t = if (p.changes.task) |*t| t else return;
    if (t.ask.gen != gen or t.future != null) return;
    t.ask.out = gpa;
    // No worker to be had: here, its answer an input.
    t.future = io.concurrent(work, .{ t.ask, ctx, sink }) catch return runHere(p, gen, true);
    t.io = io;
}

fn work(a: *Ask, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void {
    const b = answer(null, a.out, a);
    if (!sink(ctx, b)) b.deinit(a.out);
}

/// With no worker: the runs here, each a site (a replica replays them).
/// `in_call`: in the host's `search` entry, the answer handed in as an
/// input, as a worker's is.
pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void {
    const t = p.changes.task orelse return;
    if (t.ask.gen != gen or t.future != null) return;
    const b = answer(p, p.gpa, t.ask);
    defer b.deinit(p.gpa);
    if (in_call) p.update(.{ .search = b }) else receive(p, &b);
}

/// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given
/// (on the loop), else run here (a worker).
fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch {
    if (a.kind == .compare) return pairsAnswer(p, gpa, a);
    const failed = struct {
        fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch {
            _ = g;
            return .{ .gen = at.gen, .rows = why, .end = .failed };
        }
    }.f;
    const set = fileset(gpa, a.path) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
    defer gpa.free(set);
    // The changes, oldest first, each with its diff of the file: one run.
    // The revset's, each marked behind the shown revision (its ancestors,
    // it too), ahead of it (its descendants) or neither (a sibling: its
    // lines are no revision's on its line, drawn nowhere and named in
    // words, `pinAnswer`). With them the changes the revset does not pin
    // between the first and the shown revision, and between it and those
    // ahead (marked so), whose hunks move the places of the pins' lines.
    const query = std.fmt.allocPrint(gpa, "(({0s}) | (roots({0s})::({1s})) | (({1s})::({0s}))) & files({2s})", .{ a.revset, a.rev, set }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
    defer gpa.free(query);
    const template = logTemplate(gpa, a.revset, a.rev) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
    defer gpa.free(template);
    const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", template, "--git", "--context=0", "--", set };
    const logged = switch (runJj(p, gpa, dirOf(a.path), &log_args)) {
        .refused => |why| return failed(gpa, a, why),
        // The wall clock first, read where jj runs (an input, as jj's
        // answer is): the descriptions' ages are of it.
        .bytes => |bytes| stamped: {
            defer gpa.free(bytes);
            const now = if (p) |q| q.tape.value(.clock, wallSeconds, .{}) else wallSeconds();
            break :stamped std.fmt.allocPrint(gpa, "{d}\n{s}", .{ now, bytes }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
        },
    };
    var it = std.mem.splitScalar(u8, logged, '\n');
    const any = while (it.next()) |l| {
        if (if (entryOf(l)) |e| e.pinned else false) break true;
    } else false;
    if (!any) return .{ .gen = a.gen, .rows = logged, .end = .done };
    // Churn: jj's text of the revision, to line the counts up with the pane's.
    if (a.kind == .churn) return switch (runJj(p, gpa, dirOf(a.path), &.{ "file", "show", "-r", a.rev, "--", set })) {
        .refused => |why| {
            gpa.free(logged);
            return failed(gpa, a, why);
        },
        .bytes => |shown| .{ .gen = a.gen, .rows = logged, .styles = shown, .end = .done },
    };
    // Who wrote each line: a path, not a fileset (annotate takes one file
    // as it is named).
    const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) };
    return switch (runJj(p, gpa, dirOf(a.path), &annotate_args)) {
        .refused => |why| {
            gpa.free(logged);
            return failed(gpa, a, why);
        },
        .bytes => |annotated| .{ .gen = a.gen, .rows = logged, .styles = annotated, .end = .done },
    };
}

/// The wall clock, in seconds since the epoch (a `.clock` read as `u32`:
/// a replica's guess and a stamp answer it so too).
fn wallSeconds() u32 {
    var ts: std.c.timespec = undefined;
    if (std.c.clock_gettime(.REALTIME, &ts) != 0) return 0;
    return std.math.cast(u32, ts.sec) orelse 0;
}

fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown {
    return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args);
}

/// A `Compare`'s runs (`answer`), its answer in the shape a `Changes` gets,
/// which `parse` reads: the wall clock; for each two points in their order
/// an entry as `logTemplate` writes one, its id the first point's change,
/// its title the pair's row (`pairRow`), then the file's difference
/// between the two (`jj diff --from --to --git --context=0`: a pin whose
/// hunks are two trees' difference; an entry not pinned when there is
/// none); then from the last point to the revision shown an entry not
/// pinned, whose hunks carry the pairs' places there; and, for who wrote
/// each line (`pairOwners`: jj has no annotation of a pair), jj's text of
/// the revision shown. A pair whose first point's text is the revision
/// shown's, and every pair after it, is AHEAD of it (`a`, as a change ahead
/// is: the lines it will write are the read-only ones), and no step
/// carries their places: none is needed. What lies
/// between two points is named by ancestry (one `jj log` a pair: its row's
/// counts and dates); what is drawn is the two trees.
fn pairsAnswer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch {
    var scratch: std.heap.ArenaAllocator = .init(gpa);
    defer scratch.deinit();
    var rows: std.ArrayList(u8) = .empty;
    const got = pairRuns(p, gpa, scratch.allocator(), a, &rows) catch refusal(gpa, "out of memory");
    switch (got) {
        .refused => |why| {
            rows.deinit(gpa);
            return .{ .gen = a.gen, .rows = why, .end = .failed };
        },
        .bytes => |shown| {
            const logged = rows.toOwnedSlice(gpa) catch {
                rows.deinit(gpa);
                gpa.free(shown);
                return .{ .gen = a.gen, .rows = refusal(gpa, "out of memory").refused, .end = .failed };
            };
            return .{ .gen = a.gen, .rows = logged, .styles = shown, .end = .done };
        },
    }
}

/// `pairsAnswer`'s runs, its entries and diffs onto `rows`: jj's text of
/// the revision shown, or what jj refused, in its words.
fn pairRuns(p: ?*Pardes, gpa: std.mem.Allocator, arena: std.mem.Allocator, a: *const Ask, rows: *std.ArrayList(u8)) error{OutOfMemory}!Shown {
    const dir = dirOf(a.path);
    const set = try fileset(arena, a.path);
    const now = if (p) |q| q.tape.value(.clock, wallSeconds, .{}) else wallSeconds();
    try rows.print(gpa, "{d}\n", .{now});
    var points: std.ArrayList([]const u8) = .empty;
    var words = std.mem.tokenizeAny(u8, a.revset, " \t");
    while (words.next()) |point| try points.append(arena, point);
    if (points.items.len < 2) return refusal(gpa, "two points or more");
    // Where the revision shown stands: at the first point whose text is
    // its (no difference between the two), the pairs from there on ahead
    // of it; at the last, or at none (after the last), every pair behind.
    const to_shown = switch (runJj(p, gpa, dir, &.{ "diff", "--from", points.items[points.items.len - 1], "--to", a.rev, "--git", "--context=0", "--", set })) {
        .refused => |why| return .{ .refused = why },
        .bytes => |b| b,
    };
    defer gpa.free(to_shown);
    var shown_at = points.items.len;
    if (to_shown.len == 0) shown_at = points.items.len - 1 else for (points.items[0 .. points.items.len - 1], 0..) |point, k| {
        const differs = switch (runJj(p, gpa, dir, &.{ "diff", "--from", point, "--to", a.rev, "--git", "--context=0", "--", set })) {
            .refused => |why| return .{ .refused = why },
            .bytes => |b| b,
        };
        defer gpa.free(differs);
        if (differs.len == 0) {
            shown_at = k;
            break;
        }
    }
    var last: [8]u8 = @splat('z');
    for (points.items[0 .. points.items.len - 1], points.items[1..], 0..) |from, to, k| {
        const diffed = switch (runJj(p, gpa, dir, &.{ "diff", "--from", from, "--to", to, "--git", "--context=0", "--", set })) {
            .refused => |why| return .{ .refused = why },
            .bytes => |b| b,
        };
        defer gpa.free(diffed);
        const between = try std.fmt.allocPrint(arena, "(({s})..({s}) | ({s})..({s})) & files({s})", .{ from, to, to, from, set });
        const revset = try std.fmt.allocPrint(arena, "({s}) | ({s}) | {s}", .{ from, to, between });
        const template = try std.fmt.allocPrint(arena, "change_id.short(8) ++ \"\\t\" ++ if(self.contained_in(\"({s})\"), \"f\") ++ if(self.contained_in(\"({s})\"), \"t\") ++ if(self.contained_in(\"{s}\"), if(self.contained_in(\"::({s})\"), \"+\", \"-\")) ++ \"\\t\" ++ author.timestamp().utc().format(\"%Y-%m-%d\") ++ \"\\n\"", .{ try quoted(arena, from), try quoted(arena, to), try quoted(arena, between), try quoted(arena, to) });
        const logged = switch (runJj(p, gpa, dir, &.{ "log", "--no-graph", "-r", revset, "-T", template })) {
            .refused => |why| return .{ .refused = why },
            .bytes => |b| b,
        };
        defer gpa.free(logged);
        const row = pairRow(logged);
        // `logTemplate`'s marks: pinned or not (no difference), behind or ahead.
        const mark: u8 = if (k >= shown_at) (if (diffed.len > 0) 'a' else 'd') else if (diffed.len > 0) 'p' else 'c';
        try rows.print(gpa, "{s}\t{c}\t0\t\t", .{ &row.from, mark });
        try row.say(gpa, rows);
        try rows.append(gpa, '\n');
        try rows.appendSlice(gpa, diffed);
        if (diffed.len > 0 and diffed[diffed.len - 1] != '\n') try rows.append(gpa, '\n');
        last = row.to;
    }
    if (shown_at == points.items.len) {
        try rows.print(gpa, "{s}\tc\t0\t\t\n", .{&last});
        try rows.appendSlice(gpa, to_shown);
    }
    return runJj(p, gpa, dir, &.{ "file", "show", "-r", a.rev, "--", set });
}

/// `text` as it goes inside a template's string literal.
fn quoted(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]u8 {
    var out: std.ArrayList(u8) = .empty;
    for (text) |c| {
        if (c == '"' or c == '\\') try out.append(arena, '\\');
        try out.append(arena, c);
    }
    return out.toOwnedSlice(arena);
}

/// A pair of points as its row says it (`pairsAnswer`'s `jj log`, a line a
/// change: its id, `f` the first point, `t` the second, `+` a change
/// between in the second and not the first, `-` one the other way (what
/// the difference takes back), its author's day).
const PairRow = struct {
    from: [8]u8 = @splat('z'),
    to: [8]u8 = @splat('z'),
    brought: u32 = 0,
    undone: u32 = 0,
    first: [10]u8 = @splat(' '),
    last: [10]u8 = @splat(' '),

    /// `from..to  N changes, M undone  first..last` (the parts there are).
    fn say(r: *const PairRow, gpa: std.mem.Allocator, out: *std.ArrayList(u8)) error{OutOfMemory}!void {
        try out.print(gpa, "{s}..{s}", .{ &r.from, &r.to });
        if (r.brought + r.undone == 0) return;
        try out.print(gpa, "  {d} change{s}", .{ r.brought, if (r.brought == 1) "" else "s" });
        if (r.undone > 0) try out.print(gpa, ", {d} undone", .{r.undone});
        try out.print(gpa, "  {s}", .{&r.first});
        if (!std.mem.eql(u8, &r.first, &r.last)) try out.print(gpa, "..{s}", .{&r.last});
    }
};

fn pairRow(logged: []const u8) PairRow {
    var r: PairRow = .{};
    var lines = std.mem.splitScalar(u8, logged, '\n');
    while (lines.next()) |l| {
        var cols = std.mem.splitScalar(u8, l, '\t');
        const id = cols.next() orelse continue;
        const marks = cols.next() orelse continue;
        const day = cols.next() orelse continue;
        if (id.len != 8) continue;
        if (std.mem.indexOfScalar(u8, marks, 'f') != null) r.from = id[0..8].*;
        if (std.mem.indexOfScalar(u8, marks, 't') != null) r.to = id[0..8].*;
        const side = std.mem.indexOfAny(u8, marks, "+-") orelse continue;
        if (marks[side] == '+') r.brought += 1 else r.undone += 1;
        if (day.len != 10) continue;
        if (r.first[0] == ' ' or std.mem.order(u8, day, &r.first) == .lt) r.first = day[0..10].*;
        if (r.last[0] == ' ' or std.mem.order(u8, day, &r.last) == .gt) r.last = day[0..10].*;
    }
    return r;
}

/// A `Changes` answer (`Event.search` with a `Changes` generation),
/// borrowed: the last asked of its kind is parsed and pinned (or counted,
/// a `Churn`'s) on its pane (the ask names it); an earlier one's, or a gone
/// pane's, dropped. Then the one asked meanwhile goes.
pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void {
    var revset: [Changes.revset_max]u8 = undefined;
    var revset_len: usize = 0;
    var serial: u32 = 0;
    var kind: Ask.Kind = .changes;
    if (p.changes.task) |t| if (t.ask.gen == b.gen) {
        p.changes.task = null;
        if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait);
        serial = t.ask.serial;
        kind = t.ask.kind;
        revset_len = t.ask.revset.len;
        @memcpy(revset[0..revset_len], t.ask.revset);
        t.ask.deinit();
    };
    defer if (p.changes.task == null) if (p.changes.next) |next| {
        p.changes.next = null;
        go(p, next);
    };
    if (revset_len == 0) return;
    // A later one of its kind asked meanwhile: only that one is shown.
    if (p.changes.next) |n| if (n.kind == kind) return;
    const id = p.paneBySerial(serial) orelse return;
    switch (kind) {
        .changes, .compare => pinAnswer(p, id, b, revset[0..revset_len], kind),
        .churn => heatAnswer(p, id, b, revset[0..revset_len]),
    }
}

/// A splice of `f`'s text, before its bytes go in (File.edit, the one
/// place a text changes, an undo's too): each pane showing it that has
/// pins keeps a value for each of its lines, so the values ride with the
/// lines, never asking jj again: the lines a splice takes out take their
/// values with them, and a line it puts in is nobody's.
pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void {
    // The values are the file's lines': the layer's lines before the edit
    // are none of them.
    var shown_before: usize = 0;
    for (f.layer.lines) |r| {
        if (r.at >= off) break;
        shown_before += 1;
    }
    var i = p.changes.answers.items.len;
    while (i > 0) {
        i -= 1;
        const c = &p.changes.answers.items[i];
        const id = p.paneBySerial(c.serial) orelse continue;
        const shown = if (p.panes[id].?.file) |*shown| shown else continue;
        if (shown.content.ptr != f.content.ptr) continue;
        // The layer shown: its ghosts stand where its lines are (`placed`).
        const placed_by_lines = c.serial == f.layer.owner;
        splice(p.gpa, c, f.content, off, len, bytes, shown_before, placed_by_lines) catch {
            // No room for it: its values would lie, so it goes; the one
            // shown stays (its lines are the buffer's, its places theirs).
            if (placed_by_lines) continue;
            c.deinit(p.gpa);
            _ = p.changes.answers.swapRemove(i);
        };
    }
    i = p.changes.heats.items.len;
    while (i > 0) {
        i -= 1;
        const h = &p.changes.heats.items[i];
        const id = p.paneBySerial(h.serial) orelse continue;
        const shown = if (p.panes[id].?.file) |*shown| shown else continue;
        if (shown.content.ptr != f.content.ptr) continue;
        _ = spliceValues(u16, p.gpa, &h.lines, 0, f.content, off, len, bytes, shown_before) catch {
            h.deinit(p.gpa);
            _ = p.changes.heats.swapRemove(i);
        };
    }
}

/// `c`'s values spliced as `text`'s lines are by the splice of `len` bytes
/// at `off` for `bytes`. A splice that starts in a line's leading blanks
/// (at its start, or after its indent, as `o` puts a line in) leaves that
/// line's text after what it puts in: the lines it takes and puts come
/// before it. Else the line it starts in keeps its value, and the lines
/// taken and put come after it.
fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8, shown_before: usize, placed_by_lines: bool) error{OutOfMemory}!void {
    const cut = try spliceValues(Line, gpa, &c.lines, .{ .pin = .none }, text, off, len, bytes, shown_before) orelse return;
    const from = cut.from;
    const take = cut.take;
    const put = cut.put;
    if (placed_by_lines) return;
    // A ghost row stands before the line it stood before; one before a
    // line taken out, before the line after what took its place.
    for (c.ghosts) |*g| {
        if (g.at <= from) continue;
        g.at = @intCast(if (g.at < from + take) from + put else g.at - take + put);
    }
}

/// A value a line, `values`, spliced as `splice` says, a line put in
/// `none`; null when no line is taken or put. `text` is the buffer, whose
/// `shown_before` lines before the edit are the layer's (none of the
/// file's: File.layer.lines).
fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, text: []const u8, off: usize, len: usize, bytes: []const u8, shown_before: usize) error{OutOfMemory}!?struct { from: usize, take: usize, put: usize } {
    const taken = std.mem.count(u8, text[off..][0..len], "\n");
    const put = std.mem.count(u8, bytes, "\n");
    if (taken == 0 and put == 0) return null;
    const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0;
    const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0;
    const from = std.mem.count(u8, text[0..line_start], "\n") - shown_before + @intFromBool(!in_lead);
    if (from > values.len) return null;
    const take = @min(taken, values.len - from);
    const next = try gpa.alloc(T, values.len - take + put);
    @memcpy(next[0..from], values.*[0..from]);
    @memset(next[from..][0..put], none);
    @memcpy(next[from + put ..], values.*[from + take ..]);
    gpa.free(values.*);
    values.* = next;
    return .{ .from = from, .take = take, .put = put };
}

/// jj's answer `b` for `revset` (a `Compare`'s points: `kind`) parsed and
/// pinned on pane `id`, or its refusal said there.
fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8, kind: Ask.Kind) void {
    const pane = p.panes[id].?;
    var line: pardes.Kind.Buf(512) = .{};
    const f = if (pane.file) |*file| file else return;
    // Nothing pinned yet: no gutter for it.
    defer if (answered(p, pane.serial) == null) setLanes(p, f, false);
    const name = kind.word();
    if (b.end == .failed) return p.reportFailure(id, line.print("{s}: {s}", .{ name, b.rows[0..@min(b.rows.len, 480)] }));
    // jj's lines lined up with the file's (the layer's are none of it).
    const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("{s}: {s}", .{ name, @errorName(err) }));
    var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, text, kind == .compare) catch |err| return p.reportFailure(id, line.print("{s}: {s}", .{ name, @errorName(err) }));
    switch (got) {
        .refused => |why| {
            defer p.gpa.free(why);
            return p.reportFailure(id, line.print("{s}: {s}", .{ name, why[0..@min(why.len, 480)] }));
        },
        .read => |*changes| {
            // The revset's changes neither behind nor ahead: said, not drawn.
            var aside_said: pardes.Kind.Buf(512) = .{};
            const aside = asideSaid(b.rows, if (of(f)) |r| r.rev else "@", &aside_said);
            if (changes.pins.len == 0) {
                changes.deinit(p.gpa);
                const shown = std.Io.Dir.path.basename(if (of(f)) |r| r.path else f.path);
                if (aside.len > 0) return p.reportFailure(id, aside);
                if (kind == .compare) return p.reportFailure(id, line.print("{s}: no difference in {s} between `{s}`", .{ name, shown, revset }));
                return p.reportFailure(id, line.print("{s}: no change of `{s}` touches {s}", .{ name, revset, shown }));
            }
            @memcpy(changes.revset[0..revset.len], revset);
            changes.revset_len = @intCast(revset.len);
            changes.serial = pane.serial;
            // The lines shown go before the answer they are of.
            hideLayer(p, f);
            if (answered(p, pane.serial)) |kept| {
                kept.deinit(p.gpa);
                kept.* = changes.*;
            } else p.changes.answers.append(p.gpa, changes.*) catch {
                changes.deinit(p.gpa);
                return p.reportFailure(id, line.print("{s}: out of memory", .{name}));
            };
            p.setStatus(.at(id), aside);
            if (pane.layers.lanes > 0) showLayer(p, f, pane.serial);
        },
    }
}

/// The changes jj's log `logged` marks neither behind nor ahead of the
/// shown revision `rev` (`logTemplate`'s `s`: a sibling), in words:
/// `Changes: <id> is not on <rev>'s line`; "" for none.
fn asideSaid(logged: []const u8, rev: []const u8, said: *pardes.Kind.Buf(512)) []const u8 {
    var ids: [256]u8 = undefined;
    var w: std.Io.Writer = .fixed(&ids);
    var n: usize = 0;
    var it = std.mem.splitScalar(u8, logged, '\n');
    while (it.next()) |l| if (entryOf(l)) |e| if (e.aside) {
        w.print("{s}{s}", .{ if (n == 0) "" else ", ", &e.pin.id }) catch break;
        n += 1;
    };
    if (n == 0) return "";
    return said.print("Changes: {s} {s} not on {s}'s line", .{ w.buffered(), if (n == 1) "is" else "are", rev });
}

/// jj's answer `b` for a `Churn` of `window` on pane `id`, kept raw
/// until the text's declarations are there (a worker's parse,
/// Stream.parseFor: a big file's parse is seconds in a Debug build, never
/// the loop's), then counted (`count`); or its refusal said there.
fn heatAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, window: []const u8) void {
    const pane = p.panes[id].?;
    var line: pardes.Kind.Buf(512) = .{};
    if (pane.file == null) return;
    if (b.end == .failed) {
        if (churned(p, pane.serial) == null) pane.layers.heat = 0;
        return p.reportFailure(id, line.print("Churn: {s}", .{b.rows[0..@min(b.rows.len, 480)]}));
    }
    var heat: Heat = .{ .serial = pane.serial, .revset_len = @intCast(window.len) };
    @memcpy(heat.revset[0..window.len], window);
    heat.pending = std.mem.concat(p.gpa, u8, &.{ b.rows, b.styles }) catch return p.reportFailure(id, "Churn: out of memory");
    heat.pending_was = @intCast(b.rows.len);
    if (churned(p, pane.serial)) |kept| {
        kept.deinit(p.gpa);
        kept.* = heat;
    } else p.changes.heats.append(p.gpa, heat) catch {
        heat.deinit(p.gpa);
        pane.layers.heat = 0;
        return p.reportFailure(id, "Churn: out of memory");
    };
    parsed(p, pane.serial);
}

/// A parse of pane `serial`'s text landed (Stream.receiveParse), or jj's
/// answer did: a `Churn` waiting on it counted when the declarations are of
/// the text as it is, else a parse of it asked.
pub fn parsed(p: *Pardes, serial: u32) void {
    const h = churned(p, serial) orelse return;
    if (h.pending.len == 0) return;
    const id = p.paneBySerial(serial) orelse return;
    const pane = p.panes[id].?;
    const f = if (pane.file) |*file| file else return;
    var line: pardes.Kind.Buf(512) = .{};
    if (!syntax.supportsPath(f.path)) {
        // No grammar for it (a revision's pane too: its name ends `@rev`).
        p.reportFailure(id, line.print("Churn: no declarations to count in {s}", .{std.Io.Dir.path.basename(f.path)}));
        pane.layers.heat = 0;
        return forgetHeat(p, serial);
    }
    if (f.context.revision != f.revision) return pardes.Stream.parseFor(p, id);
    const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)}));
    const lines = heatOf(p.gpa, p.scratch.allocator(), h.pending[0..h.pending_was], h.pending[h.pending_was..], text, f.context.declarations, &h.hottest) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)}));
    p.gpa.free(h.pending);
    h.pending = &.{};
    h.lines = lines;
    if (h.hottest > 0) return p.setStatus(.at(id), "");
    p.reportFailure(id, line.print("Churn: no change of `{s}` touches a declaration of {s}", .{ h.window(), std.Io.Dir.path.basename(File.langPath(f)) }));
    pane.layers.heat = 0;
    forgetHeat(p, serial);
}

/// For each line of `text` (`decls` its declarations), how many of the window's
/// changes in `logged` (jj's log, `p` the window's, `c` a later change
/// that only carries places) touched the declaration it is in: tree-
/// sitter's innermost, a line in none 0. A change's hunk touches the lines
/// it wrote, carried into the revision jj showed (`was`) through the later
/// changes' hunks, then into `text` (`Moved`); a hunk that only took lines
/// away, the line above where they stood. Each change counts once a
/// declaration. `hottest`: the largest count.
fn heatOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, was: []const u8, text: []const u8, decls: []const syntax.ContextDeclaration, hottest: *u16) error{OutOfMemory}![]u16 {
    var hunks: std.ArrayList(Hunk) = .empty;
    var removed: std.ArrayList(u8) = .empty;
    var windowed: std.ArrayList(bool) = .empty;
    var starts: std.ArrayList(usize) = .empty;
    var it = std.mem.splitScalar(u8, logged, '\n');
    var ahead: std.ArrayList(bool) = .empty;
    while (it.next()) |l| if (entryOf(l)) |e| {
        if (windowed.items.len == Hunk.carrier) break;
        try windowed.append(arena, e.pinned);
        // A sibling of the shown revision, as one ahead: none of its lines.
        try ahead.append(arena, e.ahead or e.aside);
        try starts.append(arena, it.index orelse logged.len);
    };
    try starts.append(arena, logged.len);
    for (starts.items[0 .. starts.items.len - 1], starts.items[1..], 0..) |from, to, i|
        try hunksOf(arena, arena, Hunk.carrier, @intCast(i), ahead.items[i], logged[from..to], text, &.{}, &hunks, &removed, undefined, undefined);
    const n = lineCount(text);
    const moved: Moved = .of(was, text);
    // Each line's innermost declaration (outermost first, so an inner one
    // writes over its container's lines).
    const none = std.math.maxInt(u32);
    const inner = try arena.alloc(u32, n);
    @memset(inner, none);
    for (decls, 0..) |d, k| {
        if (d.start_line >= n) continue;
        @memset(inner[d.start_line..@min(n, d.end_line + 1)], @intCast(k));
    }
    const counts = try arena.alloc(u16, decls.len);
    @memset(counts, 0);
    // The last change each declaration was counted for.
    const seen = try arena.alloc(u32, decls.len);
    @memset(seen, none);
    for (hunks.items) |h| {
        // A change ahead of the shown revision touched none of its lines.
        if (!windowed.items[h.step] or h.ahead or n == 0) continue;
        const a = carried(hunks.items, h.step, h.new_start -| 1 + @intFromBool(h.new_len == 0), moved) orelse continue;
        const b = carried(hunks.items, h.step, h.new_start -| 1 + h.new_len, moved) orelse continue;
        const lo = @min(if (h.new_len == 0) a -| 1 else a, n - 1);
        for (inner[lo..@max(lo + 1, @min(b, n))]) |k| {
            if (k == none or seen[k] == h.step) continue;
            seen[k] = h.step;
            counts[k] +|= 1;
        }
    }
    const out = try gpa.alloc(u16, n);
    hottest.* = 0;
    for (out, inner) |*o, k| {
        o.* = if (k == none) 0 else counts[k];
        hottest.* = @max(hottest.*, o.*);
    }
    return out;
}

/// The layer of pane `owner` (its `Changes` answer's ghosts, in order)
/// put in `f`'s buffer as its read-only lines (File.ReadOnly), each where
/// it stands: before its file line, a line of its own (PARDES.md "Changes
/// on the source view"). One already there goes first. Every view keeps
/// its place in the file (File.relayer).
pub fn showLayer(p: *Pardes, f: *File.State, owner: u32) void {
    const ch = answered(p, owner) orelse return hideLayer(p, f);
    if (f.layer.owner != 0) hideLayer(p, f);
    // Not out (no memory): nothing more.
    if (f.layer.owner != 0) return;
    // The file's text, the layer out.
    const text = f.content;
    var size = text.len;
    for (ch.ghosts) |g| size += g.len + 1;
    const new = pardes.memory.unfilled(p.gpa, size) catch return;
    const spans = p.gpa.alloc(File.ReadOnly, ch.ghosts.len) catch {
        pardes.memory.freeRaw(p.gpa, new);
        return;
    };
    const lines = lineCount(text);
    // `text` copied up to `from`; line `line` starts at `line_at`; `n`
    // bytes of `new` written.
    var from: usize = 0;
    var line: usize = 0;
    var line_at: usize = 0;
    var n: usize = 0;
    for (ch.ghosts, spans) |g, *r| {
        const at = @min(g.at, lines);
        while (line < at) : (line += 1) line_at = if (std.mem.indexOfScalarPos(u8, text, line_at, '\n')) |nl| nl + 1 else text.len;
        @memcpy(new[n..][0 .. line_at - from], text[from..line_at]);
        n += line_at - from;
        from = line_at;
        const said = ch.ghost_text[g.text..][0..g.len];
        // After a last line with no `\n`, its `\n` first.
        const lead = line_at == text.len and text.len > 0 and text[text.len - 1] != '\n';
        r.* = .{ .at = n, .len = g.len + 1, .line = @intCast(at), .lead = lead };
        if (lead) {
            new[n] = '\n';
            @memcpy(new[n + 1 ..][0..g.len], said);
        } else {
            @memcpy(new[n..][0..g.len], said);
            new[n + g.len] = '\n';
        }
        n += g.len + 1;
    }
    @memcpy(new[n..][0 .. text.len - from], text[from..]);
    std.debug.assert(n + text.len - from == size);
    if (File.relayer(p, f, new, spans, owner)) return;
    pardes.memory.freeRaw(p.gpa, new);
    p.gpa.free(spans);
}

/// The layer's lines out of `f`'s buffer, which is the file's text again;
/// every view keeps its place in the file: one in a line that leaves goes
/// to the start of the file line it stood before (File.relayer).
pub fn hideLayer(p: *Pardes, f: *File.State) void {
    if (f.layer.owner == 0) return;
    const text = File.fileText(f, p.scratch.allocator()) catch return;
    const new = pardes.memory.dupeUnfilled(p.gpa, text) catch return;
    if (!File.relayer(p, f, new, &.{}, 0)) pardes.memory.freeRaw(p.gpa, new);
}

/// A session loaded from a dump that kept a layer shown as a view's bit
/// and no lines (wire 31 and older: the ghost rows were drawn, not the
/// buffer's): each pane whose views showed it, its lines in its buffer
/// and shown in every view (File.layer.lines), its places kept in the file.
pub fn loaded(p: *Pardes) void {
    for (p.panes) |slot| {
        const pane = slot orelse continue;
        const f = if (pane.file) |*file| file else continue;
        if (f.layer.owner != 0 or answered(p, pane.serial) == null) continue;
        const shown = pane.layers.lanes > 0 or for (0..pardes.views.max) |k| {
            if (k != p.live and p.views[k] != null and pane.pv[k].layers.lanes > 0) break true;
        } else false;
        if (!shown) continue;
        setLanes(p, f, true);
        showLayer(p, f, pane.serial);
    }
}

/// After an edit of `f`'s buffer (File.edit): the shown layer's ghosts
/// stand before the file lines their lines stand before.
pub fn placed(p: *Pardes, f: *const File.State) void {
    const ch = answered(p, f.layer.owner) orelse return;
    if (ch.ghosts.len != f.layer.lines.len) return;
    for (ch.ghosts, f.layer.lines) |*g, r| g.at = r.line;
}

const Read = union(enum) { refused: []u8, read: Changes };

/// jj's answers parsed: `logged` (the pins, each with its diff of the
/// file) and `annotated` (who wrote each line of `text`, what the pane
/// shows: a line is matched to the line its change added by its text; a
/// `Compare`'s, `pairs`: jj's text of the revision shown, `pairOwners`).
fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8, pairs: bool) error{OutOfMemory}!Read {
    var out: Changes = .{ .serial = 0 };
    const now = std.fmt.parseInt(i64, logged[0 .. std.mem.indexOfScalar(u8, logged, '\n') orelse logged.len], 10) catch 0;
    var kept = false;
    defer if (!kept) out.deinit(gpa);
    var pins: std.ArrayList(Pin) = .empty;
    defer pins.deinit(gpa);
    // Each pin's whole author and title, for its description (`describe`):
    // never cut.
    var whole: std.ArrayList([2][]const u8) = .empty;
    // Each change jj answered, oldest first: its pin (or `Hunk.carrier`)
    // and where its diff starts in `logged`; then the end.
    const Step = struct { pin: u16, diff: usize, ahead: bool = false, aside: bool = false };
    var steps: std.ArrayList(Step) = .empty;
    var it = std.mem.splitScalar(u8, logged, '\n');
    while (it.next()) |l| if (entryOf(l)) |e| {
        if (e.pinned and pins.items.len == pins_max) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes touch it", .{pins_max}) };
        if (steps.items.len == Hunk.carrier) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes between them touch it", .{Hunk.carrier}) };
        if (e.pinned) try pins.append(gpa, e.pin);
        if (e.pinned) try whole.append(arena, .{ e.author, e.title });
        try steps.append(arena, .{ .pin = if (e.pinned) @intCast(pins.items.len - 1) else Hunk.carrier, .diff = it.index orelse logged.len, .ahead = e.ahead, .aside = e.aside });
    };
    try steps.append(arena, .{ .pin = Hunk.carrier, .diff = logged.len });
    out.pins = try pins.toOwnedSlice(gpa);
    if (out.pins.len == 0) {
        kept = true;
        return .{ .read = out };
    }
    var moved: Moved = undefined;
    out.lines = if (pairs) try pairOwners(gpa, arena, logged, steps.items, annotated, text, &moved) else try provenance(gpa, arena, annotated, out.pins, text, &moved);
    // Each change's hunks, and which of its lines a pin added whole.
    var hunks: std.ArrayList(Hunk) = .empty;
    defer hunks.deinit(gpa);
    var removed: std.ArrayList(u8) = .empty;
    defer removed.deinit(gpa);
    var marks: std.ArrayList([2]u32) = .empty;
    defer marks.deinit(gpa);
    var taken: std.ArrayList(Taken) = .empty;
    // A sibling's (`aside`) none: it moves no place on the shown line.
    for (steps.items[0 .. steps.items.len - 1], steps.items[1..], 0..) |s, next, i| if (!s.aside) try hunksOf(gpa, arena, s.pin, @intCast(i), s.ahead, logged[s.diff..next.diff], text, out.lines, &hunks, &removed, &marks, &taken);
    out.hunks = try hunks.toOwnedSlice(gpa);
    nest(out.lines, out.pins.len);
    going(out.lines, out.hunks, moved);
    out.ghosts = try ghostsOf(gpa, arena, out.pins, whole.items, out.lines, out.hunks, taken.items, &removed, now, moved);
    out.ghost_text = try removed.toOwnedSlice(gpa);
    out.marks = try marks.toOwnedSlice(gpa);
    kept = true;
    return .{ .read = out };
}

/// `jj log`'s line a change, before its diff: its id, its mark (`p` when
/// `revset` pins it and it is behind the shown revision `rev` or is it, `a`
/// pinned and ahead; `c` and `d` the same for one it does not pin; `s` one
/// neither behind nor ahead, a sibling), its author's time, its author, its
/// description's first line, a tab between.
fn logTemplate(gpa: std.mem.Allocator, revset: []const u8, rev: []const u8) error{OutOfMemory}![]u8 {
    var t: std.ArrayList(u8) = .empty;
    errdefer t.deinit(gpa);
    const Quoted = struct {
        fn put(g: std.mem.Allocator, out: *std.ArrayList(u8), text: []const u8) error{OutOfMemory}!void {
            for (text) |c| {
                if (c == '"' or c == '\\') try out.append(g, '\\');
                try out.append(g, c);
            }
        }
    };
    try t.appendSlice(gpa, "change_id.short(8) ++ \"\\t\" ++ if(self.contained_in(\"::(");
    try Quoted.put(gpa, &t, rev);
    try t.appendSlice(gpa, ")\"), if(self.contained_in(\"");
    try Quoted.put(gpa, &t, revset);
    try t.appendSlice(gpa, "\"), \"p\", \"c\"), if(self.contained_in(\"(");
    try Quoted.put(gpa, &t, rev);
    try t.appendSlice(gpa, ")::\"), if(self.contained_in(\"");
    try Quoted.put(gpa, &t, revset);
    try t.appendSlice(gpa, "\"), \"a\", \"d\"), \"s\")) ++ \"\\t\" ++ author.timestamp().utc().format(\"%s\") ++ \"\\t\" ++ author.name() ++ \"\\t\" ++ description.first_line() ++ \"\\n\"");
    return t.toOwnedSlice(gpa);
}

/// A `logTemplate` line, or null for a line of a diff (which starts with
/// a blank, a sign, `@`, `\\` or a word and a blank: never eight of jj's
/// id letters, k to z, and a tab).
fn entryOf(l: []const u8) ?struct { pin: Pin, pinned: bool, ahead: bool, aside: bool, author: []const u8, title: []const u8 } {
    if (l.len < 11 or l[8] != '\t' or l[10] != '\t') return null;
    for (l[0..8]) |c| if (c < 'k' or c > 'z') return null;
    var cols = std.mem.splitScalar(u8, l[11..], '\t');
    var pin: Pin = .{ .id = l[0..8].*, .time = std.fmt.parseInt(i64, cols.next() orelse "", 10) catch 0 };
    const author = cols.next() orelse "";
    pin.author_len = @intCast(@min(author.len, pin.author.len));
    @memcpy(pin.author[0..pin.author_len], author[0..pin.author_len]);
    const title = cols.rest();
    pin.title_len = @intCast(@min(title.len, pin.title.len));
    @memcpy(pin.title[0..pin.title_len], title[0..pin.title_len]);
    return .{ .pin = pin, .pinned = l[9] == 'p' or l[9] == 'a', .ahead = l[9] == 'a' or l[9] == 'd', .aside = l[9] == 's', .author = author, .title = title };
}

/// Which pin wrote each line of `text` (what the pane shows: `whole` is the
/// hunks' to say), a value a line, the caller's in `gpa`, from `annotated`
/// (`jj file annotate`'s answer: an id, a tab and the line, a line each, of
/// the revision it annotated, which is jj's last snapshot of a file and
/// not the keys typed since): the two texts lined up by what they agree on
/// at either end (`File.spanOf`, the editor's differ: a line inside both
/// ends keeps its owner, a line only the pane has is nobody's); `moved`,
/// where jj's lines stand in `text`.
pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: []const u8, pins: []const Pin, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line {
    var owners: std.ArrayList(PinIndex) = .empty;
    var was: std.ArrayList(u8) = .empty;
    var rows = std.mem.splitScalar(u8, annotated, '\n');
    while (rows.next()) |row| {
        // The empty text after the last newline is no line.
        if (row.len == 0 and rows.peek() == null) break;
        const tab = std.mem.indexOfScalar(u8, row, '\t') orelse row.len;
        try owners.append(arena, for (pins, 0..) |pin, i| {
            if (std.mem.eql(u8, &pin.id, row[0..tab])) break @enumFromInt(i);
        } else .none);
        try was.appendSlice(arena, row[@min(tab + 1, row.len)..]);
        try was.append(arena, '\n');
    }
    if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1;
    return linedUp(gpa, owners.items, was.items, text, moved);
}

/// A value a line of `text` from `owners`, a pin a line of jj's text
/// `was`: the two lined up by what they agree on at either end (`Moved`),
/// a line between nobody's; `moved`, where jj's lines stand in `text`.
fn linedUp(gpa: std.mem.Allocator, owners: []const PinIndex, was: []const u8, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line {
    const out = try gpa.alloc(Line, lineCount(text));
    @memset(out, .{ .pin = .none });
    moved.* = .of(was, text);
    for (out[0..@min(moved.head, owners.len)], owners[0..@min(moved.head, owners.len)]) |*l, pin| l.pin = pin;
    const tail = @min(moved.tail, owners.len);
    for (out[out.len - tail ..], owners[owners.len - tail ..]) |*l, pin| l.pin = pin;
    return out;
}

/// Which pair of a `Compare` wrote each line of `text` (`provenance`'s
/// answer where jj annotates no pair): jj's text of the revision shown,
/// `was`, walked back through the steps' hunks from the last (each step's
/// diff in `logged`, from its entry to the next's): a line is the newest
/// step's that wrote it (a step not pinned writes it nobody's), one no
/// step wrote nobody's; then lined up with `text` as an annotation is.
fn pairOwners(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, steps: anytype, was: []const u8, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line {
    const none = std.math.maxInt(u32);
    const owners = try arena.alloc(PinIndex, lineCount(was));
    @memset(owners, .none);
    const claimed = try arena.alloc(bool, owners.len);
    @memset(claimed, false);
    // Each line of the step's newer revision: its line of `was`, or none.
    var at = try arena.alloc(u32, owners.len);
    for (at, 0..) |*a, i| a.* = @intCast(i);
    var k = steps.len - 1;
    while (k > 0) {
        k -= 1;
        // A step ahead of the revision shown wrote none of its lines.
        if (steps[k].ahead) continue;
        var hunks: std.ArrayList(diff.HunkHeader) = .empty;
        var walk: diff.Walk = .{};
        var lines = std.mem.splitScalar(u8, logged[steps[k].diff..steps[k + 1].diff], '\n');
        while (lines.next()) |raw| if (walk.step(raw).kind == .hunk) try hunks.append(arena, diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?);
        var grew: i64 = 0;
        for (hunks.items) |h| {
            for (h.new_start -| 1..h.new_start -| 1 + h.new_count) |j| {
                if (j >= at.len or at[j] == none or claimed[at[j]]) continue;
                claimed[at[j]] = true;
                if (steps[k].pin != Hunk.carrier) owners[at[j]] = @enumFromInt(steps[k].pin);
            }
            grew += @as(i64, @intCast(h.new_count)) - @as(i64, @intCast(h.old_count));
        }
        // The older revision's lines: one a hunk took away is none.
        const older = try arena.alloc(u32, @intCast(@max(0, @as(i64, @intCast(at.len)) - grew)));
        var o: usize = 0;
        var n: usize = 0;
        for (hunks.items) |h| {
            const old_from = if (h.old_count == 0) h.old_start else h.old_start -| 1;
            const new_from = if (h.new_count == 0) h.new_start else h.new_start -| 1;
            while (o < @min(old_from, older.len)) : ({
                o += 1;
                n += 1;
            }) older[o] = if (n < at.len) at[n] else none;
            while (o < @min(old_from + h.old_count, older.len)) : (o += 1) older[o] = none;
            n = new_from + h.new_count;
        }
        while (o < older.len) : ({
            o += 1;
            n += 1;
        }) older[o] = if (n < at.len) at[n] else none;
        at = older;
    }
    return linedUp(gpa, owners, was, text, moved);
}

/// Where jj's lines (the revision it annotated) stand in the pane's text,
/// which has keys typed since (before the word, never snapshotted, or
/// while jj ran): its first `head` lines and its last `tail` are the same
/// lines, those between were rewritten.
pub const Moved = struct {
    head: u32,
    tail: u32,
    /// jj's lines, and the text's.
    was: u32,
    now: u32,

    /// `was` (jj's text) lined up with `text` by what they agree on at
    /// either end (`File.spanOf`, the editor's differ).
    pub fn of(was: []const u8, text: []const u8) Moved {
        const was_n: u32 = @intCast(lineCount(was));
        const now: u32 = @intCast(lineCount(text));
        if (std.mem.eql(u8, was, text)) return .{ .head = was_n, .tail = 0, .was = was_n, .now = was_n };
        const span = File.spanOf(was, text);
        const head = @min(std.mem.count(u8, was[0..span.head], "\n"), now, was_n);
        var tail = @min(tailLines(was, span.tail), now - head, was_n - head);
        // The line the two ends meet inside (an insertion before it shares its
        // indent with the line above) is the same line when its bytes are.
        if (head + tail < @min(now, was_n) and std.mem.eql(u8, lineFromEnd(was, tail), lineFromEnd(text, tail))) tail += 1;
        return .{ .head = @intCast(head), .tail = @intCast(tail), .was = was_n, .now = now };
    }

    /// The text's place of jj's place `at` (before its line `at`), or null
    /// inside lines rewritten since: no place there tells the truth.
    fn place(m: Moved, at: u32) ?u32 {
        if (at >= m.was - m.tail) return at - (m.was - m.tail) + (m.now - m.tail);
        return if (at <= m.head) at else null;
    }
};

/// `text`'s line `k` from its end (0: its last).
fn lineFromEnd(text: []const u8, k: usize) []const u8 {
    var end = text.len - @intFromBool(std.mem.endsWith(u8, text, "\n"));
    for (0..k) |_| end = (std.mem.lastIndexOfScalar(u8, text[0..end], '\n') orelse return "");
    const from = if (std.mem.lastIndexOfScalar(u8, text[0..end], '\n')) |nl| nl + 1 else 0;
    return text[from..end];
}

/// The lines of `text`: one after each newline but a last one, as the
/// annotation numbers them.
fn lineCount(text: []const u8) usize {
    return std.mem.count(u8, text, "\n") + @intFromBool(text.len > 0 and text[text.len - 1] != '\n');
}

/// How many of `text`'s lines lie whole in its last `tail` bytes.
fn tailLines(text: []const u8, tail: usize) usize {
    if (tail == 0) return 0;
    const from = text.len - tail;
    // A line starts at `from`, and after each newline in the tail but the
    // text's last byte.
    const starts = if (from == 0) 1 else @intFromBool(text[from - 1] == '\n');
    return starts + std.mem.count(u8, text[from .. text.len - 1], "\n");
}

/// A line a pin took away (in hunk order, a pin's after another's): one
/// line changed (`paired`, with the line it became, by its number in the
/// pin's revision and, while it is shown, its line of the text) or taken
/// away whole; the words that went, in `Changes.marks`.
const Taken = struct { paired: bool, marks: u32, nmarks: u16, new: u32 = 0, shown: ?u32 = null, partner: usize = 0 };

/// Pin `k`'s hunks in `diffed` (its diff of the file, `--git --context=0`) onto
/// `hunks`, their removed lines onto `removed`, what became of each onto
/// `taken`; and each line of `text` pin `k` wrote (`lines`), matched in
/// order by its text, marked `whole` when the change added it whole, else
/// with the words that came. Which lines a run of lines taken away and
/// written changed, and their words, is the patch view's alignment
/// (hunks.format: its `inferEdits`), read off its rows. A change the
/// revset does not pin (`k` is `Hunk.carrier`): its hunks alone.
fn hunksOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, k: u16, step: u16, ahead: bool, diffed: []const u8, text: []const u8, lines: []Line, hunks: *std.ArrayList(Hunk), removed: *std.ArrayList(u8), marks: *std.ArrayList([2]u32), taken: *std.ArrayList(Taken)) error{OutOfMemory}!void {
    const Added = struct { text: []const u8, whole: bool, marks: u32, nmarks: u16, new: u32, shown: ?u32 = null };
    var added: std.ArrayList(Added) = .empty;
    var walk: diff.Walk = .{};
    var it = std.mem.splitScalar(u8, diffed, '\n');
    while (it.next()) |raw| {
        const l = walk.step(raw);
        switch (l.kind) {
            .hunk => {
                const h = diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?;
                try hunks.append(gpa, .{ .pin = k, .step = step, .ahead = ahead, .old_start = @intCast(h.old_start), .old_len = @intCast(h.old_count), .new_start = @intCast(h.new_start), .new_len = @intCast(h.new_count), .removed = @intCast(removed.items.len), .removed_len = 0 });
            },
            // A pin ahead of the shown revision: the lines it will write
            // are what the text has not.
            .added => if (k != Hunk.carrier and ahead) {
                const body = std.mem.trimEnd(u8, raw, "\r")[1..];
                try removed.appendSlice(gpa, body);
                try removed.append(gpa, '\n');
                hunks.items[hunks.items.len - 1].removed_len += @intCast(body.len + 1);
            },
            .removed => if (k != Hunk.carrier and !ahead) {
                const body = std.mem.trimEnd(u8, raw, "\r")[1..];
                try removed.appendSlice(gpa, body);
                try removed.append(gpa, '\n');
                hunks.items[hunks.items.len - 1].removed_len += @intCast(body.len + 1);
            },
            else => {},
        }
    }
    if (k == Hunk.carrier or ahead) return;
    // The patch view's rows of the same diff: a line it paired is one
    // changed (its marker has no `ground_line`), its words `ground_emph`.
    const patch = format: {
        const ctx: @import("hunks.zig").Ctx = .{ .arena = arena };
        break :format @import("hunks.zig").format(&ctx, "", diffed) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            else => return,
        };
    };
    var said = std.mem.splitScalar(u8, patch.text, '\n');
    var run_from = taken.items.len;
    var plus_from = added.items.len;
    for (patch.rows) |row| {
        const row_text = said.next() orelse break;
        if (row.kind == .hunk) {
            pairRun(taken.items[run_from..], added.items[plus_from..], plus_from);
            run_from = taken.items.len;
            plus_from = added.items.len;
        }
        if (row.kind != .added and row.kind != .removed) continue;
        const paired = row.styles.len > 0 and row.styles[0] & syntax.ground_line == 0;
        const from = marks.items.len;
        var i: usize = 1;
        while (i < row.styles.len) {
            if (row.styles[i] & syntax.ground_emph == 0) {
                i += 1;
                continue;
            }
            const run = i;
            while (i < row.styles.len and row.styles[i] & syntax.ground_emph != 0) i += 1;
            try marks.append(gpa, .{ @intCast(run - 1), @intCast(i - 1) });
        }
        const nmarks: u16 = @intCast(marks.items.len - from);
        if (row.kind == .added)
            try added.append(arena, .{ .text = row_text[@min(1, row_text.len)..], .whole = !paired, .marks = @intCast(from), .nmarks = nmarks, .new = @intCast(row.new orelse 0) })
        else
            try taken.append(arena, .{ .paired = paired, .marks = @intCast(from), .nmarks = nmarks });
    }
    pairRun(taken.items[run_from..], added.items[plus_from..], plus_from);
    var next: usize = 0;
    var rows = std.mem.splitScalar(u8, text, '\n');
    const taken_from = taken.items.len - count: {
        var n: usize = 0;
        for (hunks.items) |h| if (h.pin == k) {
            n += h.old_len;
        };
        break :count @min(n, taken.items.len);
    };
    for (lines, 0..) |*line, line_index| {
        const row = rows.next() orelse break;
        if (@intFromEnum(line.pin) != k) continue;
        const from = next;
        while (next < added.items.len and !std.mem.eql(u8, added.items[next].text, std.mem.trimEnd(u8, row, "\r"))) next += 1;
        if (next == added.items.len) {
            next = from;
            continue;
        }
        line.whole = added.items[next].whole;
        if (!line.whole) {
            line.marks = added.items[next].marks;
            line.nmarks = added.items[next].nmarks;
        }
        added.items[next].shown = @intCast(line_index);
        next += 1;
    }
    for (taken.items[taken_from..]) |*t| if (t.paired) {
        t.new = added.items[t.partner].new;
        t.shown = added.items[t.partner].shown;
    };
}

/// A run's lines taken away paired with the lines written, in order (the
/// alignment pairs each with a later one than the last it paired): each
/// paired one's partner, by its place in `plus`'s list (from `base`).
fn pairRun(minus: []Taken, plus: anytype, base: usize) void {
    var j: usize = 0;
    for (minus) |*m| if (m.paired) {
        while (j < plus.len and plus[j].whole) j += 1;
        if (j == plus.len) {
            m.paired = false;
            continue;
        }
        m.partner = base + j;
        j += 1;
    };
}

/// A run longer than this (lines taken away in one hunk) shows none of
/// them as ghost rows; the patch view's alignment gives up past 256 too.
const max_run = 1024;

/// The ghost rows (`Ghost`), in `at` order: each line a pin took away
/// whole or changed, where it stood (`carried` into the text); and each
/// pin's description after its last line (a pin none of whose lines is
/// left: after its last ghost row, or where its last hunk wrote). At one
/// place: the descriptions of pins whose lines end just above it, the
/// newest first (an inner block closes first), then the lines taken away,
/// older pins' first, each pin's description right after its own. A place
/// inside lines rewritten since jj's snapshot (`Moved.place`) has no row.
/// `text` holds the hunks' removed lines; the descriptions' rows go on
/// after them.
fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin, whole: []const [2][]const u8, lines: []const Line, hunks: []const Hunk, taken: []const Taken, text: *std.ArrayList(u8), now: i64, moved: Moved) error{OutOfMemory}![]Ghost {
    const Made = struct { g: Ghost, rank: u64 };
    var made: std.ArrayList(Made) = .empty;
    var ti: usize = 0;
    for (hunks) |h| {
        // A pin ahead: the lines it will write, after those it will take
        // away (or where it writes), where they will stand.
        if (h.ahead) {
            if (h.pin == Hunk.carrier or h.new_len == 0) continue;
            const at = carriedBack(hunks, h.step, if (h.old_len == 0) h.old_start else h.old_start - 1 + h.old_len, moved) orelse continue;
            var from: usize = h.removed;
            for (0..h.new_len) |n| {
                const nl = std.mem.indexOfScalarPos(u8, text.items, from, '\n') orelse text.items.len;
                defer from = nl + 1;
                try made.append(arena, .{
                    .g = .{ .at = at, .pin = h.pin, .kind = .added, .line = h.new_start + @as(u32, @intCast(n)), .text = @intCast(from), .len = @intCast(nl - from) },
                    .rank = 1 << 32 | made.items.len << 1,
                });
            }
            continue;
        }
        if (h.old_len == 0 or h.pin == Hunk.carrier) continue;
        const run = taken[@min(ti, taken.len)..@min(ti + h.old_len, taken.len)];
        ti += h.old_len;
        // A changed line's old text right above the line; a line taken
        // away whole above the next changed one's; after the last changed
        // one, right after its new text; with none changed, before the
        // lines written in their place (a diff's order: what went, then
        // what came).
        if (run.len > max_run) continue;
        var last: ?usize = null;
        for (run, 0..) |t, n| if (t.paired) {
            last = n;
        };
        var at = if (last) |n| next: {
            const shown = run[n].shown orelse carried(hunks, h.step, run[n].new -| 1, moved);
            break :next if (shown) |v| v + 1 else null;
        } else carried(hunks, h.step, if (h.new_len > 0) h.new_start - 1 else h.new_start, moved);
        var ats: [max_run]?u32 = undefined;
        var k = run.len;
        while (k > 0) {
            k -= 1;
            if (run[k].paired) at = run[k].shown orelse carried(hunks, h.step, run[k].new -| 1, moved);
            ats[k] = at;
        }
        var from: usize = h.removed;
        for (run, 0..) |t, n| {
            const nl = std.mem.indexOfScalarPos(u8, text.items, from, '\n') orelse text.items.len;
            defer from = nl + 1;
            try made.append(arena, .{
                .g = .{ .at = ats[n] orelse continue, .pin = h.pin, .kind = if (t.paired) .changed else .deleted, .line = h.old_start + @as(u32, @intCast(n)), .text = @intCast(from), .len = @intCast(nl - from), .marks = if (t.paired) t.marks else 0, .nmarks = if (t.paired) t.nmarks else 0 },
                .rank = 1 << 32 | made.items.len << 1,
            });
        }
    }
    for (pins, 0..) |pin, k| {
        var at: ?u32 = null;
        var rank: u64 = pins.len - k;
        var i = lines.len;
        while (i > 0) {
            i -= 1;
            if (@intFromEnum(lines[i].pin) == k or @intFromEnum(lines[i].going) == k) {
                at = @intCast(i + 1);
                break;
            }
        }
        if (at == null) {
            rank |= 2 << 32;
            for (made.items) |m| if (m.g.pin == k) {
                at = @max(at orelse 0, m.g.at);
            };
        }
        var first: u32 = 0;
        var end: u32 = 0;
        var step: u16 = 0;
        var ahead = false;
        for (hunks) |h| if (h.pin == k) {
            if (first == 0) first = h.new_start;
            // A pin ahead: after the lines it takes away, in its parent's.
            end = if (h.ahead) h.old_start - 1 + h.old_len + @intFromBool(h.old_len == 0) else if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start;
            step = h.step;
            ahead = h.ahead;
        };
        const place = at orelse (if (ahead) carriedBack(hunks, step, end, moved) else carried(hunks, step, end, moved)) orelse continue;
        // After its own ghost rows at its place.
        for (made.items) |m| if (m.g.pin == k and m.g.at == place) {
            rank = m.rank | 1;
        };
        const at_text = text.items.len;
        const author = try describe(gpa, text, pin, whole[k][0], whole[k][1], now);
        try made.append(arena, .{
            .g = .{ .at = place, .pin = @intCast(k), .kind = .description, .line = @max(first, 1), .text = @intCast(at_text), .len = @intCast(text.items.len - at_text), .author = @intCast(author - at_text) },
            .rank = rank,
        });
    }
    std.sort.pdq(Made, made.items, {}, struct {
        fn before(_: void, a: Made, b: Made) bool {
            return if (a.g.at != b.g.at) a.g.at < b.g.at else a.rank < b.rank;
        }
    }.before);
    const out = try gpa.alloc(Ghost, made.items.len);
    for (out, made.items) |*o, m| o.* = m.g;
    return out;
}

/// Where the place after line `after` of step `from`'s revision (its
/// change's place in jj's answer, `Hunk.step`) is in the text: moved by each later change's hunks before it (a pin's, or one
/// between the pins the revset does not pin), or, inside a run of lines a
/// later one took away, after what it wrote there; then from jj's lines
/// to the text's (`moved`).
fn carried(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 {
    var pos: i64 = after;
    var i: usize = 0;
    while (i < hunks.len) {
        const j = hunks[i].step;
        var shift: i64 = 0;
        var inside: ?i64 = null;
        while (i < hunks.len and hunks[i].step == j) : (i += 1) {
            const h = hunks[i];
            // A change ahead of the shown revision moves nothing in it.
            if (j <= from or h.ahead) continue;
            if (h.old_len == 0) {
                if (h.old_start < pos) shift += h.new_len;
            } else if (h.old_start + h.old_len - 1 <= pos) {
                shift += @as(i64, h.new_len) - h.old_len;
            } else if (h.old_start <= pos) inside = @as(i64, h.new_start) - 1 + h.new_len;
        }
        if (j > from) pos = inside orelse pos + shift;
    }
    return moved.place(@intCast(std.math.clamp(pos, 0, @as(i64, moved.was))));
}

/// Where the place after line `after` of the revision step `from`'s change
/// (a pin ahead of the shown revision) was made from is in the text: moved
/// back through each change ahead of the shown revision before it, newest
/// first, their hunks turned round; then from jj's lines to the text's
/// (`moved`).
fn carriedBack(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 {
    var pos: i64 = after;
    var i = hunks.len;
    while (i > 0) {
        const j = hunks[i - 1].step;
        var lo = i;
        while (lo > 0 and hunks[lo - 1].step == j) lo -= 1;
        defer i = lo;
        if (j >= from or !hunks[lo].ahead) continue;
        var shift: i64 = 0;
        var inside: ?i64 = null;
        for (hunks[lo..i]) |h| {
            if (h.new_len == 0) {
                if (h.new_start < pos) shift += h.old_len;
            } else if (h.new_start + h.new_len - 1 <= pos) {
                shift += @as(i64, h.old_len) - h.new_len;
            } else if (h.new_start <= pos) inside = @as(i64, h.old_start) - 1 + h.old_len;
        }
        pos = inside orelse pos + shift;
    }
    return moved.place(@intCast(std.math.clamp(pos, 0, @as(i64, moved.was))));
}

/// The lines of the text a pin ahead of the shown revision takes away,
/// going (`Line.going`), its lane beside them.
fn going(lines: []Line, hunks: []const Hunk, moved: Moved) void {
    for (hunks) |h| {
        if (!h.ahead or h.pin == Hunk.carrier or h.old_len == 0) continue;
        const first = carriedBack(hunks, h.step, h.old_start - 1, moved) orelse continue;
        const pin: PinIndex = @enumFromInt(h.pin);
        for (lines[@min(first, lines.len)..@min(first + h.old_len, lines.len)]) |*l| {
            l.going = pin;
            if (std.mem.indexOfScalar(PinIndex, &l.lanes, pin) != null) continue;
            if (std.mem.indexOfScalar(PinIndex, &l.lanes, .none)) |free| l.lanes[free] = pin;
        }
    }
}

/// A pin's description line (PARDES.md: `id title author age`, one blank
/// between): its id's first four letters, its whole title (its
/// description's first line), its whole author, its age short (`5h`, `2d`,
/// `3w`, `4m`, `1y`; under an hour `now`), no "ago". Nothing is cut: a
/// line too long for its pane wraps as any line does. Where its author
/// starts in `text`. A `Compare`'s pair: its row (`PairRow.say`), its
/// title, whole; no author.
fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, author: []const u8, title: []const u8, now: i64) error{OutOfMemory}!usize {
    if (isPair(pin)) {
        try text.appendSlice(gpa, title);
        return text.items.len;
    }
    try text.print(gpa, "{s} {s} ", .{ pin.id[0..4], title });
    const at = text.items.len;
    try text.print(gpa, "{s} ", .{author});
    const s = @max(0, now - pin.time);
    const day = 24 * 3600;
    for ([_]struct { u8, i64 }{ .{ 'y', 365 * day }, .{ 'm', 30 * day }, .{ 'w', 7 * day }, .{ 'd', day }, .{ 'h', 3600 } }) |unit| {
        if (s >= unit[1]) {
            try text.print(gpa, "{d}{c}", .{ @divFloor(s, unit[1]), unit[0] });
            return at;
        }
    }
    try text.appendSlice(gpa, "now");
    return at;
}

/// A pin a `Compare` made of two points (`pairsAnswer`): its title, its
/// row, starts with its id (the first point's) and `..`.
fn isPair(pin: Pin) bool {
    const title = pin.title[0..pin.title_len];
    return title.len > 10 and std.mem.startsWith(u8, title, &pin.id) and std.mem.startsWith(u8, title[8..], "..");
}

/// The lanes on ghost line `gi` (`ghosts[gi]`): those of the line above it
/// that run on below it or whose description is this line or one after it
/// at the same place, then its own pin's (on a description's rows after
/// its first, not: its lane ended in the arrow).
fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize, first_row: bool) [levels]PinIndex {
    const g = ghosts[gi];
    var out: [levels]PinIndex = @splat(.none);
    var n: usize = 0;
    if (g.at > 0 and g.at - 1 < ch.lines.len) for (ch.lines[g.at - 1].lanes) |lane| {
        if (lane == .none) break;
        const below = g.at < ch.lines.len and std.mem.indexOfScalar(PinIndex, &ch.lines[g.at].lanes, lane) != null;
        const closes = for (ghosts[gi..]) |later| {
            if (later.at != g.at) break false;
            if (later.kind == .description and later.pin == @intFromEnum(lane)) break true;
        } else false;
        if (!below and !closes) continue;
        if (!first_row and g.kind == .description and @intFromEnum(lane) == g.pin) continue;
        out[n] = lane;
        n += 1;
    };
    const own = first_row or g.kind != .description;
    if (own and n < levels and std.mem.indexOfScalar(PinIndex, out[0..n], @enumFromInt(g.pin)) == null) out[n] = @enumFromInt(g.pin);
    return out;
}

/// A ghost line's cells on one of its rows (body row `vr`, from byte
/// `from` of buffer line `row` to byte `to`): a line taken away whole red
/// across, its text in the line numbers' grey (dimmer than the text's ink);
/// a changed line's old text grey, the words that went red; a
/// description's id and title in its lane's colour `lane`, or with one
/// change pinned (no one colour a lane) its id in the theme's keyword ink,
/// its author and age grey. All of them the chrome's (Chrome.add, .del).
fn inkGhost(p: *Pardes, s: *pardes.Surface, pane: *const Pane, g: Ghost, row: i32, from: usize, to: usize, pad: i32, marks: []const [2]u32, lane: ?[3]u8, x: u16, y: u16, w: u16) void {
    const chrome = p.chrome();
    const tab = p.settings.tab;
    const said = File.sourceLine(pane, row);
    const Ink = struct {
        q: *Pardes,
        s: *pardes.Surface,
        pane: *const Pane,
        row: i32,
        from: usize,
        to: usize,
        pad: i32,
        x: u16,
        y: u16,
        w: u16,
        /// The cells of bytes `lo` to `hi` on this row.
        fn cells(k: @This(), lo: usize, hi: usize) [2]u16 {
            const a = @max(k.from, lo);
            const b = @min(k.to, hi);
            if (a >= b) return .{ 0, 0 };
            const c0 = k.pad + File.displayOffset(k.q.settings.tab, k.pane, k.row, @intCast(k.from), @intCast(a));
            const c1 = k.pad + File.displayOffset(k.q.settings.tab, k.pane, k.row, @intCast(k.from), @intCast(b));
            return .{ @intCast(std.math.clamp(c0, 0, k.w)), @intCast(std.math.clamp(c1, 0, k.w)) };
        }
        fn fg(k: @This(), lo: usize, hi: usize, rgb: [3]u8) void {
            const c = k.cells(lo, hi);
            for (c[0]..c[1]) |cell| k.s.at(k.x + @as(u16, @intCast(cell)), k.y).style.fg = .{ .rgb = rgb };
        }
    };
    const ink: Ink = .{ .q = p, .s = s, .pane = pane, .row = row, .from = from, .to = to, .pad = pad, .x = x, .y = y, .w = w };
    _ = tab;
    switch (g.kind) {
        .deleted => s.tint(x, y, w, chrome.del.row, chrome.line_number),
        .added => s.tint(x, y, w, chrome.add.row, null),
        .changed => {
            ink.fg(0, said.len, chrome.line_number);
            for (marks[g.marks..][0..g.nmarks]) |m| {
                const c = ink.cells(m[0], m[1]);
                if (c[0] < c[1]) s.tint(x + c[0], y, c[1] - c[0], chrome.del.emph, null);
            }
        },
        .description => {
            // `id title author age`: the id (and with several pinned the
            // title) in the lane's colour, the author and the age grey.
            const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len;
            const author = @min(g.author, said.len);
            ink.fg(0, if (lane != null) author else id_end, lane orelse chrome.syntax[@intFromEnum(syntax.Syn.keyword)]);
            ink.fg(author, said.len, chrome.line_number);
        },
    }
}

/// A changed line's words that came (`marks`, byte ranges of line `row`),
/// green on body row `vr`, as much of them as the row shows.
fn inkCame(p: *Pardes, s: *pardes.Surface, pane: *Pane, marks: []const [2]u32, row: i32, vr: u16, x: u16, y: u16, w: u16) void {
    const tab = p.settings.tab;
    const len: u32 = @intCast(File.sourceLine(pane, row).len);
    const here = pane.wrapAt(tab, vr);
    const next = pane.wrapAt(tab, @as(i32, vr) + 1);
    const first: u32 = @intCast(here.at);
    const end: u32 = if (next.line == row) @intCast(next.at) else len;
    for (marks) |m| {
        const lo = @max(first, @min(m[0], len));
        const hi = @min(end, @min(m[1], len));
        if (lo >= hi) continue;
        const from = here.pad + File.displayOffset(tab, pane, row, @intCast(first), @intCast(lo));
        const to = @min(@as(i32, w), here.pad + File.displayOffset(tab, pane, row, @intCast(first), @intCast(hi)));
        if (from >= 0 and from < to) s.tint(x + @as(u16, @intCast(from)), y, @intCast(to - from), p.chrome().add.emph, null);
    }
}

/// The pin buffer row `row` of `f` is one of: of a ghost line, its pin's
/// (none for a description); of a file line, the pin that wrote it.
fn ownerOf(ch: *const Changes, f: *const File.State, row: usize) PinIndex {
    if (File.readOnlyRow(f, row)) |k| {
        if (k >= ch.ghosts.len) return .none;
        const g = ch.ghosts[k];
        return if (g.kind == .description) .none else @enumFromInt(g.pin);
    }
    const line = File.fileRow(f, row);
    if (line >= ch.lines.len) return .none;
    return if (ch.lines[line].going != .none) ch.lines[line].going else ch.lines[line].pin;
}

/// The line `]g` (`forward`) or `[g` goes to from buffer line `from` of
/// the pane: the next or the previous change's first line (the first of a
/// run of lines one pin wrote or took away: a ghost line is a line); null
/// with none shown, or none that way, or none in the `most` lines looked
/// at (a body's painted targets look at the rows shown alone).
pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool, most: usize) ?usize {
    const f = if (pane.file) |*file| file else return null;
    // No changes shown: the last edit not saved yet is one (POLISH 11:
    // `]g` and its painted target found nothing in an edited file).
    if (pane.layers.lanes == 0) {
        if (f.revision == f.saved_revision) return null;
        const at = pane.body.last_edit orelse return null;
        const line: usize = @intCast(@max(0, at.row));
        if (forward and line > from and line - from <= most) return line;
        if (!forward and line < from and from - line <= most) return line;
        return null;
    }
    const ch = answered(p, f.layer.owner) orelse return null;
    const n = File.lineCount(f.content);
    var row = from;
    for (0..most) |_| {
        if (forward) {
            row += 1;
            if (row >= n) return null;
        } else {
            if (row == 0) return null;
            row -= 1;
        }
        const owner = ownerOf(ch, f, row);
        if (owner != .none and (row == 0 or ownerOf(ch, f, row - 1) != owner)) return row;
    }
    return null;
}

/// A Look (B3) at column `col` of body row `vr` of pane `id` on the id of
/// a change's description line (mouse.zig): its change's patch at the row
/// for the last line of it this file has (`Diff <id> <path>:<line>`, what a
/// user could type). False anywhere else: the Look is a regular one.
pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool {
    const pane = p.panes[id].?;
    const f = if (pane.file) |*file| file else return false;
    const ch = answered(p, f.layer.owner) orelse return false;
    const tab = p.settings.tab;
    const w = pane.wrapAt(tab, vr);
    if (w.line < 0 or w.at != 0) return false;
    const gi = File.readOnlyRow(f, @intCast(w.line)) orelse return false;
    if (gi >= ch.ghosts.len) return false;
    const g = ch.ghosts[gi];
    if (g.kind != .description) return false;
    const said = File.sourceLine(pane, w.line);
    const at = File.byteAtRowDisplay(tab, pane, w.line, 0, col - @as(i32, File.gutterWidth(pane)) - w.pad);
    const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len;
    if (at < 0 or at >= id_end) return false;
    const path = if (of(f)) |r| r.path else f.path;
    var last: u32 = g.line;
    for (ch.hunks) |h| if (h.pin == g.pin) {
        last = @max(last, h.new_start + h.new_len -| 1);
    };
    var line: [4200]u8 = undefined;
    // A pair's row starts with its two points (`from..to`): its patch.
    const change: []const u8 = if (isPair(ch.pins[g.pin])) said[0..id_end] else &ch.pins[g.pin].id;
    const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ change, path, last }) catch return true;
    pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg);
    return true;
}

/// A jj change id as jj writes one: its letters, k to z.
pub fn isChangeId(text: []const u8) bool {
    if (text.len < 4 or text.len > 32) return false;
    for (text) |c| if (c < 'k' or c > 'z') return false;
    return true;
}

/// `Diff <change> [path[:line]]` (hunks.zig): change `change` of the
/// repository pane `id`'s directory is in, its patch as `jj show --git`
/// prints it (its ids, author, dates and whole message above its hunks),
/// stacked in its +Diff (one a change: a second goes to it); the cursor on
/// the patch's row for `path`'s line `line` (that file's first row
/// without one; none of it: the top). With `any`, `change` is any word jj
/// takes for one revision (`@-`, a bookmark, a commit). False when it
/// names none.
pub fn diffChange(p: *Pardes, id: usize, arg: []const u8, any: bool) bool {
    var words = std.mem.tokenizeAny(u8, arg, " \t");
    const change = words.next() orelse return false;
    if (!any and !isChangeId(change)) return false;
    const dir = pardes.filesystem.localPath(Pardes.paneDir(p.panes[id].?)) orelse return false;
    var buf: [128]u8 = undefined;
    const revset = if (any) change else std.fmt.bufPrint(&buf, "change_id({s})", .{change}) catch return false;
    const shown = p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dir, @as([]const []const u8, &.{ "show", "--git", "-r", revset }) });
    const bytes = switch (shown) {
        .refused => |why| {
            p.gpa.free(why);
            return false;
        },
        .bytes => |b| b,
    };
    defer p.gpa.free(bytes);
    var name: [4200]u8 = undefined;
    const hid = @import("hunks.zig").openDiff(p, id, std.fmt.bufPrint(&name, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), change }) catch return false, bytes) catch return false;
    p.view().active = hid;
    const place = look.parsePathLine(words.next() orelse return true);
    standAt(p, hid, std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, place.path }) catch return true, place.at.line);
    return true;
}

/// The cursor of +Diff `hid` on the patch's row for line `line` of `want`
/// (absolute): that file's first row when the line is not in it; none of
/// it, where it was.
fn standAt(p: *Pardes, hid: usize, want: []const u8, line: usize) void {
    const pane = p.panes[hid].?;
    var best: ?usize = null;
    for (pane.file.?.location_rows, 0..) |row, i| {
        if (!std.mem.endsWith(u8, want, row.path) or row.path.len == 0) continue;
        if (best == null) best = i;
        if (row.at.line == line) {
            best = i;
            break;
        }
    }
    if (best) |i| {
        pane.body.cur_row = @intCast(i);
        pane.body.cur_col = 0;
        pane.ensureCursorVisible(p.settings.tab);
    }
}

/// `Diff <from>..<to> [path[:line]]` (hunks.zig): a `Compare`'s pair, its
/// patch: the difference between the two points as `jj diff --from --to
/// --git` prints it (of `path` alone when one is given), on top the changes
/// between them, newest first, a line each, `+ id title author day` for one
/// in `to` and not in `from`, `-` the other way (what the difference takes
/// back); stacked in a +Diff, the cursor on the row of `path`'s `line`.
/// What jj refuses is said in its words. False when the word is not two
/// ids (a change's or a commit's) joined by `..`.
pub fn diffPair(p: *Pardes, id: usize, arg: []const u8) bool {
    var words = std.mem.tokenizeAny(u8, arg, " \t");
    const range = words.next() orelse return false;
    const dots = std.mem.indexOf(u8, range, "..") orelse return false;
    const from = range[0..dots];
    const to = range[dots + 2 ..];
    if (!isRevisionId(from) or !isRevisionId(to)) return false;
    const dir = pardes.filesystem.localPath(Pardes.paneDir(p.panes[id].?)) orelse return false;
    const arena = p.scratch.allocator();
    const place = look.parsePathLine(words.next() orelse "");
    const path: ?[]const u8 = if (place.path.len == 0) null else std.Io.Dir.path.resolvePosix(arena, &.{ dir, place.path }) catch return true;
    const at = if (path) |f| dirOf(f) else dir;
    const set: ?[]const u8 = if (path) |f| fileset(arena, f) catch return true else null;
    const between = std.fmt.allocPrint(arena, "(({s})..({s}) | ({s})..({s})){s}{s}{s}", .{ from, to, to, from, if (set != null) " & files(" else "", set orelse "", if (set != null) ")" else "" }) catch return true;
    const template = std.fmt.allocPrint(arena, "if(self.contained_in(\"::({s})\"), \"+ \", \"- \") ++ change_id.short(8) ++ \" \" ++ description.first_line() ++ \" \" ++ author.name() ++ \" \" ++ author.timestamp().utc().format(\"%Y-%m-%d\") ++ \"\\n\"", .{to}) catch return true;
    const listed = switch (p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, at, @as([]const []const u8, &.{ "log", "--no-graph", "-r", between, "-T", template }) })) {
        .refused => |why| return pairRefused(p, id, why),
        .bytes => |b| b,
    };
    defer p.gpa.free(listed);
    const argv = [_][]const u8{ "diff", "--from", from, "--to", to, "--git", "--", set orelse "" };
    const diffed = switch (p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, at, @as([]const []const u8, argv[0 .. if (set != null) argv.len else argv.len - 2]) })) {
        .refused => |why| return pairRefused(p, id, why),
        .bytes => |b| b,
    };
    defer p.gpa.free(diffed);
    const bytes = std.fmt.allocPrint(arena, "Compare {s}..{s}\n{s}\n{s}", .{ from, to, listed, diffed }) catch return true;
    const name = std.fmt.allocPrint(arena, "{s}/{s}..{s}", .{ std.mem.trimEnd(u8, dir, "/"), from, to }) catch return true;
    const hid = @import("hunks.zig").openDiff(p, id, name, bytes) catch |err| return pairRefused(p, id, p.gpa.dupe(u8, if (err == error.NoHunks) "no difference" else @errorName(err)) catch return true);
    p.view().active = hid;
    if (path) |f| standAt(p, hid, f, place.at.line);
    return true;
}

/// A `Diff` of a pair that jj refused (`why`, freed): said in its words;
/// a plumbing rule's declines, saying nothing.
fn pairRefused(p: *Pardes, id: usize, why: []u8) bool {
    defer p.gpa.free(why);
    if (p.plumb_declined) |*d| {
        d.* = true;
        return true;
    }
    var line: pardes.Kind.Buf(512) = .{};
    p.reportFailure(id, line.print("Diff: {s}", .{why[0..@min(why.len, 480)]}));
    return true;
}

/// A word that may be a change id or a commit id: 4 to 40 of `0-9`, `a-z`.
fn isRevisionId(text: []const u8) bool {
    if (text.len < 4 or text.len > 40) return false;
    for (text) |c| if (!std.ascii.isDigit(c) and !std.ascii.isLower(c)) return false;
    return true;
}

/// Each line's lanes: the blocks of the pins that span it, oldest first.
/// A pin's block runs from a line it wrote on to each next line it wrote
/// while every line between was written by a newer pin: its lane unbroken
/// down what it wrote, through what later pins rewrote inside it. An older
/// pin's line (or one no pin wrote) ends a newer pin's block, so blocks
/// nest, the older outside, and a block keeps its level down all its rows:
/// the spine keeps its place, a nested change steps to the right on its
/// rows only. Past `levels`, the innermost are not drawn.
fn nest(lines: []Line, npins: usize) void {
    for (0..npins) |k| {
        var i: usize = 0;
        while (i < lines.len) {
            if (@intFromEnum(lines[i].pin) != k) {
                i += 1;
                continue;
            }
            var last = i;
            for (lines[i + 1 ..], i + 1..) |l, j| {
                const q = @intFromEnum(l.pin);
                if (q == k) last = j else if (l.pin == .none or q < k) break;
            }
            for (lines[i .. last + 1]) |*l| for (&l.lanes) |*lane| if (lane.* == .none) {
                lane.* = @enumFromInt(k);
                break;
            };
            i = last + 1;
        }
    }
}

/// The pane's pinned changes as a view shows them, on its body's rows (body_layer.zig, while
/// File.Layers.lanes is set): in the gutter's lane cells after the number a
/// lane each pin whose block runs down the row, at its level, a glyph in a
/// terminal, a strip of pixels in a window (Surface.lanes); a line a pin
/// added whole green across it, as a diff's added line, a changed line's
/// words that came green; on each row of a ghost line (`Ghost`) its lanes
/// and its cells (`inkGhost`).
pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
    if (pane.layers.heat > 0) paintHeat(p, s, pane, r, tx, body_h);
    if (pane.layers.lanes > 0) paintLanes(p, s, pane, r, tx, tw, body_h);
}

/// A count's colour on churn's eight steps from the line numbers' grey to
/// the deleted hue (Chrome.heat, worked out with the theme), on a log scale
/// of the count against the hottest; null for none.
fn heatColour(c: *const pardes.colors.Chrome, count: u16, hottest: u16) ?[3]u8 {
    if (count == 0 or hottest == 0) return null;
    const t = @log(@as(f32, @floatFromInt(count)) + 1) / @log(@as(f32, @floatFromInt(hottest)) + 1);
    return c.heat[@min(c.heat.len, @as(usize, @intFromFloat(@ceil(t * c.heat.len)))) -| 1];
}

/// The heat lane: a cell after the line number (before the changes'
/// lanes, which stay next to the text they mark), a half block in its
/// line's colour; none on a ghost line or a line in no declaration.
fn paintHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, body_h: u16) void {
    const heat = churned(p, pane.serial) orelse return;
    const f = if (pane.file) |*file| file else return;
    const x = tx + File.gutterWidth(pane) - File.laneCells(pane) - 1;
    const body_y = p.bodyTop(pane, r);
    const scroll = pane.scroll();
    var vr: u16 = pane.context_rows;
    while (vr < body_h) : (vr += 1) {
        const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break;
        if (row < 0 or File.readOnlyRow(f, @intCast(row)) != null) continue;
        const line = File.fileRow(f, @intCast(row));
        if (line >= heat.lines.len) continue;
        const rgb = heatColour(p.chrome(), heat.lines[line], heat.hottest) orelse continue;
        var style = s.at(x, body_y + vr).style;
        style.fg = .{ .rgb = rgb };
        s.set(x, body_y + vr, "\u{258c}", style);
    }
}

/// Churn's strip by the scroll thumb (draw.zig, while a view shows it): a
/// rail row each, the hottest line of the lines that row stands for; in a
/// terminal the rail's second cell's ground, for a pixel shell a list
/// (Surface.heat).
pub fn railHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, id: usize, rail: pardes.Rect) void {
    const heat = churned(p, pane.serial) orelse return;
    const total = heat.lines.len;
    if (rail.h == 0 or total == 0) return;
    for (0..rail.h) |row| {
        const lo = row * total / rail.h;
        const hi = @max(lo + 1, (row + 1) * total / rail.h);
        const rgb = heatColour(p.chrome(), std.mem.max(u16, heat.lines[lo..@min(hi, total)]), heat.hottest) orelse continue;
        if (p.view().frontend.windowed)
            s.heat.append(p.gpa, .{ .owner = @intCast(id), .row = @intCast(row), .rgb = rgb }) catch {}
        else
            s.fill(rail.x + 1, rail.y + @as(u16, @intCast(row)), 1, 1, .{ .bg = .{ .rgb = rgb } });
    }
}

fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
    const f = if (pane.file) |*file| file else return;
    const ch = answered(p, f.layer.owner) orelse return;
    if (ch.lines.len == 0) return;
    const tab = p.settings.tab;
    const chrome = p.chrome();
    const colours = chrome.lanes[0..chrome.lanes_len];
    // One change pinned is a diff: its lane in the diff's own two markers
    // (the user's rulings of 2026-11-23: added beside a row it wrote, deleted
    // beside one it took away); several, a colour a change, to tell them
    // apart.
    const one = ch.pins.len == 1;
    const gutter = File.gutterWidth(pane);
    const cells = File.laneCells(pane);
    if (gutter >= tw or cells == 0) return;
    const first = tx + gutter - cells;
    const windowed = p.view().frontend.windowed;
    const body_y = p.bodyTop(pane, r);
    const nrows = File.lineCount(f.content);
    var vr: u16 = pane.context_rows;
    while (vr < body_h) : (vr += 1) {
        const y = body_y + vr;
        var taken = false;
        // On a description's first row, its change's lane: an arrow to it.
        var points: PinIndex = .none;
        const w = pane.wrapAt(tab, vr);
        if (w.line < 0) continue;
        const row: usize = @intCast(w.line);
        if (row >= nrows) break;
        const lanes: [levels]PinIndex = if (File.readOnlyRow(f, row)) |gi| ghost: {
            // A ghost line, on each row it wraps to.
            if (gi >= ch.ghosts.len) continue;
            const g = ch.ghosts[gi];
            const next = pane.wrapAt(tab, @as(i32, vr) + 1);
            const to: usize = if (next.line == w.line) @intCast(next.at) else File.sourceLine(pane, w.line).len;
            const first_row = w.at <= 0;
            inkGhost(p, s, pane, g, w.line, @intCast(@max(0, w.at)), to, w.pad, ch.marks, if (one) null else colours[g.pin % colours.len], tx + gutter, y, tw - gutter);
            if (g.kind == .description and first_row) points = @enumFromInt(g.pin);
            taken = g.kind == .deleted or g.kind == .changed or (g.kind == .description and takenAbove(ch.ghosts, gi));
            break :ghost ghostLanes(ch, ch.ghosts, gi, first_row);
        } else line: {
            const at = File.fileRow(f, row);
            if (at >= ch.lines.len) continue;
            const line = ch.lines[at];
            if (line.whole and line.pin != .none) s.tint(tx + gutter, y, tw - gutter, chrome.add.row, null);
            // Going: a pin ahead takes it away.
            if (line.going != .none) s.tint(tx + gutter, y, tw - gutter, chrome.del.row, null);
            taken = line.going != .none;
            if (!line.whole and line.nmarks > 0) inkCame(p, s, pane, ch.marks[line.marks..][0..line.nmarks], w.line, vr, tx + gutter, y, tw - gutter);
            break :line line.lanes;
        };
        for (lanes, 0..) |lane, level| {
            if (lane == .none) break;
            const arrow = lane == points;
            const rgb = if (one) (if (taken) chrome.del.ink else chrome.add.ink) else colours[@intFromEnum(lane) % colours.len];
            if (windowed) {
                // A body a pixel shell draws as a layer is painted on a
                // temporary surface first: its lanes are not drawn yet.
                if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb, .arrow = if (arrow) @intCast(cells) else 0 }) catch {};
            } else if (level < cells) {
                var style = s.at(first + @as(u16, @intCast(level)), y).style;
                style.fg = .{ .rgb = rgb };
                // An arrow: the lane bent into a shaft and a head at the text
                // (`╰─→`, the user's choice of 2026-11-23 over `▎─→`); from
                // the last level, where there is one cell, a bent arrow.
                const at: u16 = @intCast(level);
                s.set(first + at, y, if (!arrow) "\u{258e}" else if (at + 1 == cells) "\u{21b3}" else "\u{2570}", style);
                if (arrow) for (at + 1..cells) |c| s.set(first + @as(u16, @intCast(c)), y, if (c + 1 == cells) "\u{2192}" else "\u{2500}", style);
            }
        }
    }
}

/// Whether the row above description `ghosts[gi]` is one its lanes stand
/// beside as taken away: a ghost row of a line at its place, not a line.
fn takenAbove(ghosts: []const Ghost, gi: usize) bool {
    var j = gi;
    while (j > 0) {
        j -= 1;
        if (ghosts[j].at != ghosts[gi].at) return false;
        if (ghosts[j].kind == .added) return false;
        if (ghosts[j].kind != .description) return true;
    }
    return false;
}

// ---- tests ----

const testing = std.testing;

test "path@rev splits at its first @: a path before it, a revision after" {
    const cases = [_]struct { []const u8, []const u8, []const u8 }{
        .{ "a.zig@main", "a.zig", "main" },
        .{ "core/File.zig@@-", "core/File.zig", "@-" },
        .{ "x.zig@main@origin", "x.zig", "main@origin" },
    };
    for (cases) |c| {
        const got = split(c[0]).?;
        try testing.expectEqualStrings(c[1], got.path);
        try testing.expectEqualStrings(c[2], got.rev);
    }
    for ([_][]const u8{ "@p12", "a.zig@", "a.zig", "dir/@x" }) |text| try testing.expect(split(text) == null);
}

/// A jj repository in a test's directory: `a.zig` committed as `one`, then
/// as `two`, and `three` in its working copy, never snapshotted. Null with
/// no jj to run.
const Repo = struct {
    tmp: testing.TmpDir,
    dir: []const u8,
    file: []const u8,

    const one = "const one = 1;\nconst x = 2;\n";
    const two = "const two = 2;\nconst x = 2;\nconst y = 3;\n";
    const three = "const three = 3;\n";

    fn init(gpa: std.mem.Allocator) !?Repo {
        return with(gpa, &.{ .{ one, "one" }, .{ two, "two" } }, three);
    }

    /// `a.zig` committed as each text with its message, in order; then
    /// `working` in the working copy, never snapshotted.
    fn with(gpa: std.mem.Allocator, commits: []const [2][]const u8, working: ?[]const u8) !?Repo {
        var tmp = testing.tmpDir(.{});
        errdefer tmp.cleanup();
        var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
        const dir = try gpa.dupe(u8, buf[0..try tmp.dir.realPath(testing.io, &buf)]);
        errdefer gpa.free(dir);
        if (!try run(gpa, dir, &.{ "git", "init" })) return null;
        for (commits) |c| {
            try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = c[0] });
            if (!try run(gpa, dir, &.{ "commit", "-m", c[1] })) return null;
        }
        if (working) |text| try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text });
        return .{ .tmp = tmp, .dir = dir, .file = try std.fmt.allocPrint(gpa, "{s}/a.zig", .{dir}) };
    }

    fn run(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) !bool {
        var argv: std.ArrayList([]const u8) = .empty;
        defer argv.deinit(gpa);
        try argv.appendSlice(gpa, &.{ "jj", "--config=user.name=t", "--config=user.email=t@t", "--quiet" });
        try argv.appendSlice(gpa, args);
        const r = std.process.run(gpa, testing.io, .{ .argv = argv.items, .cwd = .{ .path = dir } }) catch return false;
        gpa.free(r.stdout);
        gpa.free(r.stderr);
        return r.term == .exited and r.term.exited == 0;
    }

    fn deinit(r: *Repo, gpa: std.mem.Allocator) void {
        gpa.free(r.file);
        gpa.free(r.dir);
        r.tmp.cleanup();
    }
};

fn told(p: *Pardes, id: usize) []const u8 {
    const pane = p.panes[id].?;
    return p.messages.saidBy(pane);
}

test "At shows a file at a revision beside it, read-only, coloured as its file; a Look at path@rev:line goes to it; At in it turns it in place; jj's refusals are said" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
    p.settings.jumps = .@"new-pane";
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const file = p.view().active;
    try testing.expectEqualStrings(Repo.three, p.panes[file].?.file.?.content);
    p.update(.{ .command = "At @-" });
    const shown = p.view().active;
    try testing.expect(shown != file);
    const pane = p.panes[shown].?;
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    const name = try std.fmt.allocPrint(gpa, "{s}@@-", .{repo.file});
    defer gpa.free(name);
    try testing.expectEqualStrings(name, try pardes.tagline.pathPrefix(p, p.scratch.allocator(), pane));
    try testing.expectEqualStrings(repo.file, File.langPath(&pane.file.?));
    try testing.expect(pane.colorAlgo() == .source);
    // Read-only: a key's edit and a whole-text edit (dd) change nothing, and a bare Save says so.
    for ("iz") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    for ("dd") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    p.update(.{ .command = "Save" });
    try testing.expect(std.mem.indexOf(u8, told(p, shown), "is a revision, read-only") != null);
    // From the file's pane, a Look at the address with a line goes there.
    p.view().active = file;
    p.update(.{ .command = "Look a.zig@@-:3" });
    try testing.expectEqual(shown, p.view().active);
    try testing.expectEqual(@as(i32, 2), pane.body.cur_row);
    // Turned to another revision in its place: one pane, the older text.
    p.update(.{ .command = "At @--" });
    const turned = p.view().active;
    try testing.expect(p.panes[shown] == null);
    try testing.expectEqualStrings(Repo.one, p.panes[turned].?.file.?.content);
    var n: usize = 0;
    for (p.panes) |slot| if (slot) |s| if (s.file) |*f| {
        n += @intFromBool(of(f) != null);
    };
    try testing.expectEqual(@as(usize, 1), n);
    // jj's refusals, in its words.
    p.update(.{ .command = "At nosuch" });
    try testing.expect(std.mem.indexOf(u8, told(p, turned), "At: Revision `nosuch` doesn't exist") != null);
    p.view().active = file;
    p.update(.{ .command = "At" });
    try testing.expect(std.mem.indexOf(u8, told(p, file), "At: which revision?") != null);
    // Bare in a revision's pane: the file.
    p.view().active = turned;
    p.update(.{ .command = "At" });
    try testing.expectEqual(file, p.view().active);
}

test "a client replays the open of a file at a revision and ends equal" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const R = pardes.replica;
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-:2", .{repo.file}) }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    try testing.expectEqualStrings(Repo.two, a.core.panes[id].?.file.?.content);
    try testing.expectEqualStrings(Repo.two, r.core().panes[id].?.file.?.content);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "Changes pins a revset's changes on the pane, shown in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare hides and shows them; jj's refusals are said" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    p.update(.{ .command = "Changes @--::@-" });
    try testing.expectEqual(levels, pane.layers.lanes);
    const ch = answered(p, pane.serial).?;
    try testing.expectEqualStrings("@--::@-", ch.pinned());
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    for (ch.pins, [_][]const u8{ "one", "two" }) |pin, title| {
        try testing.expectEqualStrings(title, pin.title[0..pin.title_len]);
        try testing.expectEqualStrings("t", pin.author[0..pin.author_len]);
        try testing.expect(pin.time > 0);
    }
    // `two` changed line 1 (`one`'s first) and added line 3 whole; line 2 is `one`'s, added whole.
    const one: PinIndex = @enumFromInt(0);
    const two: PinIndex = @enumFromInt(1);
    const want = [_]Line{
        .{ .pin = two, .whole = false, .lanes = .{ two, .none, .none }, .marks = 2, .nmarks = 2 },
        .{ .pin = one, .whole = true, .lanes = .{ one, .none, .none } },
        .{ .pin = two, .whole = true, .lanes = .{ two, .none, .none } },
    };
    try testing.expectEqualSlices(Line, &want, ch.lines);
    // The patch view's alignment: the words that went (`one`, `1`), then
    // those that came (`two`, `2`), byte ranges of each line.
    try testing.expectEqualSlices([2]u32, &.{ .{ 6, 9 }, .{ 12, 13 }, .{ 6, 9 }, .{ 12, 13 } }, ch.marks);
    const hunks = [_]Hunk{
        .{ .pin = 0, .step = 0, .old_start = 0, .old_len = 0, .new_start = 1, .new_len = 2, .removed = 0, .removed_len = 0 },
        .{ .pin = 1, .step = 1, .old_start = 1, .old_len = 1, .new_start = 1, .new_len = 1, .removed = 0, .removed_len = 15 },
        .{ .pin = 1, .step = 1, .old_start = 2, .old_len = 0, .new_start = 3, .new_len = 1, .removed = 15, .removed_len = 0 },
    };
    try testing.expectEqualSlices(Hunk, &hunks, ch.hunks);
    try testing.expectStringStartsWith(ch.ghost_text, "const one = 1;\n");
    // Bare: not shown in this view; what jj said is kept on the pane.
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(0, pane.layers.lanes);
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    // Bare again: the pane's, shown again (jj not asked).
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(levels, pane.layers.lanes);
    try testing.expectEqual(ch, answered(p, pane.serial).?);
    // jj's refusal, in its words; what was shown stays.
    p.update(.{ .command = "Changes nosuch" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: Revision `nosuch` doesn't exist") != null);
    try testing.expectEqualStrings("@--::@-", answered(p, pane.serial).?.pinned());
    // `@`, the working copy's change, which (never snapshotted) touches nothing.
    p.update(.{ .command = "Changes @" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null);
}

test "the layer is the pane's: Changes in one view shows its lines in every view of the pane, another revset there replaces them in all, and a bare Changes in any hides them in all, the text the file's again" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    const before = File.gutterWidth(pane);
    const other = p.openView().?;
    p.update(.{ .command = "Changes @--::@-" });
    try testing.expectEqual(before + levels, File.gutterWidth(pane));
    const shown = try gpa.dupe(u8, pane.file.?.content);
    defer gpa.free(shown);
    try testing.expect(pane.file.?.layer.lines.len > 0);
    // Shown in the other view too, its lines the same.
    p.toView(other);
    try testing.expectEqual(levels, pane.layers.lanes);
    try testing.expectEqual(before + levels, File.gutterWidth(pane));
    try testing.expectEqualStrings(shown, pane.file.?.content);
    p.update(.{ .command = "Changes @-" });
    try testing.expectEqualStrings("@-", answered(p, pane.serial).?.pinned());
    try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len);
    p.toView(.at(0));
    try testing.expectEqual(levels, pane.layers.lanes);
    // Hidden from the other view: hidden in both, the buffer the file's.
    p.toView(other);
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(0, pane.layers.lanes);
    p.toView(.at(0));
    try testing.expectEqual(0, pane.layers.lanes);
    try testing.expectEqual(before, File.gutterWidth(pane));
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    try testing.expectEqual(@as(usize, 0), pane.file.?.layer.lines.len);
}

test "a client replays Changes from what the session's jj answered and ends equal" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const R = pardes.replica;
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes @--::@-" }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    try testing.expectEqual(@as(usize, 2), answered(a.core, a.core.panes[id].?.serial).?.pins.len);
    try testing.expectEqualSlices(Line, answered(a.core, a.core.panes[id].?.serial).?.lines, answered(r.core(), r.core().panes[id].?.serial).?.lines);
    try testing.expectEqualStrings("@--::@-", answered(r.core(), r.core().panes[id].?.serial).?.pinned());
    try testing.expect(r.core().panes[id].?.layers.lanes > 0);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
    // Its pins and lanes cross a join whole (replica.zig `hand_walked`).
    try R.loadsAsSession(a, 2);
}

/// A session whose `Changes` runs on a worker (Stream.start), as a shell's
/// does, its answer posted to an inbox, with a client of it.
const WorkerJj = struct {
    const Inbox = @import("dev").host_io.Inbox;
    const R = pardes.replica;
    /// The host's: where its worker posts, and the core it starts for.
    const Shell = struct { q: Inbox, core: ?*Pardes = null };
    shell: *Shell,
    a: *R.Authority,
    r: *R.Replica,
    /// The repository's `a.zig` open (`at`: `@@-`, its revision `@-`).
    id: usize,
    serial: u32,

    fn search(ctx: ?*anyopaque, gen: u32) void {
        const shell: *Shell = @ptrCast(@alignCast(ctx.?));
        pardes.Stream.start(testing.io, testing.allocator, shell.core.?, gen, &shell.q, Inbox.pushSearch);
    }
    const vtable: pardes.Host.VTable = .{ .search = search };

    fn init(repo: *const Repo, at: []const u8) !WorkerJj {
        const shell = try testing.allocator.create(Shell);
        shell.* = .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } };
        const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell });
        errdefer a.deinit();
        shell.core = a.core;
        const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
        var line: [4200]u8 = undefined;
        r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}{s}", .{ repo.file, at }) }));
        const id = a.core.view().active;
        return .{ .shell = shell, .a = a, .r = r, .id = id, .serial = a.core.panes[id].?.serial };
    }

    fn deinit(w: *WorkerJj) void {
        w.r.deinit();
        w.a.deinit();
        w.shell.q.deinit();
        testing.allocator.destroy(w.shell);
    }

    fn word(w: *WorkerJj, text: []const u8) !void {
        w.r.confirm(try w.a.local(.{ .command = text }));
        w.r.settle();
    }

    /// Until no `Changes` is asked or running (five seconds at most): each
    /// answer the session's input, as its loop hands it, and the client's.
    fn land(w: *WorkerJj) !void {
        var waited: u32 = 0;
        while (w.a.core.changes.task != null or w.a.core.changes.next != null or w.a.core.stream.parse != null) : (waited += 1) {
            if (waited == 5000) return error.Timeout;
            var batch: Inbox.Batch = .{};
            w.shell.q.takeInto(&batch);
            for (batch.slice()) |m| switch (m) {
                .search => |b| {
                    defer b.deinit(testing.allocator);
                    w.r.confirm(try w.a.local(.{ .search = b }));
                    w.r.settle();
                },
                else => m.deinit(testing.allocator, testing.allocator),
            };
            testing.io.sleep(.fromMilliseconds(1), .awake) catch {};
        }
        try testing.expect(w.r.diverged == null);
        try testing.expectEqual(pardes.tape.digestOf(w.a.core), pardes.tape.digestOf(w.r.core()));
    }
};

test "Changes asks jj on a worker: the word says so and returns, its answer lands as one input and pins; a client replays that input and ends equal" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "@@-");
    defer w.deinit();
    try w.word("Changes @--::@-");
    // Asked, not answered: the word did not wait for jj.
    try testing.expect(answered(w.a.core, w.serial) == null);
    try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Changes: jj") != null);
    try w.land();
    try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len);
    try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines);
}

test "a second Changes before the first's answer: only the second's pins" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "@@-");
    defer w.deinit();
    try w.word("Changes @--::@-");
    try w.word("Changes @-");
    try w.land();
    const ch = answered(w.a.core, w.serial).?;
    try testing.expectEqualStrings("@-", ch.pinned());
    try testing.expectEqual(@as(usize, 1), ch.pins.len);
}

test "the pane closed before its Changes answer: nothing pinned, nothing kept" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "@@-");
    defer w.deinit();
    try w.word("Changes @--::@-");
    try w.word("Del");
    try testing.expect(w.a.core.panes[w.id] == null or w.a.core.panes[w.id].?.serial != w.serial);
    try w.land();
    try testing.expectEqual(@as(usize, 0), w.a.core.changes.answers.items.len);
}

test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" {
    const gpa = testing.allocator;
    // `fn` wrote the function; `mid` rewrote its lines 3-4 as 3-6 (two
    // changed, two added whole); `shift` rewrote line 4 again.
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    g();\n    h();\n    i();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    b2();\n    c2();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    const shift_text = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        // Tall enough that every line is in view however long the test's
        // directory makes the tag.
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40, .windowed = windowed });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        const before = File.gutterWidth(pane);
        p.update(.{ .command = "Changes ::@" });
        try testing.expectEqual(@as(usize, 3), answered(p, pane.serial).?.pins.len);
        const cells: u16 = if (windowed) 2 else levels;
        try testing.expectEqual(before + cells, File.gutterWidth(pane));
        p.sync();
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const first = body.x + before;
        const c = p.chrome();
        const colours = c.lanes[0..c.lanes_len];
        try testing.expect(colours.len >= 3);
        const ground = c.add.row;
        // Lines 1-10, each on the row the view draws it at (ghost rows
        // stand between): `fn`'s spine on all; `mid` on 3-6; `shift` on 4.
        const want = [_][]const u8{ "0", "0", "01", "012", "01", "01", "0", "0", "0", "0" };
        for (want, 0..) |lanes, row| {
            const y = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, @intCast(File.bufferRow(&pane.file.?, row)), 0).row));
            if (windowed) {
                var n: usize = 0;
                for (s.lanes.items) |lane| if (lane.y == y) {
                    try testing.expectEqual(first, lane.x);
                    try testing.expectEqual(lanes[lane.level] - '0', lane.level);
                    try testing.expectEqual(colours[lane.level], lane.rgb);
                    n += 1;
                };
                try testing.expectEqual(lanes.len, n);
            } else for (0..levels) |level| {
                const cell = s.at(first + @as(u16, @intCast(level)), y);
                if (level < lanes.len) {
                    try testing.expectEqualStrings("\u{258e}", cell.grapheme());
                    try testing.expectEqual(pardes.Color{ .rgb = colours[level] }, cell.style.fg);
                } else if (!cell.default and !std.mem.eql(u8, cell.grapheme(), " ")) {
                    std.debug.print("row {d} level {d}: [{s}] {any}\n", .{ row, level, cell.grapheme(), cell.style });
                    return error.TestUnexpectedResult;
                }
            }
            // `fn`'s lines it still has (1, 2, 7-10) and `mid`'s x() and
            // y() (5, 6) were added whole; b2 (3) and c3 (4) changed one.
            const whole = row != 2 and row != 3;
            const text_cell = s.at(body.x + File.gutterWidth(pane) + 1, y);
            try testing.expectEqual(whole, std.meta.eql(text_cell.style.bg, pardes.Color{ .rgb = ground }));
        }
        if (!windowed) try testing.expectEqual(@as(usize, 0), s.lanes.items.len);
        p.update(.{ .command = "Changes" });
        try testing.expectEqual(before, File.gutterWidth(pane));
    }
}

test "a diff's two lane inks in every theme are its added and deleted markers (DESIGN.md R10): never one colour, each 4.5:1 on its rows, as near as the theme reaches" {
    for (&pardes.colors.themes) |*th| {
        const c: pardes.colors.Chrome = .of(th);
        errdefer std.debug.print("{s}: added {any} deleted {any}\n", .{ th.name, c.add, c.del });
        try testing.expect(!std.meta.eql(c.add.ink, c.del.ink));
        for ([2]pardes.colors.Chrome.Diff{ c.add, c.del }) |d| for ([2][3]u8{ d.row, d.emph }) |ground| {
            const reach = @max(pardes.colors.contrast(@splat(255), ground), pardes.colors.contrast(@splat(0), ground));
            try testing.expect(pardes.colors.contrast(d.ink, ground) >= @min(4.5, reach) - 0.01);
        };
    }
}

/// A function `fn` wrote, two of its lines `cut` took away whole, and one
/// `mid` rewrote as two (one changed, one added whole).
const Ghosts = struct {
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    d();\n    e();\n}\n";
    const cut_text = "fn f() void {\n    a();\n    b();\n    e();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    b2();\n    x();\n    e();\n}\n";

    fn repo() !?Repo {
        return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ cut_text, "cut" }, .{ mid_text, "mid" } }, null);
    }

    /// The body's rows as this view shows them, whole.
    fn rows(p: *Pardes, pane: *Pane, arena: std.mem.Allocator, out: [][]const u8) ![]const []const u8 {
        var it = std.mem.splitScalar(u8, try File.bodyText(p.settings.tab, arena, pane, &pane.file.?), '\n');
        var n: usize = 0;
        while (it.next()) |row| : (n += 1) out[n] = row;
        return out[0..n];
    }

    /// Each row's text after the gutter, and its number (blank: none).
    fn text(pane: *const Pane, row: []const u8) []const u8 {
        return row[@min(row.len, File.gutterWidth(pane))..];
    }
    fn number(pane: *const Pane, row: []const u8) []const u8 {
        return std.mem.trim(u8, row[0..@min(row.len, File.gutterWidth(pane))], " ");
    }

    /// The rows a `Changes ::@` shows: `said` each pin's description;
    /// `b();` the old text of the line `mid` changed, right above it.
    fn want(said: [3][]const u8) [12][]const u8 {
        return .{ "fn f() void {", "    a();", "    b();", "    b2();", "    x();", said[2], "    c();", "    d();", said[1], "    e();", "}", said[0] };
    }
};

fn saidOf(arena: std.mem.Allocator, ch: *const Changes) ![3][]const u8 {
    var said: [3][]const u8 = undefined;
    for (&said, ch.pins, [_][]const u8{ "fn", "cut", "mid" }) |*d, pin, title| d.* = try std.fmt.allocPrint(arena, "{s} {s} t now", .{ pin.id[0..4], title });
    return said;
}

test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour, its lane an arrow to it; no number, their lanes; one change pinned, its lane green beside what it wrote and red beside what it took away; the lines below moved down in every view of the pane: the layer is the pane's" {
    const gpa = testing.allocator;
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed });
        defer p.deinit();
        // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
        p.settings.jumps = .@"new-pane";
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        const other = p.openView().?;
        p.update(.{ .command = "Changes ::@" });
        const ch = answered(p, pane.serial).?;
        try testing.expectEqual(@as(usize, 3), ch.pins.len);
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const said = try saidOf(arena.allocator(), ch);
        var buf: [64][]const u8 = undefined;
        const got = try Ghosts.rows(p, pane, arena.allocator(), &buf);
        const want = Ghosts.want(said);
        const numbers = [_][]const u8{ "1", "2", "", "3", "4", "", "", "", "", "5", "6", "" };
        for (want, numbers, got[0..want.len]) |w, n, row| {
            try testing.expectEqualStrings(w, Ghosts.text(pane, row));
            try testing.expectEqualStrings(n, Ghosts.number(pane, row));
        }
        // Drawn: each row's lanes (pins by level), its ground, a ghost's ink.
        p.sync();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const first = body.x + File.gutterWidth(pane) - File.laneCells(pane);
        const grounds = p.chrome();
        const colours = grounds.lanes[0..grounds.lanes_len];
        const lanes = [_][]const u8{ "0", "0", "02", "02", "02", "02", "01", "01", "01", "0", "0", "0" };
        const Ground = enum { none, add, del };
        const ground = [_]Ground{ .add, .add, .none, .none, .add, .none, .del, .del, .none, .add, .add, .none };
        // On a description row the level its change's arrow leaves from.
        const arrows = [_]?usize{ null, null, null, null, null, 1, null, null, 1, null, null, 0 };
        for (lanes, ground, arrows, 0..) |pins, gr, arrow, row| {
            const y = body.y + @as(u16, @intCast(row));
            if (windowed) {
                var n: usize = 0;
                for (s.lanes.items) |lane| if (lane.y == y) {
                    try testing.expect(lane.level < pins.len);
                    try testing.expectEqual(colours[pins[lane.level] - '0'], lane.rgb);
                    try testing.expectEqual(@as(u8, if (arrow == lane.level) @intCast(File.laneCells(pane)) else 0), lane.arrow);
                    n += 1;
                };
                try testing.expectEqual(pins.len, n);
            } else for (0..levels) |level| {
                // `▎` a lane; an arrow: its lane bent, a shaft, a head (`╰─→`).
                const cell = s.at(first + @as(u16, @intCast(level)), y);
                const bent = arrow != null and arrow.? == level;
                const glyph = if (level < pins.len) (if (!bent) "\u{258e}" else if (level + 1 == levels) "\u{21b3}" else "\u{2570}") else if (arrow == null) " " else if (level + 1 == levels) "\u{2192}" else "\u{2500}";
                try testing.expectEqualStrings(glyph, cell.grapheme());
                const pin = if (level < pins.len) pins[level] - '0' else pins[arrow orelse 0] - '0';
                if (!std.mem.eql(u8, glyph, " ")) try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, cell.style.fg);
            }
            const cell = s.at(body.x + File.gutterWidth(pane) + 1, y);
            const bg: ?[3]u8 = switch (gr) {
                .none => null,
                .add => grounds.add.row,
                .del => grounds.del.row,
            };
            if (bg) |rgb| try testing.expectEqual(pardes.Color{ .rgb = rgb }, cell.style.bg) else {
                try testing.expect(!std.meta.eql(cell.style.bg, pardes.Color{ .rgb = grounds.add.row }));
                try testing.expect(!std.meta.eql(cell.style.bg, pardes.Color{ .rgb = grounds.del.row }));
            }
        }
        // A description's id and title in its lane's colour; a line taken
        // away in the numbers' grey.
        for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| {
            try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane), body.y + row).style.fg);
            try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane) + 5, body.y + row).style.fg);
        }
        try testing.expectEqual(pardes.Color{ .rgb = grounds.line_number }, s.at(body.x + File.gutterWidth(pane) + 4, body.y + 6).style.fg);
        // The changed line: on its old text the word that went (`b`) red,
        // on it the word that came (`b2`) green; the rest of each neither.
        const text_x = body.x + File.gutterWidth(pane);
        for ([_]u16{ 4, 5 }, [_]bool{ true, false }) |col, went| try testing.expectEqual(went, std.meta.eql(s.at(text_x + col, body.y + 2).style.bg, pardes.Color{ .rgb = grounds.del.emph }));
        for ([_]u16{ 4, 5, 6 }, [_]bool{ true, true, false }) |col, came| try testing.expectEqual(came, std.meta.eql(s.at(text_x + col, body.y + 3).style.bg, pardes.Color{ .rgb = grounds.add.emph }));
        // The layer is the pane's (its lines are its buffer's): the other
        // view shows the same lines.
        p.toView(other);
        try testing.expect(pane.layers.lanes > 0);
        const there = try Ghosts.rows(p, pane, arena.allocator(), &buf);
        for (want, there[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row));
        p.toView(.at(0));
        // One change pinned, mid: a diff. Its rows `b();` (its old text),
        // `b2();`, `x();`, its description: the lane red beside the first,
        // green beside the lines, green into its arrow; its id the
        // keyword's ink, its title the text's.
        var one: [64]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&one, "Changes {s}", .{ch.pins[2].id}) });
        p.sync();
        const s1 = try p.render(arena.allocator());
        const top = s1.region(.body, id).?.rect.y;
        const at = body.x + File.gutterWidth(pane) - File.laneCells(pane);
        try testing.expect(!std.meta.eql(grounds.add.ink, grounds.del.ink));
        for ([_]u16{ 2, 3, 4, 5 }, [_]bool{ true, false, false, false }) |row, red| {
            const ink = if (red) grounds.del.ink else grounds.add.ink;
            if (windowed) {
                var n: usize = 0;
                for (s1.lanes.items) |lane| if (lane.y == top + row) {
                    try testing.expectEqual(ink, lane.rgb);
                    n += 1;
                };
                try testing.expectEqual(@as(usize, 1), n);
            } else try testing.expectEqual(pardes.Color{ .rgb = ink }, s1.at(at, top + row).style.fg);
        }
        const keyword = grounds.syntax[@intFromEnum(syntax.Syn.keyword)];
        try testing.expectEqual(pardes.Color{ .rgb = keyword }, s1.at(text_x, top + 5).style.fg);
        try testing.expect(!std.meta.eql(pardes.Color{ .rgb = keyword }, s1.at(text_x + 5, top + 5).style.fg));
    }
}

test "]g and [g go from change to change, to each one's first line, a layer's line among them; a Look on a word of a layer's line is a Look of that word as anywhere" {
    const gpa = testing.allocator;
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    p.update(.{ .command = "Changes ::@" });
    // The lines (Ghosts.want): fn's first two, mid's from the old text of
    // the line it changed (2), cut's two lines taken away (6), fn's again
    // after cut's description (9).
    Lines.at(pane, 0, 0);
    for ([_]i32{ 2, 6, 9, 9 }) |want| {
        Lines.send(p, "]g");
        try testing.expectEqual(want, pane.body.cur_row);
    }
    for ([_]i32{ 6, 2, 0 }) |want| {
        Lines.send(p, "[g");
        try testing.expectEqual(want, pane.body.cur_row);
    }
    // A Look (B3) on `c();`, a line cut took away: a Look of `c`, as
    // `Look c` typed in the pane; no file at a revision opens.
    p.sync();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const body = s.region(.body, id).?.rect;
    Lines.click(p, .right, body.x + File.gutterWidth(pane) + 4, body.y + 6);
    try testing.expectEqual(id, p.view().active);
    for (p.panes) |slot| if (slot) |q| if (q.file) |*f| try testing.expect(of(f) == null);
    const clicked: [2]i32 = .{ pane.body.cur_row, pane.body.cur_col };
    Lines.at(pane, 0, 0);
    look.lookAt(p, id, "c");
    try testing.expectEqual(clicked, [2]i32{ pane.body.cur_row, pane.body.cur_col });
}

test "a Look on a change's id opens its patch, its header and whole message at the top: on a description row, at the row of that change's last line in this file; in any text, at the top; a word that names no change is looked as any word" {
    const gpa = testing.allocator;
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = windowed });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        p.update(.{ .command = "Changes ::@" });
        const ch = answered(p, pane.serial).?;
        const mid = ch.pins[2].id;
        p.sync();
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        // mid's description (row 5): a B3 on its id.
        const x = body.x + File.gutterWidth(pane) + 1;
        p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 5 } });
        p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 5 } });
        const hid = p.view().active;
        try testing.expect(hid != id);
        const patch = p.panes[hid].?;
        const f = &patch.file.?;
        try testing.expectStringStartsWith(f.path, try std.fmt.allocPrint(arena.allocator(), "{s}/+Diff-", .{repo.dir}));
        // jj show's header, the whole message, above the hunks.
        var rows = std.mem.splitScalar(u8, f.content, '\n');
        try testing.expectStringStartsWith(rows.next().?, "Commit ID: ");
        try testing.expectStringStartsWith(rows.next().?, try std.fmt.allocPrint(arena.allocator(), "Change ID: {s}", .{mid}));
        try testing.expectStringStartsWith(rows.next().?, "Author   : t <t@t>");
        try testing.expect(std.mem.indexOf(u8, f.content, "\n    mid\n") != null);
        // The cursor on mid's last line in a.zig, `x();` (its line 4).
        try testing.expectEqualStrings("a.zig:4", try std.fmt.allocPrint(arena.allocator(), "{s}:{d}", .{ std.Io.Dir.path.basename(f.location_rows[@intCast(patch.body.cur_row)].path), f.location_rows[@intCast(patch.body.cur_row)].at.line }));
        // The same, typed: one pane a change, the cursor moved there.
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:2", .{mid}) });
        try testing.expectEqual(hid, p.view().active);
        try testing.expectEqual(@as(usize, 2), f.location_rows[@intCast(patch.body.cur_row)].at.line);
        // In running text: the patch at its top.
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{ch.pins[1].id}) });
        const cut = p.panes[p.view().active].?;
        try testing.expectStringStartsWith(cut.file.?.content, "Commit ID: ");
        try testing.expect(std.mem.indexOf(u8, cut.file.?.content, "\n    cut\n") != null);
        try testing.expectEqual(@as(i32, 0), cut.body.cur_row);
        // A word of k to z that names no change: no patch.
        const patches = struct {
            fn count(q: *Pardes) usize {
                var n: usize = 0;
                for (q.panes) |slot| if (slot) |o| if (o.file) |*of_| {
                    n += @intFromBool(std.mem.indexOf(u8, of_.path, "+Diff-") != null);
                };
                return n;
            }
        }.count;
        const before = patches(p);
        p.update(.{ .command = "Look zzzzzzzz" });
        try testing.expectEqual(before, patches(p));
    }
}

test "Diff with a revision jj takes (`@-`, a bookmark) and no file of that name: the revision's patch, its commit's ids, author, date and whole message at its top; a word that names neither is still no such file" {
    const gpa = testing.allocator;
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    if (!try Repo.run(gpa, repo.dir, &.{ "bookmark", "create", "-r", "@--", "cutmark" })) return error.SkipZigTest;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    for ([_]struct { []const u8, []const u8 }{ .{ "@-", "\n    mid\n" }, .{ "cutmark", "\n    cut\n" } }) |case| {
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const from = p.view().active;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s}", .{case[0]}) });
        const shown = p.panes[p.view().active].?;
        try testing.expect(p.view().active != from);
        try testing.expectStringStartsWith(shown.file.?.content, "Commit ID: ");
        try testing.expect(std.mem.indexOf(u8, shown.file.?.content, "\nAuthor   : t <t@t>") != null);
        try testing.expect(std.mem.indexOf(u8, shown.file.?.content, case[1]) != null);
        try testing.expect(std.mem.indexOf(u8, shown.file.?.content, "a.zig") != null);
    }
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    p.update(.{ .command = "Diff nosuchword" });
    try testing.expectEqual(id, p.view().active);
    try testing.expect(std.mem.indexOf(u8, told(p, id), "nosuchword") != null);
}

test "ghost rows ride with the text: a line deleted above moves them up, a line they stood before deleted puts them before the next; a client replays it equal" {
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes ::@" }));
    r.settle();
    const serial = a.core.panes[a.core.view().active].?.serial;
    const ats = struct {
        fn of(ch: *const Changes, out: []u32) []u32 {
            for (ch.ghosts, out[0..ch.ghosts.len]) |g, *o| o.* = g.at;
            return out[0..ch.ghosts.len];
        }
    }.of;
    var got: [8]u32 = undefined;
    // mid's description, cut's two lines and its description before `e();`
    // (line 5), fn's after the last.
    try testing.expectEqualSlices(u32, &.{ 2, 4, 4, 4, 4, 6 }, ats(answered(a.core, serial).?, &got));
    // `a();` deleted: each one a line up.
    r.confirm(try a.local(.{ .command = "Look a.zig:2" }));
    for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    r.settle();
    try testing.expectEqualSlices(u32, &.{ 1, 3, 3, 3, 3, 5 }, ats(answered(a.core, serial).?, &got));
    // `e();`, the line they stood before, deleted: they stand before `}`.
    r.confirm(try a.local(.{ .command = "Look a.zig:4" }));
    for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    r.settle();
    try testing.expectEqualStrings("fn f() void {\n    b2();\n    x();\n}\n", try File.fileText(&a.core.panes[a.core.view().active].?.file.?, a.core.scratch.allocator()));
    try testing.expectEqualSlices(u32, &.{ 1, 3, 3, 3, 3, 4 }, ats(answered(a.core, serial).?, &got));
    try testing.expect(r.diverged == null);
    try testing.expectEqualSlices(Ghost, answered(a.core, serial).?.ghosts, answered(r.core(), serial).?.ghosts);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "a description is whole, its title and its author never cut: in a pane narrower than it, it wraps as any line does, its author and age at the end of its last row; its lane ends on its first row in the arrow, its rows after carry the lane's cells blank" {
    const gpa = testing.allocator;
    const title = "a title long enough that no narrow pane holds the whole of it beside its author and its age";
    var repo = try Repo.with(gpa, &.{.{ "fn f() void {\n    a();\n}\n", title }}, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 50, .rows = 20, .windowed = windowed });
        defer p.deinit();
        // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
        p.settings.jumps = .@"new-pane";
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        p.update(.{ .command = "Changes ::@" });
        const ch = answered(p, pane.serial).?;
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const said = try std.fmt.allocPrint(arena.allocator(), "{s} {s} t now", .{ ch.pins[0].id[0..4], title });
        try testing.expectEqualStrings(said, File.sourceLine(pane, 3));
        // Its rows from the fourth, each within the room, put back together:
        // the whole of it.
        var buf: [64][]const u8 = undefined;
        const got = try Ghosts.rows(p, pane, arena.allocator(), &buf);
        const room = pane.cols - File.gutterWidth(pane) - 1;
        var whole: std.ArrayList(u8) = .empty;
        var n: usize = 0;
        while (whole.items.len < said.len) : (n += 1) {
            const row = Ghosts.text(pane, got[3 + n]);
            try testing.expect(File.displayWidth(p.settings.tab, row) <= room);
            try whole.appendSlice(arena.allocator(), row);
        }
        try testing.expectEqualStrings(said, whole.items);
        try testing.expect(n >= 3);
        try testing.expectStringEndsWith(Ghosts.text(pane, got[3 + n - 1]), " t now");
        // Drawn: the id in the keyword's ink on its first row, the author and
        // the age grey at the end of its last; the arrow on the first row,
        // the rows after it no lane.
        p.sync();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const x = body.x + File.gutterWidth(pane);
        try testing.expectEqual(pardes.Color{ .rgb = p.chrome().syntax[@intFromEnum(syntax.Syn.keyword)] }, s.at(x, body.y + 3).style.fg);
        const last: u16 = body.y + 3 + @as(u16, @intCast(n - 1));
        const end = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, Ghosts.text(pane, got[3 + n - 1])))) - 1;
        try testing.expectEqualStrings("w", s.at(end, last).grapheme());
        try testing.expectEqual(pardes.Color{ .rgb = p.chrome().line_number }, s.at(end, last).style.fg);
        try testing.expectEqual(pardes.Color{ .rgb = p.chrome().line_number }, s.at(end - 4, last).style.fg);
        const first = x - File.laneCells(pane);
        for (0..n) |k| {
            const y = body.y + 3 + @as(u16, @intCast(k));
            if (windowed) {
                var lanes: usize = 0;
                for (s.lanes.items) |lane| if (lane.y == y) {
                    lanes += 1;
                    try testing.expectEqual(@as(u8, if (k == 0) @intCast(File.laneCells(pane)) else 0), lane.arrow);
                };
                try testing.expectEqual(@as(usize, @intFromBool(k == 0)), lanes);
            } else for (0..levels) |level| {
                const glyph = if (k > 0) " " else if (level == 0) "\u{2570}" else if (level + 1 == levels) "\u{2192}" else "\u{2500}";
                try testing.expectEqualStrings(glyph, s.at(first + @as(u16, @intCast(level)), y).grapheme());
            }
        }
    }
}

/// 60 numbered lines, line 20 of 130 numbered words (12 rows or more at
/// 60 columns), and a change to line 40 whose title wraps over several
/// rows: the rows a view scrolls through, the layer's description among
/// them.
const Tall = struct {
    const title = "a title long enough to wrap: the description of this change says what it does and why at some length, " ++
        "and then says it again in other words, and once more, so that no pane of sixty columns holds it in fewer than four rows " ++
        "beside its author and its age";

    fn repo(gpa: std.mem.Allocator) !?Repo {
        var base: std.ArrayList(u8) = .empty;
        defer base.deinit(gpa);
        var changed: std.ArrayList(u8) = .empty;
        defer changed.deinit(gpa);
        for (0..60) |i| {
            const from = base.items.len;
            if (i == 20) {
                for (0..130) |w| try base.print(gpa, "t{d:0>3} ", .{w});
                try base.append(gpa, '\n');
            } else try base.print(gpa, "line {d:0>2}\n", .{i});
            try changed.appendSlice(gpa, if (i == 40) "line 40 changed\n" else base.items[from..]);
        }
        return Repo.with(gpa, &.{ .{ base.items, "base" }, .{ changed.items, title } }, null);
    }

    /// The buffer's line the description is.
    fn description(f: *const File.State) !usize {
        for (f.layer.lines) |l| if (std.mem.indexOf(u8, f.content[l.at..][0..l.len], title[0..20]) != null)
            return std.mem.count(u8, f.content[0..l.at], "\n");
        return error.NoDescription;
    }

    /// The rows of the text above line `line`'s row that shows its byte
    /// `col`, in `pane`'s view.
    fn rowsAbove(tab: u16, pane: *Pane, line: usize, col: usize) usize {
        var n: usize = File.rowOf(tab, pane, line, col);
        for (0..line) |l| n += File.lineRows(tab, pane, l);
        return n;
    }
};

test "a view scrolls by rows through a line wrapped over 12 rows and a change's description wrapped over several (a line of the layer): a wheel's notch is one row down the whole text and back, PageDown and PageUp a page of rows, zj and zk one; a held j and k keep the cursor's row three rows inside the body" {
    const gpa = testing.allocator;
    var repo = try Tall.repo(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    const tab = p.settings.tab;
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    p.update(.{ .command = "Changes @-" });
    p.sync();
    const f = &pane.file.?;
    try testing.expect(File.lineRows(tab, pane, 20) >= 12);
    try testing.expect(File.lineRows(tab, pane, try Tall.description(f)) >= 4);
    var total: usize = 0;
    for (0..File.nlines(gpa, f)) |l| total += File.lineRows(tab, pane, l);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const shot = struct {
        fn of(q: *Pardes, w: *Pane, a: std.mem.Allocator) ![]const []const u8 {
            return Ghosts.rows(q, w, a, try a.alloc([]const u8, 256));
        }
    }.of;
    const rect = p.view().rects[id];
    const at = .{ .col = rect.x + 10, .row = p.bodyTop(pane, rect) + 5 };
    const notch = struct {
        fn of(down: bool, x: u16, y: u16) pardes.Event {
            return .{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = x, .row = y } };
        }
    }.of;
    // Every row of the text at the body's top in turn, a notch each: the
    // body's rows one up.
    var was = try shot(p, pane, arena.allocator());
    const kept = was.len - 1;
    var all: std.ArrayList([]const u8) = .empty;
    try all.append(arena.allocator(), was[0]);
    while (true) {
        p.update(notch(true, at.col, at.row));
        const now = try shot(p, pane, arena.allocator());
        if (std.mem.eql(u8, now[0], was[0])) break;
        for (now[0 .. kept - 1], was[1..kept]) |n, w| try testing.expectEqualStrings(w, n);
        try all.append(arena.allocator(), now[0]);
        was = now;
    }
    try testing.expectEqual(total, all.items.len);
    // And back up, a row a notch.
    var back = all.items.len - 1;
    while (back > 0) : (back -= 1) {
        p.update(notch(false, at.col, at.row));
        const now = try shot(p, pane, arena.allocator());
        try testing.expectEqualStrings(all.items[back - 1], now[0]);
        for (now[1..kept], was[0 .. kept - 1]) |n, w| try testing.expectEqualStrings(w, n);
        was = now;
    }
    const indexOf = struct {
        fn in(rows: []const []const u8, row: []const u8) usize {
            for (rows, 0..) |r, i| if (std.mem.eql(u8, r, row)) return i;
            return rows.len;
        }
    }.in;
    // PageDown and PageUp: a page of rows each, the text's last row at the
    // top the furthest.
    var top: usize = 0;
    while (top < all.items.len - 1) {
        p.update(.{ .key = .{ .cp = pardes.Key.page_down } });
        top = @min(top + pane.rows, all.items.len - 1);
        try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
    }
    while (top > 0) {
        p.update(.{ .key = .{ .cp = pardes.Key.page_up } });
        top -|= pane.rows;
        try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
    }
    // zj and zk: a row each, through line 20's rows and the description's.
    for (0..all.items.len - 1) |n| {
        for ("zj") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
        try testing.expectEqual(n + 1, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
    }
    for (0..all.items.len - 1) |n| {
        for ("zk") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
        try testing.expectEqual(all.items.len - 2 - n, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
    }
    // A held j from the first line to the last and a held k back: the
    // cursor's row three rows (`scroll_off`) inside the body's edges, or
    // as far as the text before or after it goes.
    p.update(.{ .command = "Look a.zig:1" });
    const body = File.shownRows(tab, pane);
    for ("jk") |cp| for (0..total) |_| {
        p.update(.{ .key = .{ .cp = cp, .text = &[_]u8{cp} } });
        const t = File.top(tab, pane);
        const cur = Tall.rowsAbove(tab, pane, @intCast(pane.body.cur_row), @intCast(pane.body.cur_col));
        const on = cur - Tall.rowsAbove(tab, pane, t.line, 0) - t.row;
        try testing.expect(on >= @min(pardes.config.scroll_off, cur));
        try testing.expect(on <= body - 1 - @min(pardes.config.scroll_off, total - 1 - cur));
    };
}

test "a client wheels its session's view a row a notch into a change's description wrapped over several rows (a line of the layer), agreeing with the session at every notch; a client joined over that view loads its row" {
    var repo = try Tall.repo(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 60, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes @-" }));
    r.settle();
    const id = a.core.view().active;
    const af = &a.core.panes[id].?.file.?;
    const desc = try Tall.description(af);
    const rect = a.core.view().rects[id];
    const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } };
    var n: usize = 0;
    while (af.scroll != desc or af.scroll_row != 2) : (n += 1) {
        if (n > 300) return error.NeverThere;
        const m = try testing.allocator.dupe(u8, try r.input(notch));
        defer testing.allocator.free(m);
        r.confirm(try a.take(m));
        r.settle();
        try testing.expect(r.diverged == null);
        try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
        const rf = &r.core().panes[id].?.file.?;
        try testing.expectEqual(af.scroll, rf.scroll);
        try testing.expectEqual(af.scroll_row, rf.scroll_row);
    }
    try R.loadsAsSession(a, 2);
}

test "at one place a change's ghost rows come before its description: a line it changed and the next it took away, then its description" {
    const gpa = testing.allocator;
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    d();\n}\n";
    const chg_text = "fn f() void {\n    a();\n    b2();\n    d();\n}\n";
    var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ chg_text, "chg" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
    p.settings.jumps = .@"new-pane";
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    p.update(.{ .command = "Changes ::@" });
    const ch = answered(p, pane.serial).?;
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const said = [2][]const u8{ try std.fmt.allocPrint(arena.allocator(), "{s} fn t now", .{ch.pins[0].id[0..4]}), try std.fmt.allocPrint(arena.allocator(), "{s} chg t now", .{ch.pins[1].id[0..4]}) };
    var buf: [64][]const u8 = undefined;
    const got = try Ghosts.rows(p, pane, arena.allocator(), &buf);
    const want = [_][]const u8{ "fn f() void {", "    a();", "    b();", "    b2();", "    c();", said[1], "    d();", "}", said[0] };
    for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row));
}

test "a change the revset does not pin, between two it does, moves the older one's ghost rows to where they stand: jj's answer has its hunks" {
    const gpa = testing.allocator;
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    d();\n}\n";
    // `old` takes `c();` away; `mid` (not pinned) writes two lines above
    // it; `last` changes `d();`.
    const old_text = "fn f() void {\n    a();\n    b();\n    d();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    x();\n    y();\n    b();\n    d();\n}\n";
    const last_text = "fn f() void {\n    a();\n    x();\n    y();\n    b();\n    d2();\n}\n";
    var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ old_text, "old" }, .{ mid_text, "mid" }, .{ last_text, "last" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
    p.settings.jumps = .@"new-pane";
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    p.update(.{ .command = "Changes @--- | @-" });
    const ch = answered(p, pane.serial).?;
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const said = [2][]const u8{ try std.fmt.allocPrint(arena.allocator(), "{s} old t now", .{ch.pins[0].id[0..4]}), try std.fmt.allocPrint(arena.allocator(), "{s} last t now", .{ch.pins[1].id[0..4]}) };
    var buf: [64][]const u8 = undefined;
    const got = try Ghosts.rows(p, pane, arena.allocator(), &buf);
    const want = [_][]const u8{ "fn f() void {", "    a();", "    x();", "    y();", "    b();", "    c();", said[0], "    d();", "    d2();", said[1], "}" };
    for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row));
}

test "lines typed between the word and jj's answer: the ghost rows stand where they stood, carried across them" {
    var repo = try Ghosts.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "");
    defer w.deinit();
    try w.word("Changes ::@");
    try testing.expect(answered(w.a.core, w.serial) == null);
    // A line opened above `a();` before the answer lands.
    try w.word("Look a.zig:2");
    for ("Oz();") |k| w.r.confirm(try w.a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    w.r.confirm(try w.a.local(.{ .key = .{ .cp = pardes.Key.escape } }));
    try w.land();
    try testing.expectStringStartsWith(w.a.core.panes[w.id].?.file.?.content, "fn f() void {\n    z();\n    a();\n");
    var got: [8]u32 = undefined;
    const ch = answered(w.a.core, w.serial).?;
    for (ch.ghosts, got[0..ch.ghosts.len]) |g, *o| o.* = g.at;
    try testing.expectEqualSlices(u32, &.{ 3, 5, 5, 5, 5, 7 }, got[0..ch.ghosts.len]);
    try testing.expectEqualSlices(Ghost, ch.ghosts, answered(w.r.core(), w.serial).?.ghosts);
}

/// A function `cut` took a line away from and changed another in, and a
/// file beside it: `Changes @-` puts in the buffer the line taken away (a
/// builtin's name and a path in it), the changed line's old text and
/// cut's description, as lines.
const Lines = struct {
    const fn_text = "fn f() void {\n    a();\n    // Syntax b.zig\n    c();\n}\n";
    const cut_text = "fn f() void {\n    a();\n    c2();\n}\n";

    fn repo() !?Repo {
        var r = try Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ cut_text, "cut" } }, null) orelse return null;
        errdefer r.deinit(testing.allocator);
        try r.tmp.dir.writeFile(testing.io, .{ .sub_path = "b.zig", .data = "const b = 1;\n" });
        return r;
    }

    /// The buffer's lines, the layer shown; `said` cut's description.
    fn shown(said: []const u8) [7][]const u8 {
        return .{ "fn f() void {", "    a();", "    // Syntax b.zig", "    c();", "    c2();", said, "}" };
    }

    fn open(p: *Pardes, file: []const u8) !*Pane {
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{file}) });
        p.update(.{ .command = "Changes @-" });
        return p.panes[p.view().active].?;
    }

    fn send(p: *Pardes, keys: []const u8) void {
        for (keys) |k| p.update(.{ .key = if (k == 27) .{ .cp = pardes.Key.escape } else .{ .cp = k, .text = &[_]u8{k} } });
    }

    fn click(p: *Pardes, button: pardes.Mouse.Button, col: u16, row: u16) void {
        p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = col, .row = row } });
        p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = col, .row = row } });
    }

    fn at(pane: *Pane, row: i32, col: i32) void {
        pane.body.cur_row = row;
        pane.body.cur_col = col;
        pane.body.vsel.active = false;
        pane.body.nsel = 0;
    }

    fn description(arena: std.mem.Allocator, ch: *const Changes) ![]const u8 {
        return std.fmt.allocPrint(arena, "{s} cut t now", .{ch.pins[0].id[0..4]});
    }
};

test "the layer's lines are the pane's text, read-only: j and k go onto them, a selection through them yanks the texts in order, / finds a word only a deleted line has, B2 on a builtin's name there runs it and B3 on a path opens it, a text object and a count work there; typing, d, a paste and a replace there or across their edge are refused in words, the file as it was; a Look at :N is the file's line N; hidden with the cursor in one, it is at the start of the file line it stood before" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        // Tall enough that the body's lines stay in view beside the `/`
        // query however long the test's directory makes the tags.
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 44, .windowed = windowed });
        defer p.deinit();
        // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
        p.settings.jumps = .@"new-pane";
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const pane = try Lines.open(p, repo.file);
        const id = p.view().active;
        const f = &pane.file.?;
        const ch = answered(p, pane.serial).?;
        const want = Lines.shown(try Lines.description(arena.allocator(), ch));
        for (want, 0..) |w, row| try testing.expectEqualStrings(w, File.sourceLine(pane, @intCast(row)));
        try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator()));
        // j and k: onto the line taken away, the old text, the line, the
        // description, and back.
        p.update(.{ .command = "Look :2" });
        Lines.send(p, ";");
        try testing.expectEqual(@as(i32, 1), pane.body.cur_row);
        for ([_]i32{ 2, 3, 4, 5 }) |row| {
            Lines.send(p, "j");
            try testing.expectEqual(row, pane.body.cur_row);
        }
        Lines.send(p, "k");
        try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
        // From `a();` through the two lines taken away to `c2();`: yanked,
        // the texts as shown, in order.
        Lines.at(pane, 1, 0);
        Lines.send(p, "xxxxy;");
        try testing.expectEqualStrings("    a();\n    // Syntax b.zig\n    c();\n    c2();\n", p.registers.text(p.gpa, pardes.Registers.default).?);
        // A text object (the word under the cursor) and a count there.
        Lines.at(pane, 2, 8);
        Lines.send(p, "miwy;");
        try testing.expectEqualStrings("Syntax", p.registers.text(p.gpa, pardes.Registers.default).?);
        Lines.at(pane, 2, 0);
        Lines.send(p, "2j");
        try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
        // Refused, in words, the buffer and the file as they were: a key
        // typed in it, its line deleted, a paste in it, a character
        // replaced, a deletion from the line above into it.
        const before = try arena.allocator().dupe(u8, f.content);
        for ([_][]const u8{ "iz\x1b", "d", "xd", "p", "rq", "kxxd" }) |keys| {
                p.view().active = id;
            Lines.at(pane, 2, 6);
            p.setMessage(.at(id), "");
            Lines.send(p, keys);
            try testing.expectEqualStrings(before, f.content);
            try testing.expect(std.mem.indexOf(u8, told(p, id), File.read_only_said) != null);
            Lines.send(p, "\x1b;");
        }
        try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator()));
        try testing.expectEqual(f.saved_revision, f.revision);
        // B2 on the builtin's name in the line taken away runs it; B3 on
        // the path there opens it (no selection held: B2 in one runs it).
        // (The refusals' words, stacked in the notice band over the body's
        // first rows, gone.)
        p.messages.live_len = 0;
        p.view().active = id;
        Lines.at(pane, 0, 0);
        p.sync();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const tx = body.x + File.gutterWidth(pane);
        const ty = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, 2, 0).row));
        const ink = pane.layers.ink;
        Lines.click(p, .middle, tx + 9, ty);
        try testing.expectEqual(!ink, pane.layers.ink);
        Lines.click(p, .right, tx + 16, ty);
        const opened = p.panes[p.view().active].?;
        try testing.expect(std.mem.endsWith(u8, opened.file.?.path, "/b.zig"));
        p.view().active = id;
        // `:3` is the file's line 3, `c2();`: past the two lines above it.
        p.update(.{ .command = "Look :3" });
        Lines.send(p, ";");
        try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
        // Hidden with the cursor in the old text: at the start of the line
        // it stood before, `c2();`.
        Lines.at(pane, 3, 6);
        p.update(.{ .command = "Changes" });
        try testing.expectEqualStrings(Lines.cut_text, f.content);
        try testing.expectEqual(@as(i32, 2), pane.body.cur_row);
        try testing.expectEqual(@as(i32, 0), pane.body.cur_col);
        // Shown again: the cursor stays on its line.
        p.update(.{ .command = "Changes" });
        try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
        // `/` finds a word only the line taken away has.
        p.view().active = id;
        Lines.at(pane, 0, 0);
        Lines.send(p, "/Syntax");
        p.update(.{ .key = .{ .cp = pardes.Key.enter } });
        p.view().active = id;
        try testing.expectEqual(@as(i32, 2), pane.body.cur_row);
    }
}

test "the node keys and the indent read the file's text: Alt-o and a function's text object beside the layer's lines select what they select with the layer hidden (the layer's lines inside the node with it), and o opens a line indented as there" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 44 });
    defer p.deinit();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const pane = try Lines.open(p, repo.file);
    const id = p.view().active;
    const f = &pane.file.?;
    const alt_o: pardes.Event = .{ .key = .{ .cp = 'o', .alt = true } };
    // What each gesture selects, in the file's offsets (9P's dot), with the
    // cursor on `c2();`'s `c`: buffer line 4 with the layer shown, the
    // file's line 2 hidden.
    const Gesture = enum { node1, node2, node3, function };
    var shown: [4]pardes.ctlfs.pane.State.Range = undefined;
    var hidden: [4]pardes.ctlfs.pane.State.Range = undefined;
    for ([_]bool{ true, false }) |layer| {
        p.view().active = id;
        if (!layer) p.update(.{ .command = "Changes" });
        try testing.expectEqual(layer, f.layer.lines.len > 0);
        const row: i32 = if (layer) 4 else 2;
        for (std.enums.values(Gesture), 0..) |g, k| {
            p.view().active = id;
            Lines.at(pane, row, 4);
            switch (g) {
                .node1, .node2, .node3 => for (0..@intFromEnum(g) + 1) |_| p.update(alt_o),
                .function => Lines.send(p, "maf"),
            }
            (if (layer) &shown else &hidden)[k] = pardes.ctlfs.pane.fileDot(pane);
            Lines.send(p, "\x1b;");
        }
    }
    errdefer for (shown, hidden) |s, h| std.debug.print("shown {d}..{d} hidden {d}..{d}\n", .{ s.q0, s.q1, h.q0, h.q1 });
    for (shown, hidden) |s, h| try testing.expectEqual(h, s);
    // The function, the whole file less its last newline: hidden, the text.
    try testing.expectEqualStrings("fn f() void {\n    a();\n    c2();\n}", Lines.cut_text[hidden[3].q0..hidden[3].q1]);
    // `o` on `c2();`: the line opened with the indent it gets hidden.
    var opened: [2][]const u8 = undefined;
    for ([_]bool{ false, true }, &opened) |layer, *o| {
        p.view().active = id;
        if (layer) p.update(.{ .command = "Changes" });
        try testing.expectEqual(layer, f.layer.lines.len > 0);
        Lines.at(pane, if (layer) 4 else 2, 4);
        Lines.send(p, "ox\x1b");
        o.* = try arena.allocator().dupe(u8, try File.fileText(f, arena.allocator()));
        Lines.send(p, "u");
    }
    try testing.expectEqualStrings("fn f() void {\n    a();\n    c2();\n    x\n}\n", opened[0]);
    try testing.expectEqualStrings(opened[0], opened[1]);
}

test "a pinned change neither behind nor ahead of the shown revision (a sibling) draws nothing, and the notice line says so in words: alone, nothing pinned; beside one behind, that one drawn" {
    const gpa = testing.allocator;
    // `two` and `sib` both children of `one`: the working copy on `sib`.
    var repo = try Repo.with(gpa, &.{ .{ Repo.one, "one" }, .{ Repo.two, "two" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    if (!try Repo.run(gpa, repo.dir, &.{ "new", "@--" })) return error.SkipZigTest;
    try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = Repo.three });
    if (!try Repo.run(gpa, repo.dir, &.{ "commit", "-m", "sib" })) return error.SkipZigTest;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    try testing.expectEqualStrings(Repo.three, pane.file.?.content);
    const Said = struct {
        fn aside(said: []const u8) bool {
            const want = " is not on @'s line";
            if (!std.mem.startsWith(u8, said, "Changes: ") or !std.mem.endsWith(u8, said, want)) return false;
            const named = said["Changes: ".len .. said.len - want.len];
            return named.len == 8 and isChangeId(named);
        }
    };
    // `two` alone: nothing drawn, and why.
    p.update(.{ .command = "Changes ~::@" });
    errdefer std.debug.print("told: {s}\n", .{told(p, id)});
    try testing.expect(Said.aside(told(p, id)));
    try testing.expect(answered(p, pane.serial) == null);
    try testing.expectEqual(0, pane.layers.lanes);
    try testing.expectEqualStrings(Repo.three, pane.file.?.content);
    // `two` with `sib` (behind): `sib` drawn, `two` named.
    p.update(.{ .command = "Changes ~::@ | @-" });
    try testing.expect(Said.aside(told(p, id)));
    const ch = answered(p, pane.serial).?;
    try testing.expectEqual(@as(usize, 1), ch.pins.len);
    try testing.expectEqualStrings("sib", ch.pins[0].title[0..ch.pins[0].title_len]);
    try testing.expect(pane.layers.lanes > 0);
}

test "THE FILE'S TEXT: with the layer's lines in the buffer, every reader of the file reads what it reads with them out, byte for byte: a Save, a Save to another name, Edit's w, body over 9P, the dirty check, a reread from the disk, a Get, jj's lines asked again, the context declarations, the colours of the file's lines, the language server's text and the place it is asked at" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const th = @import("ninep/harness.zig");
    const Node = @import("ninep/tree.zig").Node;
    const Lsp = @import("dev").host_io.Lsp;
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const keep = arena.allocator();
    const Seen = struct {
        lsp_source: []const u8 = "",
        lsp_offset: u32 = 0,
        saved: []const u8 = "",
        clean: bool = false,
        other: []const u8 = "",
        written: []const u8 = "",
        body: []const u8 = "",
        reread_clean: bool = false,
        gotten: []const u8 = "",
        lines: []const Line = &.{},
        declarations: []const [3]usize = &.{},
        colours: []const u8 = "",
    };
    var seen: [2]Seen = .{ .{}, .{} };
    const other = try std.fmt.allocPrint(keep, "{s}/copy.zig", .{repo.dir});
    const w_path = try std.fmt.allocPrint(keep, "{s}/w.zig", .{repo.dir});
    for ([_]bool{ false, true }, &seen) |shown, *got| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = false });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        const f = &pane.file.?;
        if (shown) p.update(.{ .command = "Changes @-" });
        try testing.expectEqual(shown, f.layer.lines.len > 0);
        // The same edit of a file line, `c2();` (its line 3).
        p.update(.{ .command = "Look :3" });
        Lines.send(p, ";A // e\x1b");
        try testing.expect(f.revision != f.saved_revision);
        // The language server: the place it is asked at, the text it is sent.
        p.update(.{ .command = "Def" });
        got.lsp_offset = p.lsp_ask.last.?.offset;
        const job = try Lsp.snapshot(gpa, p, .{ .id = 1, .kind = .definition, .pane = .at(id), .offset = got.lsp_offset, .arg = "" });
        defer job.free(gpa);
        got.lsp_source = try keep.dupe(u8, job.source);
        // The context declarations and the colours of the file's lines.
        f.tree_context = true;
        File.refreshContext(p, pane, f);
        var decls: std.ArrayList([3]usize) = .empty;
        for (f.context.declarations) |d| try decls.append(keep, .{ d.start_line, d.end_line, d.header_end_line });
        got.declarations = decls.items;
        f.tree_context = false;
        p.sync();
        _ = try p.render(arena.allocator());
        var colours: std.ArrayList(u8) = .empty;
        for (0..File.fileLen(f)) |b| {
            const at = File.bufferOffset(f, b, false);
            try colours.append(keep, if (at >= f.highlight_start and at - f.highlight_start < f.highlights.len) f.highlights[at - f.highlight_start] else 0xff);
        }
        got.colours = colours.items;
        // body over 9P.
        got.body = try keep.dupe(u8, th.rd(p, Node.of(pane.serial, .body), 0, 1 << 16).bytes);
        // A Save: what the host is asked to write; clean after it.
        p.update(.{ .command = "Save" });
        while (p.nextEffect()) |e| p.perform(e);
        got.saved = try keep.dupe(u8, p.fallback.get(repo.file) orelse "");
        got.clean = f.revision == f.saved_revision and !pardes.ctlfs.pane.dirtyOf(pane);
        // A Save to another name; Edit's w.
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Save {s}", .{other}) });
        while (p.nextEffect()) |e| p.perform(e);
        got.other = try keep.dupe(u8, p.fallback.get(other) orelse "");
        p.view().active = id;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Edit ,w {s}", .{w_path}) });
        while (p.nextEffect()) |e| p.perform(e);
        got.written = try keep.dupe(u8, p.fallback.get(w_path) orelse "");
        // The disk reread as what was saved: nothing reloaded, clean.
        const revision = f.revision;
        File.changed(p, @intCast(id), got.saved);
        got.reread_clean = f.revision == revision and f.revision == f.saved_revision;
        // jj asked again: who wrote each of the file's lines.
        p.view().active = id;
        p.update(.{ .command = "Changes @-" });
        got.lines = try keep.dupe(Line, answered(p, pane.serial).?.lines);
        if (!shown) p.update(.{ .command = "Changes" });
        try testing.expectEqual(shown, f.layer.lines.len > 0);
        // A Get: the file's text from where it was read, the layer kept.
        p.update(.{ .command = "Get" });
        got.gotten = try keep.dupe(u8, try File.fileText(f, arena.allocator()));
        try testing.expectEqual(shown, f.layer.lines.len > 0);
    }
    const off, const on = seen;
    try testing.expectEqualStrings("fn f() void {\n    a();\n    c2(); // e\n}\n", off.saved);
    inline for (comptime std.meta.fieldNames(Seen)) |name| {
        const a = @field(off, name);
        const b = @field(on, name);
        if (@TypeOf(a) == bool or @TypeOf(a) == u32) try testing.expectEqual(a, b) else try testing.expectEqualSlices(@TypeOf(a[0]), a, b);
    }
    try testing.expect(off.clean and off.reread_clean);
    try testing.expect(off.declarations.len > 0);
}

test "an edit made while the layer is shown is the file's: journaled in its lines, its undo lands right shown or hidden, hidden and shown again between; the layer's lines are never in the journal" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false });
    defer p.deinit();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const pane = try Lines.open(p, repo.file);
    const f = &pane.file.?;
    const typed = "fn f() void {\n    a();\n    c2(); // e\n}\n";
    // `c2();`, the line after the two of the layer: appended to, shown.
    Lines.at(pane, 4, 0);
    Lines.send(p, "A // e\x1b");
    try testing.expectEqualStrings(typed, try File.fileText(f, arena.allocator()));
    try testing.expectEqualStrings("    c2(); // e", File.sourceLine(pane, 4));
    // Undone while shown, redone.
    Lines.send(p, "u");
    try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator()));
    try testing.expectEqual(@as(usize, 3), f.layer.lines.len);
    try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
    Lines.send(p, "U");
    try testing.expectEqualStrings(typed, try File.fileText(f, arena.allocator()));
    // Hidden, shown again, then undone: the same file text, the lines
    // where they stood.
    p.update(.{ .command = "Changes" });
    try testing.expectEqualStrings(typed, f.content);
    p.update(.{ .command = "Changes" });
    Lines.send(p, "u");
    try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator()));
    try testing.expectEqualStrings("    c2();", File.sourceLine(pane, 4));
    // Hidden, undone back to before the edit and redone: the file's.
    p.update(.{ .command = "Changes" });
    Lines.send(p, "U");
    try testing.expectEqualStrings(typed, f.content);
    Lines.send(p, "u");
    try testing.expectEqualStrings(Lines.cut_text, f.content);
    // No entry of the journal holds a byte of the layer's.
    for (f.history.journal.entries.items) |e| try testing.expect(std.mem.indexOf(u8, e.removed, "Syntax") == null);
}

test "9P serves the file's text: body, addr and data in its offsets; dot and sel with the cursor in a layer's line are after the file line above it; a write over 9P is the file's, the layer's lines standing where they stood" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const th = @import("ninep/harness.zig");
    const Node = @import("ninep/tree.zig").Node;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false });
    defer p.deinit();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const pane = try Lines.open(p, repo.file);
    const serial = pane.serial;
    try testing.expectEqualStrings(Lines.cut_text, th.rd(p, Node.of(serial, .body), 0, 1 << 16).bytes);
    // The cursor in the line taken away: dot is where `c2();` starts in
    // the file, after `a();` (14 + 9 bytes).
    Lines.at(pane, 2, 6);
    try testing.expectEqualStrings("         23          23 ", th.rd(p, Node.of(serial, .dot), 0, 64).bytes);
    // A selection from `a();` into the old text: what the file has of it.
    Lines.at(pane, 1, 0);
    Lines.send(p, "xx");
    try testing.expectEqualStrings("    a();\n", th.rd(p, Node.of(serial, .sel), 0, 64).bytes);
    Lines.send(p, ";");
    // `addr` 3 is the file's line 3; `data` there is it.
    _ = th.wr(p, Node.of(serial, .addr), "3");
    try testing.expectEqualStrings("    c2();\n", th.rd(p, Node.of(serial, .xdata), 0, 64).bytes);
    // Written over: the file's line, the layer's lines still before it.
    _ = th.wr(p, Node.of(serial, .addr), "3");
    _ = th.wr(p, Node.of(serial, .data), "    c3();\n");
    try testing.expectEqualStrings("fn f() void {\n    a();\n    c3();\n}\n", th.rd(p, Node.of(serial, .body), 0, 1 << 16).bytes);
    try testing.expectEqualStrings("    // Syntax b.zig", File.sourceLine(pane, 2));
    try testing.expectEqualStrings("    c3();", File.sourceLine(pane, 4));
    // `dot=addr` from 9P lands on the file's line.
    _ = th.wr(p, Node.of(serial, .addr), "3");
    _ = th.wr(p, Node.of(serial, .ctl), "dot=addr");
    try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
}

test "a session dumped by a build whose layer was a view's bit and no lines (wire 31) loads with the layer shown as it was, its lines in the buffer, the file's text and its places as they were; a hidden one stays hidden" {
    const gpa = testing.allocator;
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ true, false }) |shown| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false });
        defer p.deinit();
        const pane = try Lines.open(p, repo.file);
        const f = &pane.file.?;
        // As 31 kept it: the view's bit (or none), the buffer the file's.
        hideLayer(p, f);
        if (!shown) setLanes(p, f, false);
        try testing.expectEqualStrings(Lines.cut_text, f.content);
        Lines.at(pane, 2, 3);
        try pardes.dump.dumpState(p);
        const q = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false }, p.dump_out.?);
        defer q.deinit();
        const back = q.panes[q.view().active].?;
        const bf = &back.file.?;
        try testing.expectEqualStrings(Lines.cut_text, try File.fileText(bf, q.scratch.allocator()));
        try testing.expectEqual(shown, bf.layer.lines.len == 3);
        try testing.expectEqual(shown, back.layers.lanes > 0);
        // The cursor on `c2();` (the file's line 3) as it was.
        try testing.expectEqualStrings("    c2();", File.sourceLine(back, back.body.cur_row));
    }
}

test "a line replaced by one too unlike it to be one line changed: what went right above what came, a diff's order, in the file's own pane and from the middle alike" {
    const gpa = testing.allocator;
    const one = "l1\nl2\nline 10\nl4\n";
    const two = "l1\nl2\nline ten CHANGED by two\nl4\n";
    var repo = try Repo.with(gpa, &.{ .{ one, "one" }, .{ two, "two" }, .{ two ++ "l5\n", "three" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    for ([_][]const u8{ "", "@@--" }) |at| {
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}{s}", .{ repo.file, at }) });
        const pane = p.panes[p.view().active].?;
        p.update(.{ .command = "Changes @--" });
        try testing.expectEqualStrings("line 10", File.sourceLine(pane, 2));
        try testing.expectEqualStrings("line ten CHANGED by two", File.sourceLine(pane, 3));
    }
}

test "from the middle: in a revision's pane a pin behind it shows the lines it took away where they stood (a changed line's old text right above it), and a pin ahead of it shows the lines it will write as the read-only lines where they will stand, the lines it will take away the text's, going" {
    const gpa = testing.allocator;
    // `two` changes l3 and takes l7 away; `three`, ahead of it, writes a
    // line after l1 and changes l5.
    const one = "l1\nl2\nl3\nl4\nl5\nl6\nl7\n";
    const two = "l1\nl2\nl3 two\nl4\nl5\nl6\n";
    const three = "l1\nnew three\nl2\nl3 two\nl4\nl5 three\nl6\n";
    var repo = try Repo.with(gpa, &.{ .{ one, "one" }, .{ two, "two" }, .{ three, "three" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@--", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        p.update(.{ .command = "Changes @-- | @-" });
        const ch = answered(p, pane.serial).?;
        try testing.expectEqual(@as(usize, 2), ch.pins.len);
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const said_two = try std.fmt.allocPrint(arena.allocator(), "{s} two t now", .{ch.pins[0].id[0..4]});
        const said_three = try std.fmt.allocPrint(arena.allocator(), "{s} three t now", .{ch.pins[1].id[0..4]});
        const want = [_][]const u8{ "l1", "new three", "l2", "l3", "l3 two", said_two, "l4", "l5", "l5 three", said_three, "l6", "l7" };
        for (want, 0..) |w, row| try testing.expectEqualStrings(w, File.sourceLine(pane, @intCast(row)));
        try testing.expectEqualStrings(two, try File.fileText(&pane.file.?, arena.allocator()));
        // Drawn: what three will write green across, what it will take
        // away red across, what two took away red.
        p.sync();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const x = body.x + File.gutterWidth(pane) + 1;
        const grounds = p.chrome();
        for ([_]u16{ 1, 8 }) |row| try testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, s.at(x, body.y + row).style.bg);
        for ([_]u16{ 7, 11 }) |row| try testing.expectEqual(pardes.Color{ .rgb = grounds.del.row }, s.at(x, body.y + row).style.bg);
    }
}

test "a client replays the layer's lines and an edit refused among them, and ends equal; a client joined over a pane showing the layer loads its lines" {
    var repo = try Lines.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes @-" }));
    r.confirm(try a.local(.{ .command = "Look :2" }));
    for (";jjiz") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } }));
    for ("jA;") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    const af = &a.core.panes[id].?.file.?;
    const rf = &r.core().panes[id].?.file.?;
    try testing.expectEqualStrings("fn f() void {\n    a();\n    c2();;\n}\n", try File.fileText(af, a.core.scratch.allocator()));
    try testing.expectEqualStrings(af.content, rf.content);
    try testing.expectEqualSlices(File.ReadOnly, af.layer.lines, rf.layer.lines);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
    try R.loadsAsSession(a, 2);
}

/// A function three changes wrote: `fn` all of it, `mid` its lines 3-6
/// (rewriting two, adding two), `shift` line 4 again.
const Stack = struct {
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    g();\n    h();\n    i();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    b2();\n    c2();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    const shift_text = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    /// Who wrote each of shift_text's lines: fn 0, mid 1, shift 2.
    const pins = [_]u16{ 0, 0, 1, 2, 1, 1, 0, 0, 0, 0 };

    fn repo(working: ?[]const u8) !?Repo {
        return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, working);
    }
};

fn pinsOf(ch: *const Changes, out: []u16) []u16 {
    for (ch.lines, out[0..ch.lines.len]) |l, *o| o.* = @intFromEnum(l.pin);
    return out[0..ch.lines.len];
}

test "Changes lines jj's annotation up with the pane's text: a line jj has not seen (typed, not snapshotted) is nobody's, the lines after it keep their changes" {
    // The file on disk has a line more than jj's last snapshot of it.
    const working = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    new();\n    y();\n    g();\n    h();\n    i();\n}\n";
    var repo = try Stack.repo(working) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    try testing.expectEqualStrings(working, pane.file.?.content);
    p.update(.{ .command = "Changes ::@" });
    const none = @intFromEnum(PinIndex.none);
    var got: [16]u16 = undefined;
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, none, 1, 0, 0, 0, 0 }, pinsOf(answered(p, pane.serial).?, &got));
}

test "the lanes ride with the text: a line typed in a nested block is nobody's, its undo puts the values back, a deleted line takes its value; a client replays it equal" {
    var repo = try Stack.repo(null) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    const Keys = struct {
        fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void {
            for (keys) |k| {
                const ev: pardes.Event = if (k == 27) .{ .key = .{ .cp = pardes.Key.escape } } else .{ .key = .{ .cp = k, .text = &[_]u8{k} } };
                re.confirm(try au.local(ev));
            }
            re.settle();
        }
    };
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes ::@" }));
    r.settle();
    const serial = a.core.panes[a.core.view().active].?.serial;
    const ch = answered(a.core, serial).?;
    var got: [16]u16 = undefined;
    try testing.expectEqualSlices(u16, &Stack.pins, pinsOf(ch, &got));
    const before = try testing.allocator.dupe(Line, ch.lines);
    defer testing.allocator.free(before);
    const none = @intFromEnum(PinIndex.none);
    // A line opened below `c3();` (line 4, inside mid's block): nobody's;
    // the rows around keep their lanes.
    r.confirm(try a.local(.{ .command = "Look a.zig:4" }));
    try Keys.send(a, r, "oz\x1b");
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, none, 1, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got));
    try testing.expectEqual(before[3].lanes, answered(a.core, serial).?.lines[3].lanes);
    try testing.expectEqual(before[4].lanes, answered(a.core, serial).?.lines[5].lanes);
    // Undone: the values as they were.
    try Keys.send(a, r, "u");
    try testing.expectEqualSlices(Line, before, answered(a.core, serial).?.lines);
    // `x();` (line 5, mid's) deleted: its value goes with it.
    r.confirm(try a.local(.{ .command = "Look a.zig:5" }));
    try Keys.send(a, r, ";xd");
    try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], try File.fileText(&a.core.panes[a.core.view().active].?.file.?, a.core.scratch.allocator()));
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got));
    try testing.expectEqual(before[5].lanes, answered(a.core, serial).?.lines[4].lanes);
    try testing.expect(r.diverged == null);
    try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "a client's own line opened over pinned changes, rolled back by the session's key first: the lanes it spliced under its copy are the copy's again, freed once; the client ends equal" {
    var repo = try Stack.repo(null) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes ::@" }));
    r.confirm(try a.local(.{ .command = "Look a.zig:4" }));
    r.settle();
    const serial = a.core.panes[a.core.view().active].?.serial;
    // The client opens a line below: an edit of the file, whose step splices
    // the pinned lines' values (jj.edited) under the copy it takes.
    const typed = try testing.allocator.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .text = "o" } }));
    defer testing.allocator.free(typed);
    try testing.expectEqual(@as(usize, 1), r.applied);
    // The session's own key comes first: the copy put back, the `o` applied
    // again over it, then confirmed.
    r.confirm(try a.local(.{ .key = .{ .cp = 'k', .text = "k" } }));
    r.settle();
    r.confirm(try a.take(typed));
    r.settle();
    try testing.expect(r.diverged == null);
    try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

/// Two functions four changes wrote: `fn` both, `f2` and `f3` rewrote
/// f's line, `g2` g's: f three changes, g two.
const Churned = struct {
    const fn_text = "fn f() void {\n    a();\n}\n\nfn g() void {\n    b();\n}\n";
    const f2_text = "fn f() void {\n    a2();\n}\n\nfn g() void {\n    b();\n}\n";
    const f3_text = "fn f() void {\n    a3();\n}\n\nfn g() void {\n    b();\n}\n";
    const g2_text = "fn f() void {\n    a3();\n}\n\nfn g() void {\n    b2();\n}\n";

    fn repo() !?Repo {
        return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ f2_text, "f2" }, .{ f3_text, "f3" }, .{ g2_text, "g2" } }, null);
    }
};

test "Churn counts the changes that touched each declaration and draws them after the line number and by the scroll thumb, grey to red on a log scale; bare again, off" {
    const gpa = testing.allocator;
    var repo = try Churned.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        const before = File.gutterWidth(pane);
        p.update(.{ .command = "Churn" });
        const heat = churned(p, pane.serial).?;
        try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, heat.lines);
        try testing.expectEqual(@as(u16, 3), heat.hottest);
        try testing.expectEqual(before + 1, File.gutterWidth(pane));
        // Drawn: a cell after the number, f's the theme's red, g's along
        // the way from the numbers' grey at ln 3 / ln 4, none between.
        p.sync();
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const x = body.x + File.gutterWidth(pane) - 1;
        // Churn's steps (Chrome.heat): the hottest the last, f's 3 of 4's
        // log, the seventh.
        const red = p.chrome().heat[7];
        const warm = p.chrome().heat[6];
        for (0..7) |row| {
            const cell = s.at(x, body.y + @as(u16, @intCast(row)));
            if (row == 3) {
                try testing.expectEqualStrings(" ", cell.grapheme());
                continue;
            }
            try testing.expectEqualStrings("\u{258c}", cell.grapheme());
            try testing.expectEqual(pardes.Color{ .rgb = if (row < 3) red else warm }, cell.style.fg);
        }
        // By the scroll thumb: the rail's first row holds f's lines.
        const rail = s.region(.rail, id).?.rect;
        if (windowed) {
            const strip = for (s.heat.items) |h| {
                if (h.owner == id and h.row == 0) break h;
            } else return error.TestExpectedEqual;
            try testing.expectEqual(red, strip.rgb);
        } else try testing.expectEqual(pardes.Color{ .rgb = red }, s.at(rail.x + 1, rail.y).style.bg);
        // Bare again: hidden, the gutter as it was; again: shown, jj not asked.
        p.update(.{ .command = "Churn" });
        try testing.expectEqual(before, File.gutterWidth(pane));
        p.update(.{ .command = "Churn" });
        try testing.expectEqual(before + 1, File.gutterWidth(pane));
        try testing.expectEqual(heat, churned(p, pane.serial).?);
    }
}

test "Churn's window: a revset, or a span of time back from now; jj's refusal said" {
    const gpa = testing.allocator;
    var repo = try Churned.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    // f3 and g2 alone: one each.
    p.update(.{ .command = "Churn @--::@" });
    try testing.expectEqualSlices(u16, &.{ 1, 1, 1, 0, 1, 1, 1 }, churned(p, pane.serial).?.lines);
    // The last week: all four, just made.
    p.update(.{ .command = "Churn 1w" });
    try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(p, pane.serial).?.lines);
    try testing.expectEqualStrings("::(@) & author_date(after:\"1 weeks ago\")", churned(p, pane.serial).?.window());
    p.update(.{ .command = "Churn nosuch" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Churn: Revision `nosuch` doesn't exist") != null);
}

test "Churn on a worker: jj's answer kept raw, counted when the worker's parse of the text lands; the client equal" {
    var repo = try Churned.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "");
    defer w.deinit();
    try w.word("Churn");
    try w.land();
    try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(w.a.core, w.serial).?.lines);
    try testing.expectEqualSlices(u16, churned(w.a.core, w.serial).?.lines, churned(w.r.core(), w.serial).?.lines);
}

test "Churn's counts ride with the text, and a client replays them equal" {
    var repo = try Churned.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Churn" }));
    r.settle();
    const serial = a.core.panes[a.core.view().active].?.serial;
    // `a3();` deleted: its value goes with it.
    r.confirm(try a.local(.{ .command = "Look a.zig:2" }));
    for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
    r.settle();
    try testing.expectEqualSlices(u16, &.{ 3, 3, 0, 2, 2, 2 }, churned(a.core, serial).?.lines);
    try testing.expect(r.diverged == null);
    try testing.expectEqualSlices(u16, churned(a.core, serial).?.lines, churned(r.core(), serial).?.lines);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "a B3 click on path@rev:line in running text opens the file at that revision there" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "notes.txt", .data = "see a.zig@@-:2 here\n" });
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/notes.txt", .{repo.dir}) });
    const notes = p.view().active;
    p.sync();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const body = s.region(.body, notes).?.rect;
    // On the `@` of the address, the body's first row.
    const x: u16 = body.x + File.gutterWidth(p.panes[notes].?) + @as(u16, "see a.zig".len);
    p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y } });
    p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y } });
    const shown = p.view().active;
    try testing.expect(shown != notes);
    const f = &p.panes[shown].?.file.?;
    try testing.expect(of(f) != null);
    try testing.expectEqualStrings(Repo.two, f.content);
    try testing.expectEqual(@as(i32, 1), p.panes[shown].?.body.cur_row);
}

test "a revision's text is read-only over 9P too: an open to write it is refused in words" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    try testing.expect(of(&pane.file.?) != null);
    const th = @import("ninep/harness.zig");
    const tree = @import("ninep/tree.zig");
    for ([_]tree.PaneFile{ .body, .data, .xdata, .sel }) |file| {
        const got = th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, file), .omode = 1 });
        try testing.expectEqual(@as(u16, 30), got.errno());
        try testing.expectEqual(@as(u16, 30), @import("cloud9").fs.enameErrno(got.reply.ename));
    }
    // Reading it is as any text's.
    try testing.expectEqual(@as(u16, 0), th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, .body), .omode = 0 }).errno());
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
}

/// Five commits of a function on one line of history, a `Compare`'s points
/// the first, the third and the fifth (`@-----`, `@---`, `@-`): `two`
/// changes `b();`, `three` takes `c();` away (the first pair's two
/// changes); `four` changes `d();`, `five` adds `e();` (the second's).
const Points = struct {
    const one = "fn f() void {\n    a();\n    b();\n    c();\n    d();\n}\n";
    const two = "fn f() void {\n    a();\n    b2();\n    c();\n    d();\n}\n";
    const three = "fn f() void {\n    a();\n    b2();\n    d();\n}\n";
    const four = "fn f() void {\n    a();\n    b2();\n    d2();\n}\n";
    const five = "fn f() void {\n    a();\n    b2();\n    d2();\n    e();\n}\n";
    const word = "Compare @----- @--- @-";

    fn repo() !?Repo {
        return Repo.with(testing.allocator, &.{ .{ one, "one" }, .{ two, "two" }, .{ three, "three" }, .{ four, "four" }, .{ five, "five" } }, null);
    }

    /// Each pin's row (its description's ghost row), by pin.
    fn rows(ch: *const Changes, out: [][]const u8) [][]const u8 {
        for (ch.ghosts) |g| if (g.kind == .description) {
            out[g.pin] = ch.ghost_text[g.text..][0..g.len];
        };
        return out[0..ch.pins.len];
    }

    /// `row` is a pair's as `PairRow.say` writes it, two changes of one
    /// day between: `from..to  2 changes  YYYY-MM-DD`.
    fn isRow(row: []const u8, from: []const u8, to: ?[]const u8) bool {
        if (row.len != 41 or !std.mem.startsWith(u8, row, from) or !std.mem.eql(u8, row[8..10], "..")) return false;
        if (to) |t| if (!std.mem.eql(u8, row[10..18], t)) return false;
        return std.mem.eql(u8, row[18..31], "  2 changes  ") and row[35] == '-' and row[38] == '-';
    }
};

test "Compare pins the whole difference between each two points as one change: three points on one line of history are two lanes, each pair's row `from..to  N changes  day` after its last line, what each took away where it stood; bare hides and shows them; Changes after it replaces them, and it Changes'" {
    const gpa = testing.allocator;
    var repo = try Points.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 24, .windowed = windowed });
        defer p.deinit();
        // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
        p.settings.jumps = .@"new-pane";
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        p.update(.{ .command = Points.word });
        const ch = answered(p, pane.serial) orelse {
            std.debug.print("told: {s}\n", .{told(p, id)});
            return error.TestUnexpectedResult;
        };
        try testing.expectEqualStrings("@----- @--- @-", ch.pinned());
        try testing.expectEqual(@as(usize, 2), ch.pins.len);
        // Each pair's row: its two points, the two changes between, their day.
        var buf: [2][]const u8 = undefined;
        const said = Points.rows(ch, &buf);
        errdefer std.debug.print("rows: [{s}] [{s}]\n", .{ said[0], said[1] });
        try testing.expect(Points.isRow(said[0], &ch.pins[0].id, &ch.pins[1].id));
        try testing.expect(Points.isRow(said[1], &ch.pins[1].id, null));
        // Who wrote each line: b2 the first pair; d2 and e the second.
        const pins = [_]PinIndex{ .none, .none, @enumFromInt(0), @enumFromInt(1), @enumFromInt(1), .none };
        for (pins, ch.lines) |w, l| try testing.expectEqual(w, l.pin);
        // The rows as the view shows them, no number on the layer's.
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        var rbuf: [64][]const u8 = undefined;
        const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf);
        const want = [_][]const u8{ "fn f() void {", "    a();", "    b();", "    b2();", "    c();", said[0], "    d();", "    d2();", "    e();", said[1], "}" };
        const numbers = [_][]const u8{ "1", "2", "", "3", "", "", "", "4", "5", "", "6" };
        for (want, numbers, got[0..want.len]) |w, n, row| {
            try testing.expectEqualStrings(w, Ghosts.text(pane, row));
            try testing.expectEqualStrings(n, Ghosts.number(pane, row));
        }
        // Two lanes, each pair its own colour (several pinned).
        p.sync();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const first = body.x + File.gutterWidth(pane) - File.laneCells(pane);
        const colours = p.chrome().lanes[0..p.chrome().lanes_len];
        for ([_]u16{ 3, 7, 8 }, [_]usize{ 0, 1, 1 }) |row, pin| {
            if (windowed) {
                var n: usize = 0;
                for (s.lanes.items) |lane| if (lane.y == body.y + row) {
                    try testing.expectEqual(colours[pin], lane.rgb);
                    n += 1;
                };
                try testing.expectEqual(@as(usize, 1), n);
            } else {
                try testing.expectEqualStrings("\u{258e}", s.at(first, body.y + row).grapheme());
                try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(first, body.y + row).style.fg);
            }
        }
        // ]g and [g step through the pairs' places as through any change's:
        // each run's first line, a layer's line among them (`b();`, `d();`).
        p.update(.{ .command = "Look a.zig:1" });
        for ([_]i32{ 2, 6 }) |want_row| {
            for ("]g") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
            try testing.expectEqual(want_row, pane.body.cur_row);
        }
        // Bare: hidden, shown again without asking jj.
        p.update(.{ .command = "Compare" });
        try testing.expectEqual(0, pane.layers.lanes);
        p.update(.{ .command = "Compare" });
        try testing.expect(pane.layers.lanes > 0);
        try testing.expectEqual(ch, answered(p, pane.serial).?);
        // `Changes` asked after it replaces its set (one set a pane), and
        // `Compare` after `Changes` replaces that.
        p.update(.{ .command = "Changes @-" });
        const commit = answered(p, pane.serial).?;
        try testing.expectEqualStrings("@-", commit.pinned());
        try testing.expectEqual(@as(usize, 1), commit.pins.len);
        try testing.expect(!isPair(commit.pins[0]));
        p.update(.{ .command = "Compare @--- @-" });
        try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len);
        try testing.expect(isPair(answered(p, pane.serial).?.pins[0]));
    }
}

test "Compare between two points neither the other's ancestor (two branches): one change, the second point's change brought in and the first's undone, both in its row; the lines as the second has them" {
    const gpa = testing.allocator;
    const base = "fn f() void {\n    a();\n    b();\n    c();\n}\n";
    const x = "fn f() void {\n    a();\n    bx();\n    c();\n}\n";
    const y = "fn f() void {\n    a();\n    b();\n    cy();\n}\n";
    var repo = try Repo.with(gpa, &.{ .{ base, "base" }, .{ x, "x" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    // `x` a bookmark; `y` a branch of its own from `base`, the working copy on it.
    if (!try Repo.run(gpa, repo.dir, &.{ "bookmark", "create", "bx", "-r", "@-" })) return error.SkipZigTest;
    if (!try Repo.run(gpa, repo.dir, &.{ "new", "@--" })) return error.SkipZigTest;
    try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = y });
    if (!try Repo.run(gpa, repo.dir, &.{ "commit", "-m", "y" })) return error.SkipZigTest;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 24, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    p.update(.{ .command = "Compare bx @-" });
    const ch = answered(p, pane.serial) orelse {
        std.debug.print("told: {s}\n", .{told(p, id)});
        return error.TestUnexpectedResult;
    };
    try testing.expectEqual(@as(usize, 1), ch.pins.len);
    var buf: [1][]const u8 = undefined;
    const said = Points.rows(ch, &buf)[0];
    errdefer std.debug.print("row: [{s}]\n", .{said});
    try testing.expectStringStartsWith(said, &ch.pins[0].id);
    try testing.expectEqualStrings("..", said[8..10]);
    try testing.expectEqualStrings("  1 change, 1 undone  ", said[18..40]);
    // `bx` went back to `b`, `c` became `cy`: each old text above its line.
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    var rbuf: [64][]const u8 = undefined;
    const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf);
    const want = [_][]const u8{ "fn f() void {", "    a();", "    bx();", "    b();", "    c();", "    cy();", said, "}" };
    const numbers = [_][]const u8{ "1", "2", "", "3", "", "4", "", "5" };
    for (want, numbers, got[0..want.len]) |w, n, row| {
        try testing.expectEqualStrings(w, Ghosts.text(pane, row));
        try testing.expectEqualStrings(n, Ghosts.number(pane, row));
    }
    // The patch: `y` brought in, `x` undone.
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:4", .{said[0..18]}) });
    const patch = p.panes[p.view().active].?.file.?.content;
    errdefer std.debug.print("patch:\n{s}\n", .{patch});
    var brought = false;
    var undone = false;
    var rows = std.mem.splitScalar(u8, patch, '\n');
    while (rows.next()) |row| {
        if (row.len < 12) continue;
        brought = brought or (std.mem.startsWith(u8, row, "+ ") and std.mem.endsWith(u8, row[0 .. row.len - 10], " y t "));
        undone = undone or (std.mem.startsWith(u8, row, "- ") and std.mem.endsWith(u8, row[0 .. row.len - 10], " x t "));
    }
    try testing.expect(brought and undone);
}

test "Compare in a revision's pane at its middle point: the first pair behind the text as at the last; the second ahead of it (its first point's text is the one shown): the line it takes away the text's, going, the lines it writes read-only lines after it, its row after them" {
    const gpa = testing.allocator;
    var repo = try Points.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 48, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    p.update(.{ .command = "At @---" });
    const id = p.view().active;
    const pane = p.panes[id].?;
    try testing.expectEqualStrings(Points.three, pane.file.?.content);
    p.update(.{ .command = Points.word });
    const ch = answered(p, pane.serial).?;
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    var buf: [2][]const u8 = undefined;
    const said = Points.rows(ch, &buf);
    // The first pair: behind, as when the last point is shown (b2 its
    // line, `b();` and `c();` what it took away, its row after them).
    try testing.expect(Points.isRow(said[0], &ch.pins[0].id, &ch.pins[1].id));
    const pins = [_]PinIndex{ .none, .none, @enumFromInt(0), .none, .none };
    for (pins, ch.lines) |w, l| try testing.expectEqual(w, l.pin);
    // The second, ahead (a change ahead's rule): `d();` the text's, going;
    // `d2();` and `e();` read-only lines after it; its row after them.
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    var rbuf: [64][]const u8 = undefined;
    const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf);
    const want = [_][]const u8{ "fn f() void {", "    a();", "    b();", "    b2();", "    c();", said[0], "    d();", "    d2();", "    e();", said[1], "}" };
    try testing.expectEqual(@as(PinIndex, @enumFromInt(1)), ch.lines[3].going);
    errdefer for (got) |row| std.debug.print("[{s}]\n", .{row});
    try testing.expect(got.len >= want.len);
    for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row));
}

test "Compare refuses one point and a point that names several commits, and says what jj refuses in its words; nothing is pinned" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    for ([_][]const u8{ "Compare @-", "Compare" }) |word_| {
        p.update(.{ .command = word_ });
        try testing.expect(std.mem.indexOf(u8, told(p, id), "Compare: two points or more, each one revision") != null);
    }
    p.update(.{ .command = "Compare @--|@- @-" });
    errdefer std.debug.print("told: {s}\n", .{told(p, id)});
    try testing.expectStringStartsWith(told(p, id), "Compare: ");
    try testing.expect(std.mem.indexOf(u8, told(p, id), "more than one revision") != null);
    p.update(.{ .command = "Compare nosuch @-" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Compare: Revision `nosuch` doesn't exist") != null);
    try testing.expect(answered(p, pane.serial) == null);
    try testing.expectEqual(0, pane.layers.lanes);
}

test "a Look on a pair's row opens its patch: the changes between on top, newest first, each signed, then the file's difference between the two points, the cursor on its last line there; typed, the same" {
    const gpa = testing.allocator;
    var repo = try Points.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    p.update(.{ .command = Points.word });
    const ch = answered(p, pane.serial).?;
    var buf: [2][]const u8 = undefined;
    const said = Points.rows(ch, &buf);
    p.sync();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const body = s.region(.body, id).?.rect;
    // The first pair's row (row 5): a B3 on its first word.
    const x = body.x + File.gutterWidth(pane) + 1;
    p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 5 } });
    p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 5 } });
    const hid = p.view().active;
    try testing.expect(hid != id);
    const patch = p.panes[hid].?;
    const f = &patch.file.?;
    errdefer std.debug.print("patch:\n{s}\n", .{f.content});
    var rows = std.mem.splitScalar(u8, f.content, '\n');
    try testing.expectEqualStrings(try std.fmt.allocPrint(arena.allocator(), "Compare {s}", .{said[0][0..18]}), rows.next().?);
    const three = rows.next().?;
    const two = rows.next().?;
    try testing.expectStringStartsWith(three, "+ ");
    try testing.expect(std.mem.endsWith(u8, three[0 .. three.len - 10], " three t "));
    try testing.expectStringStartsWith(two, "+ ");
    try testing.expect(std.mem.endsWith(u8, two[0 .. two.len - 10], " two t "));
    try testing.expect(std.mem.indexOf(u8, f.content, "-    c();") != null);
    // The cursor on the pair's last line in a.zig, `b2();` (its line 3 at the second point).
    const at = f.location_rows[@intCast(patch.body.cur_row)];
    try testing.expectEqualStrings("a.zig:3", try std.fmt.allocPrint(arena.allocator(), "{s}:{d}", .{ std.Io.Dir.path.basename(at.path), at.at.line }));
    // The same, typed, at another line.
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:2", .{said[0][0..18]}) });
    const typed = p.panes[p.view().active].?;
    try testing.expectStringStartsWith(typed.file.?.content, "Compare ");
    try testing.expectEqual(@as(usize, 2), typed.file.?.location_rows[@intCast(typed.body.cur_row)].at.line);
}

test "a client replays Compare from what the session's jj answered and ends equal; its pairs cross a join whole" {
    const gpa = testing.allocator;
    var repo = try Points.repo() orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const R = pardes.replica;
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{});
    defer a.deinit();
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = Points.word }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    const ours = answered(a.core, a.core.panes[id].?.serial).?;
    const theirs = answered(r.core(), r.core().panes[id].?.serial).?;
    try testing.expectEqual(@as(usize, 2), ours.pins.len);
    try testing.expectEqualSlices(Line, ours.lines, theirs.lines);
    try testing.expectEqualStrings(ours.ghost_text, theirs.ghost_text);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
    try R.loadsAsSession(a, 2);
}

test "Compare asks jj on a worker: the word says so and returns, its answer lands as one input and pins its pairs; a client replays that input and ends equal" {
    var repo = try Points.repo() orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo, "");
    defer w.deinit();
    try w.word(Points.word);
    try testing.expect(answered(w.a.core, w.serial) == null);
    try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Compare: jj") != null);
    try w.land();
    try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len);
    try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines);
}