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
|
//! A file pane's text: its content and undo history, display columns, line
//! index, syntax highlights and the body it fills.
const panes = @import("panes.zig");
const std = @import("std");
const vaxis = @import("vaxis");
const builtin = @import("builtin");
const pardes = @import("root.zig");
const config = @import("config.zig");
const Pardes = pardes.Pardes;
const Surface = pardes.Surface;
const modal = @import("modal.zig");
const filesystem = @import("fs.zig");
const syntax = @import("syntax.zig");
const diff = @import("diff.zig");
const tracy = @import("tracy.zig");
const ansi = @import("ansi.zig");
const limits = @import("memory.zig").limits;
const locations = @import("locations.zig");
const Colors = @import("colors.zig");
const Tables = @import("Tables.zig");
const Stream = @import("Stream.zig");
const jj = @import("jj.zig");
const Pane = panes.Pane;
const Output = panes.Output;
const Mini = panes.mini;
const Text = panes.Text;
const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2;
const long_paint: usize = 16 << 10;
/// A rename (ninep/pane.zig nameBuffer): the name it ends, kept for an undo
/// back across it; `old` is the History's from here (owned), freed if it
/// cannot be kept.
pub fn noteRenamed(gpa: std.mem.Allocator, history: *History, old: []u8) void {
history.names.append(gpa, .{ .gen = history.gen, .path = old }) catch gpa.free(old);
history.gen +%= 1;
}
/// A file's undo, which its twins (Zerox) share: its edits as a journal
/// (Text.Journal), and the names it had.
pub const History = struct {
journal: Text.Journal = .{},
/// The names the file had, each with the rename generation it ended
/// (Text.Place.gen), and the generation now: no allocation a step, a
/// name is kept once, at its rename.
names: std.ArrayList(struct { gen: u32, path: []u8 }) = .empty,
gen: u32 = 0,
pub fn create(gpa: std.mem.Allocator) !*History {
const history = try gpa.create(History);
history.* = .{};
return history;
}
pub fn destroy(history: *History, gpa: std.mem.Allocator) void {
history.journal.deinit(gpa);
for (history.names.items) |name| gpa.free(name.path);
history.names.deinit(gpa);
gpa.destroy(history);
}
};
/// Owned syntax results: a text's declarations and symbols at a revision.
pub const ContextCache = struct {
/// Its revision is dumped and digested: a worker's parse is an input,
/// which a client joined since never saw, and a step reads what it
/// left (Query.ownerDecls, the Symbols source). The declarations and
/// symbols are made again from the text at a load (`reload`), with the
/// allocator that made them.
pub const replica = .{ .local = .{"allocator"}, .derived = .{ "declarations", "symbols" } };
allocator: ?std.mem.Allocator = null,
declarations: []syntax.ContextDeclaration = &.{},
symbols: []syntax.Symbol = &.{},
revision: ?u32 = null,
pub fn deinit(self: *ContextCache) void {
if (self.allocator) |gpa| {
gpa.free(self.declarations);
gpa.free(self.symbols);
}
self.* = .{};
}
/// A loaded text's (its revision the dump's): its context parsed
/// again where it is of the text it has.
pub fn reload(self: *ContextCache, gpa: std.mem.Allocator, path: []const u8, content: []const u8, revision: u32) void {
const at = self.revision orelse return;
if (at != revision) return;
self.replace(gpa, syntax.context(gpa, path, content) catch return, at);
}
/// Takes ownership of a context allocated by gpa.
pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, made: syntax.Context, revision: u32) void {
self.deinit();
self.* = .{ .allocator = gpa, .declarations = made.declarations, .symbols = made.symbols, .revision = revision };
}
};
/// A file pane's backing: owned content, its derived caches, and undo history.
pub const State = struct {
/// What the replay digest leaves out (core/walk.zig): what is made again
/// from the text whenever it is wanted.
// Syntax caches must not load through the dump loader's core allocator.
pub const replica = .{
.derived = .{ "cap", "line_starts", "line_cap", "widest", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" },
// Big texts, dumped and sent by their hash (core/walk.zig). The
// text is written in place by `replace`, but never while a join
// sends it (memory.zig `pin`): then an edit puts a new buffer in
// its place.
.blob = .{ "content", "location_rows" },
// Written in place in a replica's core too: its rollback copy keeps
// none of their bytes, and takes back what a speculation wrote
// (core/rollback.zig `Epoch.wrote`).
.journal = .{ "content", "line_starts" },
// Where the view's top is, held to its text (walk.zig `.place`);
// its row in that line is any (an edit leaves it past the line's
// rows, read as the last: `top`), as the session holds it.
.place = .{.{ "scroll", "lastLine" }},
};
/// The last line a view's top may be at: its text's. A clean file a
/// slim dump left the text of (dump.zig `Slim`, read from its file
/// again when it is revived) has a line a byte of what it saved at most,
/// in the rows a view counts (`Pane.wrap_line`).
pub fn lastLine(f: *const State) usize {
if (f.content.len == 0) if (f.saved_len) |n| return @min(n, std.math.maxInt(i32));
return modal.lineCount(f.content) -| 1;
}
path: []u8,
content: []u8,
/// The bytes `content`'s buffer has room for (0: as many as it holds):
/// an edit that must grow it grows it by an eighth more, so the keys
/// after it move no text but what follows them (`replace`).
cap: usize = 0,
revision: u32 = 0,
/// Revision last known to match disk, after Save or an external reload.
/// Equal means the screen matches disk.
saved_revision: u32 = 0,
/// The text at `saved_revision`, hashed as the first edit after it
/// replaces it: an edit that brings the text back to it is clean again,
/// as an undo to the save point is in acme.
saved_hash: ?u64 = null,
/// The length of the text `saved_hash` is of, when it is of one: an
/// edit to another length cannot be back to it, and is not hashed.
saved_len: ?usize = null,
watch_after_save: bool = false,
/// The file changed on disk under unsaved edits, which were kept (see
/// `changed`): its hash, so the same change is said once, until a Save
/// or get settles it. A Save warns once before overwriting it, as acme's
/// Put does (exec.c:577, "modified since last read").
disk_newer: ?u64 = null,
disk_newer_warned: bool = false,
/// Its file was deleted on disk: said once (`deleted`) until it is
/// written or found again.
disk_gone: bool = false,
/// Its text was read from, or written to, a file of this host's disk
/// at its path (not the served tree's, nor a name never saved): what
/// Recent keeps (Pardes.onDisk), learned where that read or write ran,
/// so a close asks the disk nothing.
on_disk: bool = false,
/// A +Pager pane (`pardes -`): no line numbers, its program's colours
/// through Filter until it is toggled off.
pager: bool = false,
/// A +Pager whose text is a diff (`git diff`, `show`, `log -p`): drawn
/// and looked at as a diff (Pane.colorAlgo).
pager_diff: bool = false,
/// A +Pager's colours, as its program printed them (Term.page): drawn
/// over its text by recolorSyntax, never read over 9P. ponytail: any
/// edit drops them (setContentSpan); shifting them through the splice,
/// as pane.zig's shiftOne moves dot, would keep them.
pager_spans: []pardes.Term.Span = &.{},
/// Seconds of the last content change, for the filesystem's stat; zero until edited.
mtime: u32 = 0,
/// Non-null for a generated output buffer rather than an on-disk file.
output: ?Output.State = null,
/// A directory pane's entries (Dir.zig), its output `.dir`.
listing: ?panes.Dir.State = null,
mini: ?Mini.State = null,
/// The view's top: the line its first row is of, and that row of the
/// line's wrapped rows (`Top`): each view's own (views.zig), digested,
/// dumped.
scroll: usize = 0,
scroll_row: u32 = 0,
/// `line_starts[i]` is line i's byte offset. Empty means not built yet.
line_starts: []usize = &.{},
/// The room `line_starts` has, as `cap` is `content`'s.
line_cap: usize = 0,
/// The widest any line is, found with the index and kept with it
/// (`Widest`): what tells a view whose rows are its lines (`oneRow`).
widest: Widest = .{},
/// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte.
highlights: []u8 = &.{},
location_rows: []locations.Row = &.{},
/// The last edit's splice: what the text at `revision` kept of the one
/// before it at either end (`old_len` long). A pane's places shift by it
/// rather than search the whole text again (Places.shift).
splice: struct { revision: u32 = 0, head: usize = 0, tail: usize = 0, old_len: usize = 0 } = .{},
highlight_start: usize = 0,
syntax_dirty: bool = true,
tree_context: bool = false,
context: ContextCache = .{},
/// The whole file's parse for the keys that walk its nodes (Alt-o and
/// kin), made on the first of them after an edit and kept until the next
/// one: `syntax.parseTree`'s, opaque here.
node_tree: ?*anyopaque = null,
node_tree_revision: u32 = 0,
/// The revision the tree's edits reach (`syntax.editTree`, told by
/// `edit` below): at `revision`, the next parse reuses it; else, a
/// revision it was not told of (a twin's edit, a reload), a parse anew.
node_tree_edits: u32 = 0,
/// helix's object_selections: what Alt-o grew from, for Alt-i to go back
/// to; gpa-owned ranges and the primary's index.
node_history: std.ArrayList(NodeStep) = .empty,
/// A markdown text's pipe tables, laid out in their rows (Tables.zig):
/// found again on the first body drawn after an edit.
tables: Tables = .{},
history: *History,
/// Zerox's group: the panes on one buffer share `content`, `history`
/// and (while it is the one index) `line_starts`, each with its own
/// scroll, cursor and syntax; 0, none. See `zerox`.
twin: u32 = 0,
/// In its twin group's Follow chain (builtins.Follow), whose panes
/// show the text as consecutive pages (followChain).
follow: bool = false,
/// Its `Changes` layer while it is shown (`Layer`); none while hidden.
layer: Layer = .{},
};
/// A buffer's `Changes` layer (jj.zig): whose, and its lines.
pub const Layer = struct {
/// The serial of the pane whose `Changes` answer its lines are the
/// ghosts of, in its order (jj.answered); 0, none shown.
owner: u32 = 0,
/// Its lines: read-only lines of the buffer, in order, gpa-owned (a
/// twin holds its own copy).
lines: []ReadOnly = &.{},
/// By hand, so that a file with no layer shown pays a length test:
/// nothing hashed (the walk's two fields cost two small hash updates
/// a pane a digest, a client's key 0.1% more). A shown one: its owner,
/// its lines.
pub fn digest(l: *const Layer, h: *pardes.walk.Hasher) void {
if (l.owner == 0 and l.lines.len == 0) return;
h.update(std.mem.asBytes(&l.owner));
pardes.walk.hash([]ReadOnly, &l.lines, h);
}
};
/// A read-only line of a pane's buffer: one of its `Changes` layer's (a
/// line a change took away, a changed line's old text, a change's
/// description: jj.zig `Ghost`), its bytes `content[at..][0..len]`, its
/// text and its `\n` (`lead`: after the last line of a text that ends
/// with none, its `\n` first). Regular text to everything that reads the
/// buffer (a motion, a selection, a search, a Look); the file's text is the
/// buffer less them (`fileText`); an edit touching one is refused whole
/// (`edit`).
pub const ReadOnly = struct {
at: usize,
len: usize,
/// The file's line it stands before, from 0 (the file's line count:
/// after its last).
line: u32,
lead: bool = false,
};
/// THE FILE'S TEXT: the buffer less its read-only lines, the one way to it.
/// Whatever reads "the file" (a Save, `body` over 9P, the dirty check, the
/// language server, the syntax parse, jj, a reread's comparison) asks this,
/// never `content`, which is the buffer the drawing and the editing read:
/// the buffer itself while it has none (a file with no layer pays nothing),
/// else a copy in `arena`.
pub fn fileText(f: *const State, arena: std.mem.Allocator) error{OutOfMemory}![]const u8 {
if (f.layer.lines.len == 0) return f.content;
const out = try arena.alloc(u8, fileLen(f));
var parts: FileParts = .{ .f = f };
var n: usize = 0;
while (parts.next()) |part| {
@memcpy(out[n..][0..part.len], part);
n += part.len;
}
return out;
}
/// The file's text's length (`fileText`).
pub fn fileLen(f: *const State) usize {
var n = f.content.len;
for (f.layer.lines) |r| n -= r.len;
return n;
}
/// The file's text a stretch at a time, the buffer between its read-only
/// lines (`fileText` without the copy).
pub const FileParts = struct {
f: *const State,
i: usize = 0,
at: usize = 0,
done: bool = false,
pub fn next(it: *FileParts) ?[]const u8 {
if (it.done) return null;
const ro = it.f.layer.lines;
if (it.i == ro.len) {
it.done = true;
return it.f.content[it.at..];
}
const part = it.f.content[it.at..ro[it.i].at];
it.at = ro[it.i].at + ro[it.i].len;
it.i += 1;
return part;
}
};
/// Whether the file's text is `bytes` (`fileText` without the copy).
pub fn fileEql(f: *const State, bytes: []const u8) bool {
if (fileLen(f) != bytes.len) return false;
var parts: FileParts = .{ .f = f };
var at: usize = 0;
while (parts.next()) |part| {
if (!std.mem.eql(u8, part, bytes[at..][0..part.len])) return false;
at += part.len;
}
return true;
}
/// The file's text hashed (Wyhash, as `std.hash.Wyhash.hash(0, text)`):
/// what the dirty check compares, never a copy.
pub fn fileHash(f: *const State) u64 {
if (f.layer.lines.len == 0) return std.hash.Wyhash.hash(0, f.content);
var h = std.hash.Wyhash.init(0);
var parts: FileParts = .{ .f = f };
while (parts.next()) |part| h.update(part);
return h.final();
}
/// A buffer offset as the file's: less the read-only lines before it; one
/// inside a read-only line, after the file line above it (where the line
/// it stands before starts).
pub fn fileOffset(f: *const State, at: usize) usize {
var less: usize = 0;
for (f.layer.lines) |r| {
if (r.lead) {
if (at <= r.at) break;
if (at <= r.at + r.len) return r.at - less;
} else {
if (at < r.at) break;
if (at < r.at + r.len) return r.at - less;
}
less += r.len;
}
return at - less;
}
/// A file offset as the buffer's: a line's start after the read-only lines
/// standing before it (`:N`, a Look, a language server's place land on the
/// file's line, never on one of the layer's); `end`, a range's end, before
/// them (a range of the file's lines holds none of the layer's after it).
pub fn bufferOffset(f: *const State, at: usize, end: bool) usize {
var more: usize = 0;
for (f.layer.lines) |r| {
const place = r.at - more;
if (if (r.lead or end) place >= at else place > at) break;
more += r.len;
}
return at + more;
}
/// A buffer row as the file's: a read-only line's, the file line it stands
/// before.
pub fn fileRow(f: *const State, row: usize) usize {
var less: usize = 0;
for (f.layer.lines, 0..) |r, k| {
const at = r.line + k;
if (at > row) break;
if (at == row) return r.line;
less += 1;
}
return row - less;
}
/// A file row as the buffer's: after the read-only lines standing before it.
pub fn bufferRow(f: *const State, row: usize) usize {
var more: usize = 0;
for (f.layer.lines) |r| {
if (r.line > row) break;
more += 1;
}
return row + more;
}
/// Which read-only line buffer row `row` is (its place in `read_only`),
/// null for a line of the file.
pub fn readOnlyRow(f: *const State, row: usize) ?usize {
for (f.layer.lines, 0..) |r, k| {
const at = r.line + k;
if (at == row) return k;
if (at > row) return null;
}
return null;
}
/// Whether the edit putting `bytes` over the `len` bytes at `off` touches
/// a read-only line: changes a byte of one, puts any in at its start or
/// inside it, or leaves it on the end of a line above it (an edit ending
/// where one starts must leave a line's end before it: a line deleted
/// whole above one is the file's edit; a `J` into one is not).
fn touchesReadOnly(f: *const State, off: usize, len: usize, bytes: []const u8) bool {
for (f.layer.lines) |r| {
const lo = r.at;
const hi = r.at + r.len;
if (lo > off + len) break;
if (off < hi and off + len > lo) return true;
if (r.lead) {
if (len == 0 and off > lo and off <= hi) return true;
} else {
if (len == 0 and off >= lo and off < hi) return true;
if (len > 0 and off + len == lo) {
const ends_line = if (bytes.len > 0) bytes[bytes.len - 1] == '\n' else off == 0 or f.content[off - 1] == '\n';
if (!ends_line) return true;
}
}
}
return false;
}
/// What an edit refused for a read-only line says (`edit`).
pub const read_only_said = "a change's line is read-only: nothing edited (Changes hides them)";
pub const NodeStep = @import("Editor.zig").NodeStep;
pub fn graphemeDisplayWidth(tab: u16, grapheme: []const u8) usize {
if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1;
if (std.mem.eql(u8, grapheme, "\t")) return tab;
if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode)));
// vaxis's gwidth counts back a replacement rune's 3 bytes over the one
// invalid byte it stood for (`\xee` before `e\u{301}` overflowed it):
// each invalid byte is a cell, as surface.zig draws it, and each valid
// run between is measured alone.
var width: usize = 0;
var run: usize = 0;
var i: usize = 0;
while (i < grapheme.len) {
const n = std.unicode.utf8ByteSequenceLength(grapheme[i]) catch 0;
if (n > 0 and i + n <= grapheme.len and std.unicode.utf8ValidateSlice(grapheme[i .. i + n])) {
i += n;
continue;
}
if (run < i) width += vaxis.gwidth.gwidth(grapheme[run..i], .unicode);
width += 1;
i += 1;
run = i;
}
if (run < grapheme.len) width += vaxis.gwidth.gwidth(grapheme[run..], .unicode);
return @max(1, width);
}
pub fn displayWidth(tab: u16, text: []const u8) usize {
var width: usize = 0;
var at: usize = 0;
while (at < text.len) {
const end = modal.nextGrapheme(text, at);
width +|= graphemeDisplayWidth(tab, text[at..end]);
at = end;
}
return width;
}
/// Source byte at a zero-based display column. Every cell occupied by a tab
/// maps back to that one tab byte.
pub fn byteAtDisplay(tab: u16, text: []const u8, display_col: usize) usize {
var col: usize = 0;
var at: usize = 0;
while (at < text.len) {
const end = modal.nextGrapheme(text, at);
const next = col +| graphemeDisplayWidth(tab, text[at..end]);
if (display_col < next) return at;
col = next;
at = end;
}
return text.len;
}
/// File cursor columns may live past EOL. Tabs expand before that boundary;
/// every virtual column after it remains one screen cell.
pub fn rawDisplayCol(tab: u16, line_text: []const u8, raw_col: usize) usize {
const bounded = modal.graphemeStart(line_text, @min(raw_col, line_text.len));
return displayWidth(tab, line_text[0..bounded]) +| (raw_col -| line_text.len);
}
/// Walked only as far as the column: a row's last byte, a million bytes
/// into a line, is found without measuring the rest of it. Only a line
/// that ends before the column is measured whole (it is short).
pub fn rawAtDisplay(tab: u16, line_text: []const u8, display_col: usize) usize {
const at = byteAtDisplay(tab, line_text, display_col);
if (at < line_text.len) return at;
return line_text.len +| (display_col -| displayWidth(tab, line_text));
}
pub fn byteAtDisplayFrom(tab: u16, line_text: []const u8, from_raw: usize, display_col: usize) usize {
if (from_raw >= line_text.len) return from_raw +| display_col;
const from = modal.graphemeStart(line_text, from_raw);
return from +| rawAtDisplay(tab, line_text[from..], display_col);
}
/// The display columns from `from_raw` to `to_raw` on a line. Widths add
/// (a tab is `tab_width` wherever it stands), so only the text between
/// the two is measured, never the line from its start: a selection a
/// million bytes into a line draws as fast as one at its start.
pub fn lineDisplayOffset(tab: u16, line_text: []const u8, from_raw: usize, to_raw: usize) i32 {
const lo = @min(from_raw, to_raw);
const hi = @max(from_raw, to_raw);
const a = modal.graphemeStart(line_text, @min(lo, line_text.len));
const b = modal.graphemeStart(line_text, @min(hi, line_text.len));
const past = (hi -| line_text.len) - (lo -| line_text.len);
const width: usize = displayWidth(tab, line_text[a..b]) +| past;
return if (to_raw >= from_raw) @intCast(width) else -@as(i32, @intCast(width));
}
pub fn lineDisplayEndOffset(tab: u16, line_text: []const u8, from_raw: usize, at_raw: usize) i32 {
const start = lineDisplayOffset(tab, line_text, from_raw, at_raw);
if (at_raw >= line_text.len) return start;
const at = modal.graphemeStart(line_text, at_raw);
const end = modal.nextGrapheme(line_text, at);
return start + @as(i32, @intCast(graphemeDisplayWidth(tab, line_text[at..end]))) - 1;
}
pub fn sourceLine(pane: *const Pane, row: i32) []const u8 {
const f = if (pane.file) |*file| file else return "";
if (row < 0) return "";
const line: usize = @intCast(row);
if (f.line_starts.len == 0) return modal.lineSlice(f.content, line);
if (line >= f.line_starts.len) return "";
const start = f.line_starts[line];
const end = if (line + 1 < f.line_starts.len) f.line_starts[line + 1] - 1 else f.content.len;
return f.content[start..end];
}
/// The pads `row` is laid out with in this pane: a row of a markdown
/// table (Tables.zig) of its text as it is now, when the table fits the
/// width a wrapping body has (a wider one is shown as its source, wrapped);
/// else none. Every mapping between a file row's bytes and its cells goes
/// through here, so the drawn row, the caret and a click cannot disagree.
pub fn rowPads(tab: u16, pane: *const Pane, row: i32, out: *[Tables.max_pads]Tables.Pad) []const Tables.Pad {
const table = rowTable(pane, row) orelse return &.{};
return pane.file.?.tables.padsOf(tab, table, @intCast(row), sourceLine(pane, row), out);
}
/// The table `row` is laid out in, in this pane (`rowPads`).
pub fn rowTable(pane: *const Pane, row: i32) ?*const Tables.Table {
const f = if (pane.file) |*file| file else return null;
if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return null;
const table = f.tables.find(@intCast(row)) orelse return null;
const width = wrapWidth(pane, pane.view.wrap);
if (width > 0 and table.width > width) return null;
return table;
}
pub fn displayOffset(tab: u16, pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 {
const line_text = sourceLine(pane, row);
const from: usize = @intCast(@max(0, from_raw));
const to: usize = @intCast(@max(0, to_raw));
var buf: [Tables.max_pads]Tables.Pad = undefined;
return lineDisplayOffset(tab, line_text, from, to) + Tables.between(rowPads(tab, pane, row, &buf), from, to);
}
pub fn displayEndOffset(tab: u16, pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 {
const line_text = sourceLine(pane, row);
const from: usize = @intCast(@max(0, from_raw));
const at: usize = @intCast(@max(0, at_raw));
var buf: [Tables.max_pads]Tables.Pad = undefined;
return lineDisplayEndOffset(tab, line_text, from, at) + Tables.between(rowPads(tab, pane, row, &buf), from, at);
}
pub fn byteAtRowDisplay(tab: u16, pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 {
const line_text = sourceLine(pane, row);
var buf: [Tables.max_pads]Tables.Pad = undefined;
const pads = rowPads(tab, pane, row, &buf);
if (pads.len > 0) return @intCast(Tables.byteAt(tab, line_text, pads, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col))));
return @intCast(byteAtDisplayFrom(tab, line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col))));
}
/// The slot after a text's last newline: a line the cursor can sit on that
/// is not there yet. Its gutter shows `~` for a number, as helix's does.
pub fn endSlot(pane: *const Pane, row: usize) bool {
const f = if (pane.file) |*file| file else return false;
return row > 0 and row + 1 == f.line_starts.len and f.line_starts[row] == f.content.len;
}
pub fn gutterWidth(pane: *const Pane) u16 {
if (pane.file == null) return 0;
const file = &pane.file.?;
// A +Pager, and a +Diff (hunks.zig), show no line numbers, as a
// pager and delta show none.
if (file.pager) return 0;
if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0;
// A query pane's rows carry their own line numbers (Query.zig).
if (pane.query != null) return 0;
// The file's lines: the layer's have no number.
var lines = (if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content)) - file.layer.lines.len;
var digits: u16 = 1;
while (lines >= 10) : (lines /= 10) digits += 1;
return @max(config.PREFIX_W, digits + 1) + laneCells(pane) + pane.layers.heat;
}
/// The cells the changes' lanes take after the line number in this view
/// (File.Layers), none while it pins no changes.
pub fn laneCells(pane: *const Pane) u16 {
return pane.layers.lanes;
}
/// Convert between rendered cells and UTF-8 byte columns. Tag rows always
/// need grapheme conversion; file body rows additionally skip the gutter.
pub fn renderedLineByteCol(tab: u16, pane: *const Pane, row: i32, line_text: []const u8, display_col: usize) usize {
if (row < pane.tag_rows) return rawAtDisplay(tab, line_text, display_col);
if (pane.file == null) return rawAtDisplay(tab, line_text, display_col);
const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len);
if (display_col <= prefix) return display_col;
return prefix +| rawAtDisplay(tab, line_text[prefix..], display_col - prefix);
}
pub fn renderedLineDisplayCol(tab: u16, pane: *const Pane, row: i32, line_text: []const u8, byte_col: usize) usize {
if (row < pane.tag_rows) return rawDisplayCol(tab, line_text, byte_col);
if (pane.file == null) return rawDisplayCol(tab, line_text, byte_col);
const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len);
if (byte_col <= prefix) return byte_col;
return prefix +| rawDisplayCol(tab, line_text[prefix..], byte_col - prefix);
}
pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize {
var end = start;
var used: usize = 0;
// A vector of printable ASCII at a time, a cell a byte, while the width
// is past it and the byte after it is ASCII too: what the loop below
// takes a byte at a time (it leaves the ASCII byte a non-ASCII one
// follows to the grapheme walk). Every row walk is this loop.
while (used + lanes < width and end + lanes < text.len and text[end + lanes] < 0x80) {
const v: Lanes = text[end..][0..lanes].*;
if (@reduce(.Or, v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)))) break;
used += lanes;
end += lanes;
}
// The rest of a row of printable ASCII in one vector more: its bytes and
// the two after them printable ASCII, the row ends where the width does
// (what the loops below find a byte at a time).
if (used < width and width - used + 2 <= lanes and end + lanes <= text.len) {
const v: Lanes = text[end..][0..lanes].*;
const bad: @Int(.unsigned, lanes) = @bitCast(v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)));
if (@ctz(bad) >= width - used + 2) return end + (width - used);
}
while (used < width and end < text.len) {
const b = text[end];
if (b < 0x20 or b >= 0x7f) break;
if (end + 1 < text.len and text[end + 1] >= 0x80) break;
used += 1;
end += 1;
}
// A full row before a printable ASCII byte no non-ASCII byte follows (a
// grapheme of its own, a cell wide): the row ends there, nothing walked
// (every wrapped row ends so, and the walk cost a row a hundred more).
if (used == width and end > start and end < text.len and text[end] -% 0x20 < 0x5f and (end + 1 == text.len or text[end + 1] < 0x80)) return end;
while (end < text.len) {
const next_end = modal.nextGrapheme(text, end);
const next_used = used +| graphemeDisplayWidth(tab, text[end..next_end]);
if (next_used > width) return if (end == start) next_end else end;
used = next_used;
end = next_end;
}
return end;
}
pub const lineCount = modal.cursorLineCount;
// Content changes invalidate this lazily rebuilt byte-offset index.
pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize {
if (f.line_starts.len > 0) return f.line_starts;
// Exact allocation: deinitPane frees `line_starts` itself, so the stored
// slice must span the complete allocation rather than spare capacity.
const found = countLines(f.content);
const starts = try gpa.alloc(usize, found.newlines + 1);
starts[0] = 0;
f.widest = .{ .bytes = fillLines(f.content, 0, starts[1..]), .tabbed = found.tabbed };
f.line_starts = starts;
f.line_cap = 0;
return starts;
}
/// The widest a text's lines are, at most: the most bytes between two
/// newlines, and whether a tab is among them. A tab is `tab` cells, any
/// other byte at most one (graphemeDisplayWidth), so a line is never
/// wider than its bytes, times the tab width where a tab may be. Made
/// with the line index and kept by its edits, only ever made wider: an
/// edit taking the widest line away leaves it so (`oneRow` then walks,
/// and finds the same rows).
pub const Widest = struct {
bytes: usize = 0,
tabbed: bool = false,
fn cells(w: Widest, tab: u16) usize {
return if (w.tabbed) w.bytes *| @max(tab, 1) else w.bytes;
}
};
const lanes = std.simd.suggestVectorLength(u8) orelse 16;
const Lanes = @Vector(lanes, u8);
/// The newlines in `bytes` and whether a tab is among them: a lane's own
/// sum a vector, added up every 255 (std.mem.count's popcount of a mask is
/// a dozen instructions a vector on a baseline x86-64).
fn countLines(bytes: []const u8) struct { newlines: usize, tabbed: bool } {
const one: Lanes = @splat(1);
const zero: Lanes = @splat(0);
var newlines: usize = 0;
var tabs = zero;
var i: usize = 0;
while (bytes.len - i >= lanes) {
var sums = zero;
for (0..@min((bytes.len - i) / lanes, 255)) |_| {
const v: Lanes = bytes[i..][0..lanes].*;
sums += @select(u8, v == @as(Lanes, @splat('\n')), one, zero);
tabs |= @select(u8, v == @as(Lanes, @splat('\t')), one, zero);
i += lanes;
}
newlines += @reduce(.Add, @as(@Vector(lanes, u16), sums));
}
var tabbed = @reduce(.Or, tabs) != 0;
for (bytes[i..]) |b| {
newlines += @intFromBool(b == '\n');
tabbed = tabbed or b == '\t';
}
return .{ .newlines = newlines, .tabbed = tabbed };
}
/// The start after each newline of `bytes` (its byte `off` past it) into
/// `out`, a vector at a time, a newline's place off its mask (a search for
/// each cost a short line ~57 instructions); and the most bytes of `bytes`
/// between two newlines or an end.
fn fillLines(bytes: []const u8, off: usize, out: []usize) usize {
const Mask = @Int(.unsigned, lanes);
var n: usize = 0;
var from: usize = 0;
var widest: usize = 0;
var i: usize = 0;
while (i + lanes <= bytes.len) : (i += lanes) {
const v: Lanes = bytes[i..][0..lanes].*;
var nl: Mask = @bitCast(v == @as(Lanes, @splat('\n')));
while (nl != 0) : (nl &= nl - 1) {
const at = i + @ctz(nl);
widest = @max(widest, at - from);
from = at + 1;
out[n] = off + from;
n += 1;
}
}
for (bytes[i..], i..) |b, at| if (b == '\n') {
widest = @max(widest, at - from);
from = at + 1;
out[n] = off + from;
n += 1;
};
return @max(widest, bytes.len - from);
}
/// The whole buffer of a text's bytes, its room past them included.
fn textRoom(f: *const State) []u8 {
return f.content.ptr[0..@max(f.cap, f.content.len)];
}
/// The whole buffer of a text's line index, as `textRoom` is its text's.
fn indexRoom(f: *const State) []usize {
return f.line_starts.ptr[0..@max(f.line_cap, f.line_starts.len)];
}
/// `std.sort`'s order for offsets: a key against an item.
fn ascending(key: usize, item: usize) std.math.Order {
return std.math.order(key, item);
}
/// The bytes a splice left alone at either end, when its caller knows them.
pub const Span = struct { head: usize, tail: usize };
/// `f`'s line index through the edit that puts `bytes` over the `len` bytes
/// at `off` (`shiftStarts`), in its own buffer, grown by an eighth more when
/// it must be. On no memory the index goes, to be made again when it is
/// asked for.
fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: []const u8) void {
const starts = f.line_starts;
const room = indexRoom(f);
const first = std.sort.upperBound(usize, starts, off, ascending);
const found = countLines(bytes);
const added = found.newlines;
const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - first) + added;
var out = room;
if (n > room.len) {
out = gpa.alloc(usize, n + @max(n / 8, 512)) catch {
pardes.memory.freeRaw(gpa, room);
f.line_starts = &.{};
f.line_cap = 0;
return;
};
@memcpy(out[0..starts.len], starts);
} else pardes.rollback.Epoch.wrote(gpa, usize, room, starts.len, n, off, f.content[off..][0..len], bytes.len);
const inside = shiftStarts(out, starts.len, n, off, len, bytes);
if (out.ptr != room.ptr) pardes.memory.freeRaw(gpa, room);
f.line_starts = out[0..n];
f.line_cap = out.len;
// The widest: what the edit put in, and the two lines it joined at
// its ends (the line `off` is on, the one its last newline starts).
const total = f.content.len - len + bytes.len;
const ends = [2]usize{ first - 1, first - 1 + added };
var widest = @max(f.widest.bytes, inside);
for (ends) |l| widest = @max(widest, (if (l + 1 < n) f.line_starts[l + 1] - 1 else total) - f.line_starts[l]);
f.widest = .{ .bytes = widest, .tabbed = f.widest.tabbed or found.tabbed };
}
/// The first `len` of `room`, a line index, through the edit that puts
/// `bytes` over the `cut` bytes at `off`, in place, `n` long after it
/// (`room` holds that): the starts before the edit stand, those it took
/// out go, its newlines' come in, and those after it move by what it added;
/// only the moving is a pass over the index, and only from the edit on. The
/// edit turned round (`cut` its length in, `bytes` what it took out) gives
/// the index before it back: a rollback's (core/rollback.zig `unwrite`).
/// The most bytes of `bytes` between two newlines or an end (fillLines).
pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) usize {
const starts = room[0..len];
const kept = std.sort.upperBound(usize, starts, off, ascending);
const moved = len - std.sort.upperBound(usize, starts, off + cut, ascending);
const from = len - moved;
const to = n - moved;
// The starts that move go back to front when the edit grew the index,
// front to back when it shrank it.
if (to > from) {
var k = moved;
while (k > 0) {
k -= 1;
room[to + k] = room[from + k] - cut + bytes.len;
}
} else for (0..moved) |k| {
room[to + k] = room[from + k] - cut + bytes.len;
}
return fillLines(bytes, off, room[kept..]);
}
/// line count, O(1) once the index is warm
pub fn nlines(gpa: std.mem.Allocator, f: *State) usize {
const idx = lineIndex(gpa, f) catch return lineCount(f.content);
return idx.len;
}
/// byte offset of line `row`, or content.len past the end — modal
/// .lineStartOffset's contract exactly, without its walk
pub fn lineStart(gpa: std.mem.Allocator, f: *State, row: usize) usize {
const idx = lineIndex(gpa, f) catch return modal.lineStartOffset(f.content, row);
return if (row >= idx.len) f.content.len else idx[row];
}
pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const []const u8 {
const index = try lineIndex(pane.gpa, f);
const lines = try arena.alloc([]const u8, index.len);
for (index, 0..) |start, i| {
const end = if (i + 1 < index.len) index[i + 1] - 1 else f.content.len;
lines[i] = f.content[start..end];
}
return lines;
}
/// Use the file's line index only when `text` is its complete live content.
/// Edit-buffer fragments and other temporary text retain modal's scan path.
fn contentIndex(t: *Text, text: []const u8) ?[]const usize {
if (t.what != .body) return null;
const pane = t.pane() orelse return null;
const f = if (pane.file) |*file| file else return null;
if (text.ptr != f.content.ptr or text.len != f.content.len) return null;
return lineIndex(pane.gpa, f) catch null;
}
pub fn textOffset(t: *Text, text: []const u8, cursor: modal.Cursor) usize {
const index = contentIndex(t, text) orelse return modal.offsetAt(text, cursor);
const row = @min(cursor.row, index.len - 1);
const start = index[row];
const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len;
return start + modal.graphemeStart(text[start..end], @min(cursor.col, end - start));
}
pub fn textLineStart(t: *Text, text: []const u8, row: usize) usize {
const index = contentIndex(t, text) orelse return modal.lineStartOffset(text, row);
return if (row >= index.len) text.len else index[row];
}
pub fn textLine(t: *Text, text: []const u8, row: usize) []const u8 {
const index = contentIndex(t, text) orelse return modal.lineSlice(text, row);
if (row >= index.len) return "";
const start = index[row];
const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len;
return text[start..end];
}
pub fn textLineCount(t: *Text, text: []const u8) usize {
const index = contentIndex(t, text) orelse return modal.cursorLineCount(text);
return index.len;
}
pub fn textPosition(t: *Text, text: []const u8, offset: usize) modal.Cursor {
const index = contentIndex(t, text) orelse return modal.positionAt(text, offset);
const bounded = @min(offset, text.len);
const row = std.sort.upperBound(usize, index, bounded, ascending) - 1;
const start = index[row];
const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len;
return .{ .row = row, .col = modal.graphemeStart(text[start..end], @min(bounded - start, end - start)) };
}
pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane {
std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]);
const path_copy = try p.gpa.dupe(u8, path);
errdefer p.gpa.free(path_copy);
const pane = try panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h);
errdefer p.gpa.destroy(pane);
const history = try History.create(p.gpa);
errdefer p.gpa.destroy(history);
p.reserved_slots[id] = true;
defer p.reserved_slots[id] = false;
const content = try filesystem.read(p, path);
errdefer p.gpa.free(content);
const total = lineCount(content);
const scroll: usize = if (line > 0 and line <= total) line - 1 else 0;
pane.file = .{ .path = path_copy, .content = content, .scroll = scroll, .history = history, .on_disk = filesystem.localPath(path) != null };
pane.body.cur_pinned = true;
pane.body.cur_row = @intCast(scroll);
p.installPane(id, pane);
if (filesystem.localPath(path) != null) {
p.emit(.{ .watch = .{ .pane = .at(id), .on = true } });
// Its language's server started now, off the loop: the first
// question asked of it finds it ready. Not a picker's preview's,
// which opens no pane (Pick.preview).
p.emit(.{ .lsp_open = .{ .pane = .at(id) } });
}
return pane;
}
pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void {
if (file.output == null) for (p.panes, 0..) |slot, id| {
if (slot == pane) p.emit(.{ .watch = .{ .pane = .at(id), .on = false } });
};
// A twin's text, undo and shared index stay with the twins left.
var twins: [pardes.MAX_PANES]usize = undefined;
const ntwins = twinsOf(p, file, &twins);
const index_shared = for (twins[0..ntwins]) |id| {
if (p.panes[id].?.file.?.line_starts.ptr == file.line_starts.ptr) break true;
} else false;
p.gpa.free(file.path);
// Raw, as every text is freed (a replica's rollback copy keeps the
// buffers it was taken over, core/rollback.zig, and a safe build's free
// writes over what it frees).
if (ntwins == 0) pardes.memory.freeRaw(p.gpa, textRoom(file));
if (file.listing) |listing| p.gpa.free(listing.names);
if (file.mini) |*mini| mini.deinit(p.gpa);
if (file.line_starts.len > 0 and !index_shared) pardes.memory.freeRaw(p.gpa, indexRoom(file));
if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights);
p.gpa.free(file.pager_spans);
p.gpa.free(file.layer.lines);
locations.freeRows(p.gpa, file.location_rows);
file.context.deinit();
if (file.node_tree) |tree| syntax.freeTree(tree);
for (file.node_history.items) |step| p.gpa.free(step.ranges);
file.node_history.deinit(p.gpa);
file.tables.deinit(p.gpa);
if (ntwins > 0) return;
file.history.destroy(p.gpa);
}
/// The edit `replace` makes told to the event readers, before it is made:
/// in the file's text, by its offsets.
fn reportEdit(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) void {
if (p.fs.listeners == 0) return;
const id = for (p.panes, 0..) |slot, i| {
const pane = slot orelse continue;
if (pane.file) |*state| if (state == f) break i;
} else return;
const text = fileText(f, p.scratch.allocator()) catch return;
pardes.ctlfs.events.noteEdit(p, id, false, text, fileOffset(f, off), len, bytes);
}
pub fn setContent(p: *Pardes, f: *State, new: []u8) void {
setContentSpan(p, f, new, null);
}
/// `rows`, a row a line of the text from its first (where each points, how
/// it is coloured: locations.Row), made the pane's, taken: the one way a
/// pane's rows are set, by a producer in the editor (Output.fillRows, a
/// query pane) or from outside (the pane's `rows` file). RowsMismatch, the
/// rows still the caller's, for rows the text cannot hold: more of them
/// than it has lines, or an offset or styles past its line's end. Rows
/// equal to the pane's keep its painting; others drop it, to be painted
/// from them. An edit of the text drops them (setContentSpan).
pub fn setRows(p: *Pardes, f: *State, rows: []locations.Row) error{RowsMismatch}!void {
var lines = std.mem.splitScalar(u8, f.content, '\n');
for (rows) |row| {
const line = lines.next() orelse return error.RowsMismatch;
if (row.location_end > line.len or row.code_start > line.len or row.colors.len > line.len - row.code_start) return error.RowsMismatch;
}
if (locations.equalRows(f.location_rows, rows)) return locations.freeRows(p.gpa, rows);
locations.freeRows(p.gpa, f.location_rows);
f.location_rows = rows;
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = &.{};
f.highlight_start = 0;
f.syntax_dirty = true;
}
/// `setContent` for a splice that knows what it left alone at either end,
/// so it is not found again by comparing the whole text. The edit is what
/// lies between them, made by `edit`, which takes `new`, a whole text its
/// caller made anyway, as the text's buffer.
pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void {
var span = span_in orelse spanOf(f.content, new);
if (f.layer.lines.len > 0) span = clearOfReadOnly(f, new, span);
if (edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, true, null, .edit)) return;
// Refused (read-only text, said) or no memory: `new` kept until the
// next such, as the editor keeps a text it made (edit.zig
// retireEditText): its caller may still read it.
if (p.retired_edit) |old| p.gpa.free(old);
p.retired_edit = new;
}
/// Of the splices that make `new` of the buffer, one that touches no
/// read-only line when the shortest (`span`, what it keeps at either end)
/// does: the editor's whole new text says what it changed only by the
/// bytes, and the shortest splice can run into a line of the layer's where
/// the edit did not (`a();` deleted above ` b();`, both starting with
/// four blanks, is the splice `a();\n `; it is also ` a();\n`).
/// Searched back from the shortest's head, a page of bytes at most.
fn clearOfReadOnly(f: *const State, new: []const u8, span: Span) Span {
const old = f.content;
if (!touchesReadOnly(f, span.head, old.len - span.head - span.tail, new[span.head .. new.len - span.tail])) return span;
const n = @min(old.len, new.len);
// The whole tail they share (`spanOf`'s stops at its head).
var shared: usize = 0;
while (shared < n and old[old.len - 1 - shared] == new[new.len - 1 - shared]) shared += 1;
// Never back across a read-only line: an edit made on one (a paste
// below it) is no edit of the line above it.
var floor: usize = 0;
for (f.layer.lines) |r| {
if (r.at + r.len > span.head) break;
floor = r.at + r.len;
}
var head = span.head;
while (head > floor and span.head - head < 4096) {
head -= 1;
const tail = @min(shared, n - head);
if (!touchesReadOnly(f, head, old.len - head - tail, new[head .. new.len - tail])) return .{ .head = head, .tail = tail };
}
return span;
}
/// The one change a text takes: the `len` bytes at `off` replaced by
/// `bytes`, in its own buffer, so an edit costs its bytes and what follows
/// them, never a copy of the text. False with no memory for it, or for an
/// edit of read-only text (said), and nothing changed.
pub fn replace(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) bool {
return edit(p, f, off, len, bytes, null, true, null, .edit);
}
/// What an edit is (`edit`): the editor's, of the buffer (refused where
/// it touches read-only text); a program's new text for the file (`load`:
/// never refused); the layer's lines going in or out (`jj.showLayer`:
/// nothing that reads the file hears of it).
pub const How = enum { edit, load, layer };
/// A new text for the FILE, `new` (owned), from what is not an edit of
/// the buffer: a Get, a reread from the disk, a language server's edits:
/// never refused for the layer's lines, which leave the buffer around it
/// and come back where the file's lines they stood before went (jj.edited
/// carries them).
pub fn load(p: *Pardes, f: *State, new: []u8) void {
const layer = f.layer.owner;
if (layer != 0) jj.hideLayer(p, f);
defer if (layer != 0) jj.showLayer(p, f, layer);
const span = spanOf(f.content, new);
if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, true, null, .load)) pardes.memory.freeRaw(p.gpa, new);
}
/// `replace` of the file's `len` bytes at `off` (its own offsets, `body`
/// over 9P's), as `load` is a new text: the layer's lines out and back.
pub fn replaceFile(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) bool {
const layer = f.layer.owner;
if (layer != 0) jj.hideLayer(p, f);
defer if (layer != 0) jj.showLayer(p, f, layer);
return replace(p, f, off, len, bytes);
}
/// `f`'s buffer made `new` (owned) with the read-only lines `spans` (owned)
/// of pane `layer`'s layer, or none (`layer` 0): the layer's lines in or
/// out (jj.showLayer, jj.hideLayer). No edit of the file: nothing that
/// reads it hears of it (no undo step, no event, the text as clean as it
/// was, its declarations its own), and every view of every pane on the
/// buffer keeps its place in the file (`fileOffset`), so one in a line that
/// leaves goes to the start of the file line it stood before, and one at a
/// line's start stays on that line. False with no memory, nothing changed.
pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) bool {
const arena = p.scratch.allocator();
// Each twin its own copy of the read-only lines, made first: a twin
// without them would read the layer's lines as the file's.
var twins: [pardes.MAX_PANES]usize = undefined;
const ntwins = twinsOf(p, f, &twins);
var copies: [pardes.MAX_PANES][]ReadOnly = undefined;
for (0..ntwins) |i| copies[i] = p.gpa.dupe(ReadOnly, spans) catch {
for (copies[0..i]) |c| p.gpa.free(c);
return false;
};
// Every place on the buffer, as the file's offsets: a cursor, a
// selection's anchor and ranges in the live view, a cursor and a top
// line in the others.
const Place = struct { row: *i32, col: *i32, at: usize };
const Kept = struct { line: *usize, at: usize };
var places: std.ArrayList(Place) = .empty;
var tops: std.ArrayList(Kept) = .empty;
const At = struct {
fn of(q: *Pardes, g: *State, row: i32, col: i32) usize {
const r: usize = @intCast(@max(0, row));
const start = lineStart(q.gpa, g, r);
const end = if (r + 1 < nlines(q.gpa, g)) lineStart(q.gpa, g, r + 1) - 1 else g.content.len;
return fileOffset(g, @min(@max(start, end), start + @as(usize, @intCast(@max(0, col)))));
}
};
for (p.panes) |slot| {
const pane = slot orelse continue;
const tf = if (pane.file) |*file| file else continue;
if (tf != f and (f.twin == 0 or tf.twin != f.twin)) continue;
const b = &pane.body;
places.append(arena, .{ .row = &b.cur_row, .col = &b.cur_col, .at = At.of(p, f, b.cur_row, b.cur_col) }) catch return false;
if (b.vsel.active) places.append(arena, .{ .row = &b.vsel.row, .col = &b.vsel.col, .at = At.of(p, f, b.vsel.row, b.vsel.col) }) catch return false;
for (b.sels[0..b.nsel]) |*sr| {
places.append(arena, .{ .row = &sr.row, .col = &sr.col, .at = At.of(p, f, sr.row, sr.col) }) catch return false;
places.append(arena, .{ .row = &sr.arow, .col = &sr.acol, .at = At.of(p, f, sr.arow, sr.acol) }) catch return false;
}
tops.append(arena, .{ .line = &tf.scroll, .at = fileOffset(f, lineStart(p.gpa, f, tf.scroll)) }) catch return false;
for (0..pardes.views.max) |k| {
if (k == p.live or !pardes.views.isOpen(p, @intCast(k))) continue;
const v = &pane.pv[k];
places.append(arena, .{ .row = &v.body.cur_row, .col = &v.body.cur_col, .at = At.of(p, f, v.body.cur_row, v.body.cur_col) }) catch return false;
tops.append(arena, .{ .line = &v.scroll, .at = fileOffset(f, lineStart(p.gpa, f, v.scroll)) }) catch return false;
}
}
const span = spanOf(f.content, new);
if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, false, null, .layer)) {
for (copies[0..ntwins]) |c| p.gpa.free(c);
return false;
}
p.gpa.free(f.layer.lines);
f.layer.lines = spans;
f.layer.owner = layer;
for (twins[0..ntwins], copies[0..ntwins]) |id, c| {
const tf = &p.panes[id].?.file.?;
p.gpa.free(tf.layer.lines);
tf.layer.lines = c;
tf.layer.owner = layer;
}
for (places.items) |place| {
const pos = positionIn(p.gpa, f, bufferOffset(f, place.at, false));
place.row.* = @intCast(pos.row);
place.col.* = @intCast(pos.col);
}
for (tops.items) |kept| kept.line.* = positionIn(p.gpa, f, bufferOffset(f, kept.at, false)).row;
return true;
}
/// Whether an edit of the `len` bytes at `off` is of read-only text: a
/// file at a revision (jj.zig) is that whole, to the editor and to a load;
/// the `Changes` layer's lines are each one, to the editor
/// (`touchesReadOnly`: a load takes them out first). The one check,
/// `edit`'s.
fn readOnly(f: *const State, off: usize, len: usize, bytes: []const u8, how: How) bool {
if (how == .layer) return false;
if (f.output) |o| if (o.from == .revision) return true;
return how == .edit and f.layer.lines.len > 0 and touchesReadOnly(f, off, len, bytes);
}
/// Said on each pane of `f` (`readOnly`).
fn refuse(p: *Pardes, f: *const State) void {
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
if (pane.file) |*state| if (state == f) {
pane.body.refused = true;
p.setMessage(.at(id), if (f.layer.lines.len > 0) read_only_said else "a file at a revision is read-only");
};
}
}
/// A replacement that takes out at least this much, and most of the text,
/// keeps the old buffer for its undo (Text.Journal.swap) instead of copying
/// what it takes out.
const swap_min = 64 << 10;
/// `replace`, or with `whole` that text's new buffer, `bytes` its middle,
/// taken as it is. Its room comes first, so an edit with no memory for it
/// changes nothing; then what holds a place in the text moves through the
/// edit (twins, other views, readers of its events, its line index, the
/// journal when `journaled`: an undo's own edits are not), the bytes go in
/// and it is a new revision. An edit that takes out most of the text puts
/// a new buffer in and gives the old to the journal whole (a swap); an
/// undo's swap back hands the buffer it replaces to `kept`.
fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, whole: ?[]u8, journaled: bool, kept: ?*[]u8, how: How) bool {
// Read-only text (a file at a revision, the layer's lines) takes no
// edit of the editor's: refused whole, in words.
if (readOnly(f, off, len, bytes_in, how)) {
refuse(p, f);
return false;
}
// What reads the file hears of the edit in the file's own offsets (the
// buffer less its read-only lines: `fileOffset`); the layer's own lines
// going in or out it never hears of. The undo's (`turn`) and a load's
// edits come with the layer out (undoStep, `load`).
const told = how != .layer;
const file_off = fileOffset(f, off);
const lines_taken = if (f.layer.lines.len > 0) std.mem.count(u8, f.content[off..][0..len], "\n") else 0;
const was_clean = f.revision == f.saved_revision;
const old_len = f.content.len;
const new_len = old_len - len + bytes_in.len;
const span: Span = .{ .head = off, .tail = old_len - off - len };
var twins: [pardes.MAX_PANES]usize = undefined;
const ntwins = twinsOf(p, f, &twins);
const room = textRoom(f);
// Bytes of the text's own (a move within it) are copied out first: the
// text moves under them.
const own = whole == null and @intFromPtr(bytes_in.ptr) < @intFromPtr(room.ptr) + room.len and @intFromPtr(bytes_in.ptr) + bytes_in.len > @intFromPtr(room.ptr);
const bytes = if (own) p.scratch.allocator().dupe(u8, bytes_in) catch return false else bytes_in;
// The journal keeps the file's text: never a buffer holding the
// layer's lines.
const swapping = journaled and len >= swap_min and len * 2 >= old_len and f.layer.lines.len == 0;
// A text a join is still sending stays as it is (memory.zig `pin`).
const keep = whole == null and (swapping or pardes.memory.isPinned(f.content));
const fresh: ?[]u8 = whole orelse if (keep) copySpliced(p.gpa, f.content, off, len, bytes) catch return false else null;
if (fresh == null) {
grow(p.gpa, f, new_len) catch return false;
// The twins' buffer is this one, which may have moved.
for (twins[0..ntwins]) |id| {
const tf = &p.panes[id].?.file.?;
tf.content = f.content;
tf.cap = f.cap;
}
}
// The views not live keep their place in it as twins do (views.zig).
const viewed = pardes.views.several(p);
var parked: ParkedPlaces = .{};
if (viewed) parked.before(p, f, span, new_len);
defer if (viewed) parked.after(p);
var moved: [pardes.MAX_PANES]struct { cursor: usize, scroll: usize } = undefined;
for (twins[0..ntwins], 0..) |id, i| {
const t = p.panes[id].?;
const tf = &t.file.?;
const at = lineStart(p.gpa, tf, @intCast(@max(0, t.body.cur_row))) + @as(usize, @intCast(@max(0, t.body.cur_col)));
moved[i] = .{ .cursor = spliced(@min(at, old_len), old_len, new_len, span), .scroll = spliced(lineStart(p.gpa, tf, tf.scroll), old_len, new_len, span) };
}
const old_starts = f.line_starts.ptr;
// An edit drops the rows and the colours, made for the text it changes.
locations.freeRows(p.gpa, f.location_rows);
f.location_rows = &.{};
p.gpa.free(f.pager_spans);
f.pager_spans = &.{};
for (p.panes) |slot| if (slot) |pane| {
if (pane.file) |*file| if (file == f) {
for (0..pane.sel.len) |button| {
pane.clearPointerSelection(button);
pane.sel[button].state = .none;
}
};
};
if (told) reportEdit(p, f, off, len, bytes);
// A pinned change's per-line values ride with the lines (jj.zig), in
// the file's lines.
if (told and p.changes.answers.items.len | p.changes.heats.items.len > 0) jj.edited(p, f, off, len, bytes);
// A message's places in it no longer know their lines (Messages.edited).
if (told and len + bytes.len > 0) p.messages.edited(f.path);
if (f.mini) |*mini| mini.deinit(p.gpa);
f.mini = null;
if (f.line_starts.len > 0) shiftIndex(p.gpa, f, off, len, bytes);
if (told and journaled and !swapping) f.history.journal.record(p.gpa, f.content[off..][0..len], file_off, bytes.len);
// ponytail: a whole-text hash per edit that keeps the saved length; a
// rolling hash when that too matters.
if (told and (f.revision == f.saved_revision or f.saved_hash == null)) {
f.saved_hash = fileHash(f);
f.saved_len = fileLen(f);
}
// The kept tree follows the edit (normal.fileTree parses with it), but
// not while a rollback copy holds it: an edit in place would change the
// copy's tree under it, so that one is left as it is and parsed anew;
// nor with the `Changes` layer's lines in or going (the tree is of the
// file's text, the edit of the buffer's): parsed anew.
if (f.node_tree) |tree| if (syntax.held_trees == null and f.node_tree_edits == f.revision and told and f.layer.lines.len == 0) {
syntax.editTree(tree, f.content[0..off], f.content[off..][0..len], bytes);
f.node_tree_edits = f.revision +% 1;
};
var undo_gone = false;
if (fresh) |new| {
const old = textRoom(f);
f.content = new[0..new_len];
f.cap = new.len;
if (kept) |k| {
k.* = old;
} else if (swapping) {
undo_gone = f.history.journal.swap(p.gpa, old, old_len, new_len);
} else {
// Raw: `free` overwrites a safe build's freed memory, a whole
// file's worth.
pardes.memory.freeRaw(p.gpa, old);
}
} else {
const buffer = textRoom(f);
pardes.rollback.Epoch.wrote(p.gpa, u8, buffer, old_len, new_len, off, buffer[off..][0..len], bytes.len);
const tail = old_len - off - len;
if (bytes.len != len) @memmove(buffer[off + bytes.len ..][0..tail], buffer[off + len ..][0..tail]);
@memcpy(buffer[off..][0..bytes.len], bytes);
f.content = buffer[0..new_len];
f.cap = buffer.len;
}
// The read-only lines after the edit move with what it put in and took
// out, and the layer's ghosts with them (none is in it: refused).
if (told and f.layer.lines.len > 0) {
const lines_put = std.mem.count(u8, bytes, "\n");
for (f.layer.lines) |*r| if (r.at >= off + len) {
r.at = r.at - len + bytes.len;
r.line = @intCast(r.line + lines_put - lines_taken);
};
jj.placed(p, f);
}
f.revision +%= 1;
f.splice = .{ .revision = f.revision, .head = span.head, .tail = span.tail, .old_len = old_len };
// Edited, a reading pane is held (pick-ui SPEC §6.5).
if (how == .edit) pardes.Trail.edited(p, f);
if (!told) {
// The file's text is as it was: as clean as it was, its
// declarations still its own.
if (was_clean) f.saved_revision = f.revision;
if (f.context.revision == f.revision -% 1) f.context.revision = f.revision;
} else if (f.saved_hash) |h| if ((f.saved_len orelse fileLen(f)) == fileLen(f) and fileHash(f) == h) {
f.saved_revision = f.revision;
};
// The clock the session that recorded read (core/tape.zig).
if (told) f.mtime = p.tape.value(.mtime, pardes.ctlfs.events.now, .{});
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = &.{};
f.highlight_start = 0;
f.syntax_dirty = true;
if (f.pager) f.pager_diff = looksLikeDiff(f.content[0..@min(new_len, 64 * 1024)]);
if (undo_gone) for (p.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.file) |*state| if (state == f) p.setMessage(.at(id), "undo keeps the last two texts replaced whole: the steps before them are gone");
};
for (twins[0..ntwins], 0..) |id, i| {
const t = p.panes[id].?;
const tf = &t.file.?;
// Its own index, built while the shared one was empty, goes; the
// shared one is this one's, moved through the edit.
if (tf.line_starts.len > 0 and tf.line_starts.ptr != old_starts) pardes.memory.freeRaw(p.gpa, indexRoom(tf));
tf.content = f.content;
tf.cap = f.cap;
tf.line_starts = f.line_starts;
tf.line_cap = f.line_cap;
tf.widest = f.widest;
if (!told and tf.context.revision == f.revision -% 1) tf.context.revision = f.revision;
// Its copy of the read-only lines, moved as this one's were (the
// layer's own edit sets them after, jj.showLayer).
if (told and tf.layer.lines.len == f.layer.lines.len) @memcpy(tf.layer.lines, f.layer.lines);
tf.revision = f.revision;
tf.saved_revision = f.saved_revision;
tf.saved_hash = f.saved_hash;
tf.saved_len = f.saved_len;
tf.mtime = f.mtime;
if (tf.highlights.len > 0) p.tree_sitter_gpa.free(tf.highlights);
tf.highlights = &.{};
tf.highlight_start = 0;
tf.syntax_dirty = true;
locations.freeRows(p.gpa, tf.location_rows);
tf.location_rows = &.{};
if (tf.mini) |*mini| mini.deinit(p.gpa);
tf.mini = null;
for (0..t.sel.len) |button| {
t.clearPointerSelection(button);
t.sel[button].state = .none;
}
t.body.vsel.active = false;
t.body.nsel = 0;
const cursor = positionIn(p.gpa, tf, moved[i].cursor);
t.body.cur_row = @intCast(cursor.row);
t.body.cur_col = @intCast(cursor.col);
const was = tf.scroll;
tf.scroll = positionIn(p.gpa, tf, moved[i].scroll).row;
// Moved by the edit, not scrolled: a Follow chain reflows from its head.
t.follow_scroll +%= tf.scroll -% was;
}
return true;
}
/// Room in `f`'s buffer for `n` bytes, grown by an eighth more when it must
/// be: in place where its allocator can, else into a new buffer.
fn grow(gpa: std.mem.Allocator, f: *State, n: usize) !void {
const room = textRoom(f);
if (n <= room.len) return;
const want = n + @max(n / 8, 4096);
if (room.len > 0) if (gpa.remap(room, want)) |grown| {
f.content = grown[0..f.content.len];
f.cap = grown.len;
return;
};
const fresh = try pardes.memory.unfilled(gpa, want);
@memcpy(fresh[0..f.content.len], f.content);
pardes.memory.freeRaw(gpa, room);
f.content = fresh[0..f.content.len];
f.cap = fresh.len;
// The old buffer's pages back to the system now: an arena keeps a freed
// run of a megabyte or more resident for the next block its size, which
// a text grown with room never asks for (a 100 MB file held its copy).
if (room.len >= 1 << 20) pardes.memory.trim();
}
/// `text` with the `len` bytes at `off` replaced by `bytes`, in a new buffer.
fn copySpliced(gpa: std.mem.Allocator, text: []const u8, off: usize, len: usize, bytes: []const u8) ![]u8 {
const out = try pardes.memory.unfilled(gpa, text.len - len + bytes.len);
@memcpy(out[0..off], text[0..off]);
@memcpy(out[off..][0..bytes.len], bytes);
@memcpy(out[off + bytes.len ..], text[off + len ..]);
return out;
}
/// Each other view's cursor and scroll on a text being changed, as offsets
/// moved by the splice (`spliced`), put back as places in the new text once
/// it is in: a view not live keeps its place, as a twin does. Its
/// selections go, as a twin's do.
const ParkedPlaces = struct {
const max = pardes.MAX_PANES * pardes.views.max;
at: [max]struct { pane: *Pane, view: u8, cursor: usize, scroll: usize } = undefined,
n: usize = 0,
fn before(pp: *ParkedPlaces, p: *Pardes, f: *State, span: Span, new_len: usize) void {
for (p.panes) |slot| {
const pane = slot orelse continue;
const tf = if (pane.file) |*file| file else continue;
if (tf != f and (f.twin == 0 or tf.twin != f.twin)) continue;
for (0..pardes.views.max) |k| {
if (k == p.live or !pardes.views.isOpen(p, @intCast(k)) or pp.n == max) continue;
const v = &pane.pv[k];
const at = lineStart(p.gpa, tf, @intCast(@max(0, v.body.cur_row))) + @as(usize, @intCast(@max(0, v.body.cur_col)));
pp.at[pp.n] = .{
.pane = pane,
.view = @intCast(k),
.cursor = spliced(@min(at, f.content.len), f.content.len, new_len, span),
.scroll = spliced(@min(lineStart(p.gpa, tf, v.scroll), f.content.len), f.content.len, new_len, span),
};
pp.n += 1;
}
}
}
fn after(pp: *ParkedPlaces, p: *Pardes) void {
for (pp.at[0..pp.n]) |a| {
const tf = &(a.pane.file orelse continue);
const v = &a.pane.pv[a.view];
const cursor = positionIn(p.gpa, tf, @min(a.cursor, tf.content.len));
v.body.cur_row = @intCast(cursor.row);
v.body.cur_col = @intCast(cursor.col);
v.body.vsel.active = false;
v.body.nsel = 0;
const was = v.scroll;
v.scroll = positionIn(p.gpa, tf, @min(a.scroll, tf.content.len)).row;
v.follow_scroll +%= v.scroll -% was;
}
}
};
/// Where an offset into the old text is in the new, after the splice that
/// kept `span` at either end: past it, moved by what it added; inside it,
/// at its start, as acme moves a clone's q0 (textinsert, textdelete).
fn spliced(at: usize, old_len: usize, new_len: usize, span: Span) usize {
if (at <= span.head) return at;
if (at >= old_len - span.tail) return at - (old_len - span.tail) + (new_len - span.tail);
return span.head;
}
/// What `old` and `new` agree on at either end.
/// What `new` kept of `old` at either end, compared 32 bytes at a time
/// (a byte at a time was most of a `d` in a 7 MB file).
pub fn spanOf(old: []const u8, new: []const u8) Span {
const block = 32;
const n = @min(old.len, new.len);
var head: usize = 0;
while (head + block <= n and std.mem.eql(u8, old[head..][0..block], new[head..][0..block])) head += block;
while (head < n and old[head] == new[head]) head += 1;
var tail: usize = 0;
while (tail + block <= n - head and std.mem.eql(u8, old[old.len - tail - block ..][0..block], new[new.len - tail - block ..][0..block])) tail += block;
while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1;
return .{ .head = head, .tail = tail };
}
fn positionIn(gpa: std.mem.Allocator, f: *State, at: usize) struct { row: usize, col: usize } {
const index = lineIndex(gpa, f) catch {
const c = modal.positionAt(f.content, at);
return .{ .row = c.row, .col = c.col };
};
const row = std.sort.upperBound(usize, index, at, ascending) -| 1;
return .{ .row = row, .col = at - index[row] };
}
/// The other panes on `f`'s buffer (Zerox), by id.
pub fn twinsOf(p: *Pardes, f: *const State, out: *[pardes.MAX_PANES]usize) usize {
if (f.twin == 0) return 0;
var n: usize = 0;
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
const other = if (pane.file) |*file| file else continue;
if (other == f or other.twin != f.twin) continue;
out[n] = id;
n += 1;
}
return n;
}
/// acme's Zerox: pane `to` made on `from`'s buffer, its text, undo and
/// dirty state shared, its scroll and cursor its own. An edit in either is
/// spliced into both (setContentSpan, O(the edit) more); what Save and the
/// disk watch change on one is copied to the others after each step
/// (syncTwins). An event reader on one hears no edit made in another.
pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane {
const src = p.panes[from].?;
const f = &src.file.?;
const path = try p.gpa.dupe(u8, f.path);
errdefer p.gpa.free(path);
if (f.twin == 0) {
const group = try p.gpa.dupe(u8, f.path);
errdefer p.gpa.free(group);
try p.twin_groups.append(p.gpa, .{ .id = p.next_twin, .saved_revision = f.saved_revision, .saved_hash = f.saved_hash, .saved_len = f.saved_len, .disk_newer = f.disk_newer, .disk_gone = f.disk_gone, .on_disk = f.on_disk, .path = group });
f.twin = p.next_twin;
p.next_twin +%= 1;
}
// The layer's lines are the buffer's: a twin shows them too, a copy of
// their places its own.
const read_only = try p.gpa.dupe(ReadOnly, f.layer.lines);
errdefer p.gpa.free(read_only);
const pane = try p.newDocPane(to);
pane.layers.lanes = src.layers.lanes;
pane.file = .{
.layer = .{ .owner = f.layer.owner, .lines = read_only },
.path = path,
.content = f.content,
.cap = f.cap,
.line_starts = f.line_starts,
.line_cap = f.line_cap,
.widest = f.widest,
.history = f.history,
.revision = f.revision,
.saved_revision = f.saved_revision,
.saved_hash = f.saved_hash,
.saved_len = f.saved_len,
.disk_newer = f.disk_newer,
.disk_gone = f.disk_gone,
.on_disk = f.on_disk,
.mtime = f.mtime,
.scroll = f.scroll,
.scroll_row = f.scroll_row,
.tree_context = f.tree_context,
.twin = f.twin,
};
pane.body.cur_row = src.body.cur_row;
pane.body.cur_col = src.body.cur_col;
pane.body.cur_pinned = true;
if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = .at(to), .on = true } });
return pane;
}
/// A twin closed: it keeps a text of its own until it is torn down (a
/// retired pane is drawn going), and the twins keep the shared one, its
/// undo and its index.
pub fn leaveTwins(p: *Pardes, f: *State) void {
var twins: [pardes.MAX_PANES]usize = undefined;
const n = twinsOf(p, f, &twins);
f.twin = 0;
if (n == 0) return;
const shared_index = for (twins[0..n]) |id| {
if (p.panes[id].?.file.?.line_starts.ptr == f.line_starts.ptr) break true;
} else false;
if (shared_index) {
f.line_starts = &.{};
f.line_cap = 0;
}
f.content = p.gpa.dupe(u8, f.content) catch p.gpa.alloc(u8, 0) catch &.{};
f.cap = 0;
f.history = History.create(p.gpa) catch f.history;
// The one left is no twin now (syncTwins drops the group).
if (n == 1) p.panes[twins[0]].?.file.?.twin = 0;
if (n == 1) unchain(p.panes[twins[0]].?);
}
pub const TwinGroup = struct {
id: u32,
saved_revision: u32,
saved_hash: ?u64,
saved_len: ?usize,
disk_newer: ?u64,
disk_gone: bool,
on_disk: bool,
path: []u8,
};
/// After each step: what a Save, a get, the disk watch or a rename changed
/// on one twin is copied to the others; a group down to one pane is no
/// group. O(panes) a step, and nothing at all with no twins.
pub fn syncTwins(p: *Pardes) void {
var g: usize = 0;
while (g < p.twin_groups.items.len) {
const group = &p.twin_groups.items[g];
var members: [pardes.MAX_PANES]*State = undefined;
var member_panes: [pardes.MAX_PANES]*Pane = undefined;
var n: usize = 0;
for (p.panes) |slot| {
const pane = slot orelse continue;
const f = if (pane.file) |*file| file else continue;
if (f.twin == group.id) {
members[n] = f;
member_panes[n] = pane;
n += 1;
}
}
if (n < 2) {
if (n == 1) members[0].twin = 0;
if (n == 1) unchain(member_panes[0]);
p.gpa.free(group.path);
_ = p.twin_groups.swapRemove(g);
continue;
}
for (members[0..n]) |f| {
if (f.saved_revision == group.saved_revision and f.saved_hash == group.saved_hash and f.saved_len == group.saved_len and
f.disk_newer == group.disk_newer and f.disk_gone == group.disk_gone and f.on_disk == group.on_disk and std.mem.eql(u8, f.path, group.path)) continue;
// This one changed: the group, and every other twin, take it.
if (!std.mem.eql(u8, f.path, group.path)) {
const path = p.gpa.dupe(u8, f.path) catch break;
p.gpa.free(group.path);
group.path = path;
}
group.saved_revision = f.saved_revision;
group.saved_hash = f.saved_hash;
group.saved_len = f.saved_len;
group.disk_newer = f.disk_newer;
group.disk_gone = f.disk_gone;
group.on_disk = f.on_disk;
for (members[0..n], member_panes[0..n]) |other, other_pane| {
if (other == f) continue;
other.saved_revision = f.saved_revision;
other.saved_hash = f.saved_hash;
other.saved_len = f.saved_len;
other.disk_newer = f.disk_newer;
other.disk_gone = f.disk_gone;
other.on_disk = f.on_disk;
if (!std.mem.eql(u8, other.path, f.path)) {
const path = p.gpa.dupe(u8, f.path) catch continue;
p.gpa.free(other.path);
other.path = path;
// Renamed, each twin says so, as the one renamed did.
pardes.ctlfs.events.noteLog(p, .rename, other_pane);
}
}
break;
}
// Tests hold the twins to one text, one revision, every step.
if (builtin.is_test) for (members[1..n]) |other| {
std.debug.assert(other.content.ptr == members[0].content.ptr and other.content.len == members[0].content.len);
std.debug.assert(other.revision == members[0].revision);
};
// Only a group with a chain pays for one.
for (members[0..n]) |f| if (f.follow) {
followChain(p, group.id);
break;
};
g += 1;
}
}
/// Follow's chain in twin group `twin`, as the live view lays it out: its
/// panes in column order show the text as consecutive pages, each starting
/// on the line after the one before ends. A pane scrolled (by anything:
/// the wheel, a page key, a jump, the cursor past a chain's end) moves the
/// others with it; the cursor going past a page's edge takes the keyboard
/// to the page that shows its line (ensureCursorVisible leaves the
/// keyboard's page's inner edges alone, `follow_edges`). A chain of one is
/// no chain.
fn followChain(p: *Pardes, twin: u32) void {
const v = p.view();
var chain: [pardes.MAX_PANES]*Pane = undefined;
var ids: [pardes.MAX_PANES]usize = undefined;
var n: usize = 0;
for (v.cols[0..v.ncol]) |col| for (col.panes[0..col.n]) |id| {
const pane = p.panes[id] orelse continue;
const f = if (pane.file) |*file| file else continue;
if (f.twin != twin or !f.follow) continue;
chain[n] = pane;
ids[n] = id;
n += 1;
};
if (n < 2) {
for (chain[0..n]) |pane| unchain(pane);
return;
}
// The head is the text's first page, never a follower of another.
dropUnfollow(chain[0]);
// A collapsed page shows no text: the chain flows past it, its cursor
// never hops into it, and it keeps its scroll until it opens again.
var shown: usize = 0;
for (chain[0..n], ids[0..n]) |pane, id| {
if (pane.collapsed) {
pane.follow_edges = 0;
pane.follow_crossed = false;
continue;
}
chain[shown] = pane;
ids[shown] = id;
shown += 1;
}
n = shown;
if (n == 0) return;
// The cursor moved past its page's edge: the keyboard goes to the page
// showing its line, else to the chain's end, which scrolls to it.
const active = for (ids[0..n], 0..) |id, k| {
if (id == v.active) break k;
} else null;
if (active) |k| if (v.header == null and chain[k].focus == .body) hop: {
const m = chain[k];
const row: usize = @intCast(@max(0, m.body.cur_row));
if (m.follow_crossed and (row < m.file.?.scroll or row >= pageEnd(p.settings.tab, m))) {
const j = for (chain[0..n], 0..) |o, i| {
if (row >= o.file.?.scroll and row < pageEnd(p.settings.tab, o)) break i;
} else if (row < m.file.?.scroll) 0 else n - 1;
if (j == k) break :hop;
const to = chain[j];
to.body.cur_row = m.body.cur_row;
to.body.cur_col = m.body.cur_col;
to.body.cur_pinned = true;
to.body.vsel.active = false;
to.body.nsel = 0;
to.body.mode = m.body.mode;
m.body.mode = .normal;
v.active = ids[j];
to.follow_edges = @as(u2, @intFromBool(j > 0)) | @as(u2, @intFromBool(j + 1 < n)) << 1;
to.ensureCursorVisible(p.settings.tab);
}
};
// The page that moved (the keyboard's first), else the head, sets the
// others: back to the head, then on from it.
var anchor: usize = 0;
for (chain[0..n], 0..) |o, k| if (o.file.?.scroll != o.follow_scroll) {
anchor = k;
if (ids[k] == v.active) break;
};
var k = anchor;
while (k > 0) : (k -= 1) {
const prev = chain[k - 1];
const want = chain[k].file.?.scroll;
// The furthest scroll whose page ends at `want` or before.
var s = want -| prev.rows;
setPageScroll(prev, s);
while (s < want) : (s += 1) {
setPageScroll(prev, s + 1);
if (pageEnd(p.settings.tab, prev) <= want) continue;
setPageScroll(prev, s);
break;
}
}
for (chain[1..n], 0..) |o, i| setPageScroll(o, pageEnd(p.settings.tab, chain[i]));
// Only the keyboard's page crosses its edges: a dot written to another
// scrolls it there, and the chain with it.
for (chain[0..n], ids[0..n], 0..) |o, id, i| {
o.follow_scroll = o.file.?.scroll;
o.follow_crossed = false;
o.follow_edges = if (id != v.active) 0 else @as(u2, @intFromBool(i > 0)) | @as(u2, @intFromBool(i + 1 < n)) << 1;
}
}
/// The line a page after `pane`'s starts on: the one after its last row's,
/// or that line again when the pane wraps it on past its bottom.
fn pageEnd(tab: u16, pane: *Pane) usize {
const f = &pane.file.?;
geometry(tab, pane);
if (pane.wrap_n == 0) return f.scroll + pane.rows;
const last = (if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n) - 1;
const line: usize = @intCast(pane.wrap_line[last]);
if (!pane.body_wrapped or line >= nlines(pane.gpa, f)) return line + 1;
const text = sourceLine(pane, @intCast(line));
const width = wrapWidth(pane, pane.view.wrap) -| pane.wrap_pad[last];
return if (fitEnd(tab, text, @intCast(pane.wrap_col[last]), width) < text.len) @max(line, f.scroll + 1) else line + 1;
}
fn setPageScroll(pane: *Pane, line: usize) void {
setTop(pane, .{ .line = @min(line, nlines(pane.gpa, &pane.file.?) -| 1) });
}
/// A view's top: the line its first row is of (`State.scroll`) and that
/// row of the line's rows as wrapped (`State.scroll_row`; one row
/// unwrapped). A scroll moves it by rows through the lines.
pub const Top = struct { line: usize, row: u32 = 0 };
/// The row of line `line` that shows its byte `col` (a line's last row
/// every byte past its start, as wrapRow has it), as fillBody wraps it.
pub fn rowOf(tab: u16, pane: *const Pane, line: usize, col: usize) u32 {
return rowIn(tab, pane, line, col).row;
}
/// The rows line `line` takes in `pane`'s view.
pub fn lineRows(tab: u16, pane: *const Pane, line: usize) u32 {
return rowIn(tab, pane, line, std.math.maxInt(usize)).rows;
}
/// Whether every line of `pane`'s view is one row: none wider than a row
/// (the text's widest, kept with its index), so its rows are its lines and
/// the walks below are line arithmetic, nothing read.
fn oneRow(tab: u16, pane: *const Pane, width: usize) bool {
const f = &pane.file.?;
return width == 0 or (f.line_starts.len > 0 and f.widest.cells(tab) <= width);
}
const RowIn = struct { row: u32, rows: u32 };
/// rowOf's row and lineRows' rows, in one walk of the line: the one walk
/// of a line's rows every map from rows to lines asks, beside the
/// geometry's own map of the body (the same `fitEnd` at the same width).
fn rowIn(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn {
const width = wrapWidth(pane, pane.view.wrap);
if (pane.file != null and oneRow(tab, pane, width)) {
if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, width, line, col, .{}, &.{}).rows == 1);
return .{ .row = 0, .rows = 1 };
}
return rowWalked(tab, pane, width, line, col, .{}, &.{});
}
/// How far a walk of a line's rows goes once the row showing its byte is
/// found: `after` rows past it and `least` in all, its rows a lower bound
/// then (what `show` needs of a long line); else to its end.
const Bound = struct { after: u32 = std.math.maxInt(u32), least: u32 = 0 };
/// rowIn's walk at `width`, as far as `bound`; `starts`, when it has room,
/// keeps the first byte of each row walked after the first, the last
/// `starts.len` of them (row `r` at `r % starts.len`; its caller's row 0).
fn rowWalked(tab: u16, pane: *const Pane, width: usize, line: usize, col: usize, bound: Bound, starts: []usize) RowIn {
const f = if (pane.file) |*file| file else return .{ .row = 0, .rows = 1 };
if (width == 0) return .{ .row = 0, .rows = 1 };
const text = sourceLine(pane, @intCast(line));
// No more bytes than a row has cells and no tab is one row: a tab is
// `tab` cells, any other byte at most one (Widest); no grapheme walked
// (the lines a page or a margin crosses, nearly all of a source's).
if (text.len <= width and std.mem.indexOfScalar(u8, text, '\t') == null) {
if (builtin.mode == .debug) std.debug.assert(fitEnd(tab, text, 0, width) >= text.len);
return .{ .row = 0, .rows = 1 };
}
var guide: [1024]u8 = undefined;
var at: usize = 0;
var row: u32 = 0;
var found: ?u32 = null;
while (true) {
const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide)));
if (found == null and col < end) found = row;
if (end >= text.len or end <= at) return .{ .row = found orelse row, .rows = row + 1 };
if (found) |r| if (row >= r +| bound.after and row + 1 >= bound.least) return .{ .row = r, .rows = row + 1 };
at = end;
row += 1;
if (starts.len > 0) starts[row % starts.len] = at;
}
}
/// Where `pane`'s view starts: a row past its line's last (the text
/// rewrapped, an edit, the layer's lines come or gone) is read as its
/// last, as the geometry's walk found it (no walk of the line a frame).
pub fn top(tab: u16, pane: *Pane) Top {
if (pane.file.?.scroll_row > 0) geometry(tab, pane);
return topNow(tab, pane);
}
/// `top` off a geometry made already (a step that made it reads its key
/// once: each hash of it costs a long line's step a hundredth more).
fn topNow(tab: u16, pane: *Pane) Top {
const f = &pane.file.?;
return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else topSkip(tab, pane).row };
}
/// The top's row in its line (held at the line's last) and its first byte,
/// for the geometry made now: the one read of `Pane.top_skip`, a cache
/// keyed by the geometry it is of. A step that moves the top hands the
/// next geometry its byte (`show`, `scrollRows`), and a view drawn or
/// stepped in since leaves its own: one keyed for another geometry is
/// another view's top, or another place's, never this one's, and is
/// walked again here.
fn topSkip(tab: u16, pane: *Pane) @FieldType(Pane, "top_skip") {
if (pane.top_skip.key == pane.geometry_key) return pane.top_skip;
const f = &pane.file.?;
const width = wrapWidth(pane, pane.view.wrap);
const text = if (f.scroll < nlines(pane.gpa, f)) sourceLine(pane, @intCast(f.scroll)) else "";
var guide: [1024]u8 = undefined;
var row: u32 = 0;
var at: usize = 0;
while (row < f.scroll_row and width > 0) : (row += 1) {
const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide)));
if (end >= text.len or end <= at) break;
at = end;
}
pane.top_skip = .{ .key = pane.geometry_key, .row = row, .at = at };
return pane.top_skip;
}
pub fn setTop(pane: *Pane, to: Top) void {
const f = &pane.file.?;
if (to.line != f.scroll) f.syntax_dirty = true;
f.scroll = to.line;
f.scroll_row = to.row;
}
/// The place `n` rows below `from` (above it, `n` negative) through the
/// lines' rows, held at the text's first row and at its last line's last;
/// and the rows it moved.
pub fn walkRows(tab: u16, pane: *Pane, from: Top, n: i64) Walked {
return walkKnown(tab, pane, from, n, null);
}
/// A line's rows its caller has walked already (show's, the cursor's
/// line): a walk reads them, not the line again.
const Known = struct { line: usize, rows: u32 };
const Walked = struct { to: Top, moved: i64 };
fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked {
const last = nlines(pane.gpa, &pane.file.?) -| 1;
if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return walkedRows(tab, pane, from, n, last, known);
const to = if (n < 0) from.line -| @abs(n) else if (from.line >= last) from.line else @min(from.line +| @abs(n), last);
const w: Walked = .{ .to = .{ .line = to }, .moved = @as(i64, @intCast(to)) - @as(i64, @intCast(from.line)) };
if (builtin.mode == .debug) std.debug.assert(std.meta.eql(w, walkedRows(tab, pane, from, n, last, known)));
return w;
}
fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked {
var map: ?bool = null;
const width = wrapWidth(pane, pane.view.wrap);
var t = from;
var rows = rowsOf(tab, pane, width, &map, known, t.line);
t.row = @min(t.row, rows - 1);
var left = n;
while (left > 0) {
const room = rows - 1 - t.row;
if (left <= room) {
t.row += @intCast(left);
left = 0;
} else if (t.line >= last) {
left -= room;
t.row = rows - 1;
break;
} else {
left -= room + 1;
t.line += 1;
t.row = 0;
rows = rowsOf(tab, pane, width, &map, known, t.line);
}
}
while (left < 0) {
if (-left <= t.row) {
t.row -= @intCast(-left);
left = 0;
} else if (t.line == 0) {
left += t.row;
t.row = 0;
break;
} else {
left += t.row + 1;
t.line -= 1;
rows = rowsOf(tab, pane, width, &map, known, t.line);
t.row = rows - 1;
}
}
return .{ .to = t, .moved = n - left };
}
/// The rows from `from` down to line `line`'s first row (up to it,
/// negative), or null when it is more than `bound` rows away.
pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 {
if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return rowsWalked(tab, pane, from, line, bound);
const d = @as(i64, @intCast(line)) - @as(i64, @intCast(from.line)) - from.row;
const to: ?i64 = if ((line > from.line and d > bound) or (line < from.line and -d > bound)) null else d;
if (builtin.mode == .debug) std.debug.assert(std.meta.eql(to, rowsWalked(tab, pane, from, line, bound)));
return to;
}
fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 {
var map: ?bool = null;
const width = wrapWidth(pane, pane.view.wrap);
var d: i64 = -@as(i64, from.row);
var l = from.line;
while (l < line) : (l += 1) {
d += rowsOf(tab, pane, width, &map, null, l);
if (d > bound) return null;
}
while (l > line) {
l -= 1;
d -= rowsOf(tab, pane, width, &map, null, l);
if (-d > bound) return null;
}
return d;
}
/// Whether `pane`'s map (the geometry) is of the view as it is now: only
/// then may a walk read a line's rows off it (derived state, made by
/// whoever asked first).
fn mapFresh(tab: u16, pane: *const Pane) bool {
return pane.wrap_n > 0 and pane.geometry_key == geometryKey(tab, pane, &pane.file.?);
}
/// The rows line `line` takes: counted off the map when the map is fresh
/// and holds all of them in the body (no line walked: a page, a cursor
/// past the body's edge), else walked (a walk's: no line is one row). Its
/// walk's `map`: whether the map is fresh, asked the first time a line in
/// it is.
fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, line: usize) u32 {
if (known) |k| if (k.line == line) return k.rows;
if (pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1] and
(map.* orelse fresh: {
map.* = mapFresh(tab, pane);
break :fresh map.*.?;
}))
{
const f = &pane.file.?;
var rows: u32 = 0;
var i: usize = pane.context_rows;
while (i < pane.wrap_n) : (i += 1) {
if (pane.wrap_line[i] == line) {
// Rows of it above the top are not in the map: its top row
// starts past its first byte.
if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.wrap_col[i] > 0) break;
rows += 1;
} else if (rows > 0) return rows;
}
}
return rowWalked(tab, pane, width, line, std.math.maxInt(usize), .{}, &.{}).rows;
}
/// `pane`'s view moved `delta` rows (a wheel's notch is one): the rows it
/// moved.
pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 {
geometry(tab, pane);
const t = topNow(tab, pane);
// Down to a row the body shows: the map has it, its line and its row in
// that line, no line walked (a notch, a page).
const i = @as(i64, pane.context_rows) + delta;
if (delta > 0 and pane.wrap_n > 0 and i < shownNow(pane) + @as(i64, pane.context_rows)) {
const k: usize = @intCast(i);
const line: usize = @intCast(pane.wrap_line[k]);
if (line < nlines(pane.gpa, &pane.file.?)) {
var row: u32 = if (line == t.line) t.row else 0;
for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]);
setTop(pane, .{ .line = line, .row = row });
// Its first byte is the map's: the geometry starts there.
if (pane.body_wrapped) pane.top_skip = .{ .key = geometryKey(tab, pane, &pane.file.?), .row = row, .at = @intCast(pane.wrap_col[k]) };
return delta;
}
}
const w = walkRows(tab, pane, t, delta);
setTop(pane, w.to);
return w.moved;
}
/// The rows of `pane`'s body under its context rows, of its geometry as
/// the view is now (made again first if stale: a key's step reads it
/// before any draw, and only the state it is made of may decide it).
pub fn shownRows(tab: u16, pane: *Pane) u16 {
geometry(tab, pane);
return shownNow(pane);
}
fn shownNow(pane: *const Pane) u16 {
const visible = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n;
return @max(1, if (pane.wrap_n == 0) pane.rows else visible -| pane.context_rows);
}
/// The rows of `pane`'s map its tag out of rest draws over (UX DESIGN I1,
/// `view.covered` grid rows from the body's top): its context rows at the
/// tagline's height where the geometry stacks them so, the rest at the
/// body's.
pub fn coveredRows(pane: *const Pane) u16 {
const v = pane.view;
if (v.covered == 0) return 0;
const bh: usize = @max(1, v.body_h);
const th: usize = std.math.clamp(v.tagline_h, 1, bh);
const px = @as(usize, v.covered) * bh;
const compact: usize = if (pane.context_row_limit != null) pane.context_rows else 0;
const rows = if (compact * th >= px) (px + th - 1) / th else compact + (px - compact * th + bh - 1) / bh;
// A damaged dump's covered rows are any: never past a u16's.
return @intCast(@min(rows, std.math.maxInt(u16)));
}
/// The view moved when line `line_at`'s row that shows its byte `col` is
/// out of the body's margins (`margin_rows` rows, helix's scrolloff, at
/// most half of it): by the rows that show the line's rows whole inside
/// them, or that row where the line is taller than they leave. A cursor's
/// (Pane.ensureCursorVisible's, for a file) or a result's.
pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void {
const f = &pane.file.?;
geometry(tab, pane);
const t = topNow(tab, pane);
// Its rows a tag out of rest draws over (UX DESIGN I1): what a state
// shows goes under them, as under the context rows; the bottom stays.
const covered: u16 = coveredRows(pane);
const hidden: i64 = covered -| pane.context_rows;
// The line held at the top (a sticky context row): as it is.
if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) {
for (pane.wrap_line[@min(covered, pane.context_rows)..pane.context_rows]) |row| if (row == line_at) return;
}
const full: i64 = shownNow(pane);
const body: i64 = @max(1, full - hidden);
const margin: i64 = @min(margin_rows, @divTrunc(body - 1, 2));
// The row in the body (the map's, made just now), or none: the line is
// above the top, or below the map. Inside the band the view stays, and
// no line is walked (a key's step, nearly always).
const mapped: i64 = pane.wrapRow(tab, line_at, col).row - @as(i64, pane.context_rows) - hidden;
const row: ?i64 = if (mapped >= -hidden and mapped < @as(i64, @max(pane.wrap_n, pane.rows) -| pane.context_rows) - hidden) mapped else null;
if (row) |r| if (r >= margin and r <= body - 1 - margin) return;
const line: usize = @intCast(@max(0, line_at));
// The line walked once and no further than the view needs (`Bound`: a
// long line's rows past the band are not), the first bytes of its last
// rows kept: where the view lands in it, its geometry starts there.
const width = wrapWidth(pane, pane.view.wrap);
var ring: [limits.wrap_rows]usize = undefined;
ring[0] = 0;
const starts = ring[0..@intCast(@min(body, ring.len))];
const at = if (oneRow(tab, pane, width)) RowIn{ .row = 0, .rows = 1 } else rowWalked(tab, pane, width, line, @intCast(@max(0, col)), .{ .after = @intCast(margin), .least = @intCast(body - 2 * margin + 1) }, starts);
const known: Known = .{ .line = line, .rows = at.rows };
defer if (f.scroll == line and f.scroll_row < at.rows and at.rows - 1 - f.scroll_row < starts.len) {
pane.top_skip = .{ .key = geometryKey(tab, pane, f), .row = f.scroll_row, .at = starts[f.scroll_row % starts.len] };
};
if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true;
const whole = at.rows <= body - 2 * margin;
if (if (row) |r| r < margin else line <= t.line) {
if (pane.follow_edges & 1 != 0) return;
setTop(pane, walkKnown(tab, pane, .{ .line = line, .row = if (whole) 0 else at.row }, -margin - hidden, known).to);
} else if (if (row) |r| r > body - 1 - margin else true) {
if (pane.follow_edges & 2 != 0) return;
// The margin only reveals text: a pane its whole text fits in
// never scrolls for it; a longer one keeps helix's clamp at the
// text's last line.
var past = walkKnown(tab, pane, .{ .line = line, .row = if (whole) at.rows - 1 else at.row }, margin, known).to;
if (t.line == 0 and t.row == 0 and pane.textFits()) {
const stop = @max(line, nlines(pane.gpa, f) -| 1 -| @intFromBool(std.mem.endsWith(u8, f.content, "\n")));
if (past.line > stop) past = .{ .line = stop, .row = lineRows(tab, pane, stop) - 1 };
}
setTop(pane, walkKnown(tab, pane, past, -(full - 1), known).to);
}
}
/// The line whose first row (no wrapped line's later row) is nearest body
/// row `from` inside the body's band (`margin` rows in from each edge, at
/// most half of it, under its context rows): the first at or below it
/// going `.down`, else the last above it; `.up` the other way round. Where
/// a view key leaves a cursor (Text.scrollViewMove, normal.halfPageMove);
/// null when the band has none (inside a line taller than the body): the
/// cursor stays.
pub fn textRowLine(tab: u16, pane: *Pane, from: i64, margin: i64, way: enum { down, up }) ?i32 {
geometry(tab, pane);
const lines: i32 = @intCast(nlines(pane.gpa, &pane.file.?));
const held: i64 = pane.context_rows;
const shown: i64 = shownRows(tab, pane);
const m = @min(margin, @divTrunc(shown - 1, 2));
const lo = held + m;
const hi = held + shown - 1 - m;
for ([2]i64{ if (way == .down) 1 else -1, if (way == .down) -1 else 1 }) |step| {
var vr = std.math.clamp(held + from, lo, hi);
while (vr >= lo and vr <= hi) : (vr += step) {
const w = pane.wrapAt(tab, @intCast(vr));
if ((w.at == 0 or !pane.body_wrapped) and w.line < lines) return w.line;
}
}
return null;
}
pub const Bytes = struct { start: usize, end: usize };
/// The bytes of the text `pane`'s body shows: its first row's first to its
/// last row's last (whole lines unwrapped, as each row is one).
pub fn shownBytes(tab: u16, pane: *Pane) Bytes {
const f = &pane.file.?;
const shown = shownRows(tab, pane);
if (!pane.body_wrapped) return .{ .start = lineStart(pane.gpa, f, f.scroll), .end = lineStart(pane.gpa, f, f.scroll + shown) };
const first = pane.context_rows;
const last = first + shown - 1;
const start = lineStart(pane.gpa, f, @intCast(pane.wrap_line[first])) + @as(usize, @intCast(pane.wrap_col[first]));
const line: usize = @intCast(pane.wrap_line[last]);
if (line >= nlines(pane.gpa, f)) return .{ .start = start, .end = f.content.len };
const text = sourceLine(pane, @intCast(line));
return .{ .start = start, .end = lineStart(pane.gpa, f, line) + fitEnd(tab, text, @intCast(pane.wrap_col[last]), wrapWidth(pane, pane.view.wrap) -| pane.wrap_pad[last]) };
}
/// A call stack's row after its line's first starts with its tree's guide
/// (locations.treeContinuation), in `buffer`; any other row with none.
fn guideOf(f: *const State, text: []const u8, at: usize, width: usize, buffer: *[1024]u8) []const u8 {
if (at == 0 or width <= 1 or f.output == null or !std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) return "";
return locations.treeContinuation(text, buffer, width - 1);
}
/// `pane` out of its Follow chain (Unfollow, or a chain down to it): a
/// plain twin with the scroll it has.
pub fn unchain(pane: *Pane) void {
pane.file.?.follow = false;
pane.follow_edges = 0;
pane.follow_crossed = false;
dropUnfollow(pane);
}
/// The Unfollow word Follow gave a pane's tag (builtins.Follow), gone, with
/// the blank before it (after it, first in the tag's own text).
fn dropUnfollow(pane: *Pane) void {
const own = pane.tag.own orelse return;
const word = std.mem.indexOf(u8, own, "Unfollow") orelse return;
const word_end = word + "Unfollow".len;
const blank_after = word_end < own.len and std.mem.indexOfScalar(u8, " \t\n", own[word_end]) != null;
if (word_end < own.len and !blank_after) return;
if (word > 0 and own[word - 1] != ' ') return;
const at = if (word > 0) word - 1 else word;
const end = if (word == 0 and blank_after) word_end + 1 else word_end;
const cut = std.mem.concat(pane.gpa, u8, &.{ own[0..at], own[end..] }) catch return;
pane.gpa.free(own);
pane.tag.own = cut;
}
/// Whether `head`, a text's first bytes, holds a diff, as a command pane's
/// rows are told one (diff.looksLikeDiff, its first 200 lines).
pub fn looksLikeDiff(head: []const u8) bool {
var lines: [200][]const u8 = undefined;
var it = std.mem.splitScalar(u8, head, '\n');
var n: usize = 0;
while (n < lines.len) : (n += 1) lines[n] = it.next() orelse break;
return diff.looksLikeDiff(lines[0..n]);
}
/// Where the pane is in its text and what the text is saved as now: an
/// undo step's edge (Text.Place), kept once, never a copy of the text.
fn placeOf(pane: *const Pane, f: *const State) Text.Place {
// In the file's rows: an undo step is the file's (undoStep takes it
// with the layer's lines out).
var vsel = pane.body.vsel;
vsel.row = @intCast(fileRow(f, @intCast(@max(0, vsel.row))));
return .{
.cur_row = @intCast(fileRow(f, @intCast(@max(0, pane.body.cur_row)))),
.cur_col = if (readOnlyRow(f, @intCast(@max(0, pane.body.cur_row))) != null) 0 else pane.body.cur_col,
.vsel = vsel,
.gen = f.history.gen,
.clean = f.revision == f.saved_revision,
.saved_hash = f.saved_hash,
.saved_len = f.saved_len,
};
}
/// After a step's text went in: if it was under another name, that name
/// back, and the step's saved state with it (Get file, Edit's e), as acme's
/// undo puts them back with the text.
fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Text.Place) void {
const history = f.history;
if (snap.gen == history.gen) return;
// The latest name kept for that generation.
var at = history.names.items.len;
const path = while (at > 0) {
at -= 1;
if (history.names.items[at].gen == snap.gen) break history.names.items[at].path;
} else return;
if (std.mem.eql(u8, path, f.path)) {
history.gen = snap.gen;
return;
}
const id = for (p.panes, 0..) |slot, i| {
if (slot == pane) break i;
} else return;
// nameBuffer frees nothing of `path`: it keeps the name it ends.
const back = p.gpa.dupe(u8, path) catch |err| return p.reportError(.at(id), "undo", err);
defer p.gpa.free(back);
pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch |err| return p.reportError(.at(id), "undo", err);
history.gen = snap.gen;
f.saved_hash = snap.saved_hash;
f.saved_len = snap.saved_len;
f.saved_revision = if (snap.clean) f.revision else f.revision -% 1;
f.disk_newer = null;
f.disk_newer_warned = false;
if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = .at(id), .on = true } });
}
pub fn restoreSnap(tab: u16, pane: *Pane, f: *State, snap: Text.Place) void {
const n = nlines(pane.gpa, f);
const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1);
const llen = modal.lineSlice(f.content, row).len;
pane.body.cur_row = @intCast(row);
pane.body.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen));
pane.body.vsel = snap.vsel;
pane.body.cur_pinned = true;
pane.body.sticky_col = -1;
pane.ensureCursorVisible(tab);
}
/// An undo step's edge, made before an edit (Text.Journal.mark): the edits
/// after it are one step back to the pane's place now.
pub fn pushUndo(p: *Pardes, pane: *Pane) error{OutOfMemory}!void {
const f = if (pane.file) |*file| file else return;
try f.history.journal.mark(p.gpa, try fileText(f, p.scratch.allocator()), placeOf(pane, f));
}
/// Undo (back) or redo one step: its edits turned round in the text, and the
/// place and name it began at (or, redone, was undone from) back. The
/// journal is the file's: with the layer's lines shown, the step is taken
/// with them out, and they come back after it where its lines went.
pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) error{OutOfMemory}!void {
const f = if (pane.file) |*file| file else return;
const j = &f.history.journal;
if (if (back) j.done == 0 else j.done == j.steps.items.len) return;
const at = if (back) j.done - 1 else j.done;
const now = placeOf(pane, f);
const layer = f.layer.owner;
if (layer != 0) jj.hideLayer(p, f);
defer if (layer != 0) jj.showLayer(p, f, layer);
if (!turn(p, f, at, back)) return error.OutOfMemory;
const s = &j.steps.items[at];
if (back) {
s.after = now;
j.done -= 1;
} else {
s.before = now;
j.done += 1;
}
const to = if (back) s.before else s.after;
restoreName(p, pane, f, to);
restoreSnap(p.settings.tab, pane, f, to);
}
/// Step `at`'s entries turned round in `f`'s text: each one's bytes put
/// back and the bytes it had put in kept in its place, an undo's last first
/// and a redo's first first. One entry is turned in place, its bytes alone
/// moved; several in a copy of the text whose gap goes from one to the next
/// (`Gap`), put in as one edit; none is an edit that changes nothing, as
/// the snapshot equal to the text was put in once. A step that began by
/// replacing the text whole has kept its old buffer: that buffer goes back
/// in and the step becomes one swap the other way, holding the text it
/// ended on for its redo, and no byte moves. False with no memory, nothing
/// changed.
fn turn(p: *Pardes, f: *State, at: usize, back: bool) bool {
const j = &f.history.journal;
const step = j.steps.items[at];
const entries = j.entries.items[step.first..][0..step.n];
if (entries.len == 0) return edit(p, f, f.content.len, 0, "", null, false, null, .load);
if (entries[0].swap and (back or entries.len == 1)) {
const e = &entries[0];
const now_len = f.content.len;
const back_len = e.removed.len;
const span = spanOf(f.content, e.removed);
var out: []u8 = undefined;
if (!edit(p, f, span.head, now_len - span.head - span.tail, e.removed[span.head .. back_len - span.tail], e.removed.ptr[0..@max(e.room, back_len)], false, &out, .load)) return false;
j.fold(p.gpa, at);
e.* = .{ .off = 0, .removed = out[0..now_len], .ins = back_len, .swap = true, .room = out.len };
return true;
}
if (entries.len == 1) {
const e = &entries[0];
const put = pardes.memory.dupeUnfilled(p.gpa, f.content[e.off..][0..e.ins]) catch return false;
if (!edit(p, f, e.off, e.ins, e.removed, null, false, null, .load)) {
pardes.memory.freeRaw(p.gpa, put);
return false;
}
j.bytes = j.bytes - e.removed.len + put.len;
e.ins = e.removed.len;
pardes.memory.freeRaw(p.gpa, e.removed);
e.removed = put;
return true;
}
// The gap's room: what the entries put back past what they take out.
var room: usize = 0;
for (entries) |e| room += e.removed.len -| e.ins;
var gap = Gap.init(p.gpa, f.content, room) catch return false;
const puts = p.scratch.allocator().alloc([]u8, entries.len) catch {
pardes.memory.freeRaw(p.gpa, gap.buf);
return false;
};
@memset(puts, &.{});
for (0..entries.len) |k| {
const i = if (back) entries.len - 1 - k else k;
const e = entries[i];
puts[i] = gap.replace(p.gpa, e.off, e.ins, e.removed) catch {
for (puts) |put| pardes.memory.freeRaw(p.gpa, put);
pardes.memory.freeRaw(p.gpa, gap.buf);
return false;
};
}
const new = gap.whole();
const span = spanOf(f.content, new);
if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], gap.buf, false, null, .load)) {
for (puts) |put| pardes.memory.freeRaw(p.gpa, put);
pardes.memory.freeRaw(p.gpa, gap.buf);
return false;
}
for (entries, puts) |*e, put| {
const was = e.*;
e.* = .{ .off = was.off, .removed = put, .ins = was.removed.len };
j.bytes = j.bytes - Text.Journal.held(was) + Text.Journal.held(e.*);
Text.Journal.free(p.gpa, was);
}
return true;
}
/// A copy of a text with a gap where it was last written (`turn`): moving
/// the gap costs the bytes between two places, never the text, so a step of
/// many entries (a key typed at many ranges) is turned in one pass.
const Gap = struct {
/// The text is `buf[0..lo]` then `buf[hi..]`.
buf: []u8,
lo: usize,
hi: usize,
fn init(gpa: std.mem.Allocator, bytes: []const u8, room: usize) !Gap {
const buf = try pardes.memory.unfilled(gpa, bytes.len + room);
@memcpy(buf[0..bytes.len], bytes);
return .{ .buf = buf, .lo = bytes.len, .hi = buf.len };
}
fn move(g: *Gap, at: usize) void {
if (at < g.lo) {
const n = g.lo - at;
@memmove(g.buf[g.hi - n .. g.hi], g.buf[at..g.lo]);
g.lo = at;
g.hi -= n;
} else if (at > g.lo) {
const n = at - g.lo;
@memmove(g.buf[g.lo..][0..n], g.buf[g.hi..][0..n]);
g.lo += n;
g.hi += n;
}
}
/// The `len` bytes at `at` replaced by `bytes` (in the room `init` was
/// given); what they were, copied out.
fn replace(g: *Gap, gpa: std.mem.Allocator, at: usize, len: usize, bytes: []const u8) ![]u8 {
g.move(at);
const out = try pardes.memory.dupeUnfilled(gpa, g.buf[g.hi..][0..len]);
g.hi += len;
@memcpy(g.buf[g.lo..][0..bytes.len], bytes);
g.lo += bytes.len;
return out;
}
/// The text whole, at the buffer's start.
fn whole(g: *Gap) []u8 {
g.move(g.lo + (g.buf.len - g.hi));
return g.buf[0..g.lo];
}
};
/// A pane's file deleted on disk: the text stays, and it says so once,
/// `<file> deleted on disk (Save writes it again)`, logged `changed
/// <serial> deleted`.
pub const deleted = pardes.tape.taped(deletedInner);
fn deletedInner(p: *Pardes, id: Pane.Id) void {
const pane = p.panes[id.index()] orelse return;
const f = if (pane.file) |*file| file else return;
if (f.disk_gone) return;
f.disk_gone = true;
var said: pardes.Kind.Buf(limits.host_path_cap + 64) = .{};
p.setMessage(id, said.print("{s} deleted on disk (Save writes it again)", .{f.path[0..@min(f.path.len, limits.host_path_cap)]}));
var rec: [32]u8 = undefined;
pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} deleted", .{pane.serial}) catch unreachable); // a u32 fits 32
}
/// A file rewritten on disk. A clean buffer takes the new text, committed
/// onto the same undo history as typed edits. A buffer with unsaved edits
/// is never reloaded under them: it keeps its text and stays dirty, and
/// says so once (`<file> changed on disk (get reloads it, Save overwrites
/// it)`, logged `changed <serial>`); get then asks before throwing
/// the edits away and Save before overwriting the newer file. acme reloads
/// nothing by itself: its get asks (winclean) and its Put refuses a file
/// modified since it was read (exec.c:577).
pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void {
const pane = p.panes[id] orelse return;
const f = if (pane.file) |*file| file else return;
f.disk_gone = false;
if (fileEql(f, bytes)) return;
if (f.saved_hash) |saved| if (f.revision != f.saved_revision and fileHash(f) != saved) {
const disk = std.hash.Wyhash.hash(0, bytes);
// The disk holds what the text was read or saved as: no news, only
// a watch looking again (an undo back to this name, a restart).
if (disk == saved) return;
if (f.disk_newer == disk) return;
f.disk_newer = disk;
f.disk_newer_warned = false;
// A question in its tag, never the keyboard's (pick-ui SPEC §10.2):
// one waiting already is the one about it.
if (p.messages.waiting(pane) == null) pardes.Messages.say(p, .question, id, "changed on disk").asks = .disk;
var rec: [16]u8 = undefined;
pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d}", .{pane.serial}) catch unreachable); // a u32 fits 16
return;
};
f.disk_newer = null;
// Logged as the dirty case is, with what became of it.
var rec: [32]u8 = undefined;
pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch unreachable); // a u32 fits 32
pushUndo(p, pane) catch |err| return p.reportError(.at(id), "reload", err);
const new = p.gpa.dupe(u8, bytes) catch |err| return p.reportError(.at(id), "reload", err);
load(p, f, new);
f.saved_revision = f.revision;
restoreSnap(p.settings.tab, pane, f, .{ .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel });
}
/// re-highlight the visible window of any file whose syntax went stale
/// (edit, scroll, load) — visible-range-first so big files stay snappy
/// The declarations a TreeContext pane's context rows are drawn from, for
/// its text as it is now: found in the step (Pardes.sync), never only by a
/// render, since the view's geometry is made of them (`geometry`).
pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void {
if (!f.tree_context or !supportsContext(pane) or f.context.revision == f.revision) return;
// The file's declarations, in its lines (the layer's are none of it).
f.context.replace(p.tree_sitter_gpa, syntax.context(p.tree_sitter_gpa, f.path, fileText(f, p.scratch.allocator()) catch return) catch return, f.revision);
}
pub fn refreshHighlights(p: *Pardes) void {
const tz = tracy.zone(@src(), "refreshHighlights");
defer tz.end();
for (p.panes) |slot| {
const pane = slot orelse continue;
if (pane.file == null) continue;
const f = &pane.file.?;
if (f.mini != null) {
f.syntax_dirty = false;
continue;
}
if (!f.syntax_dirty) continue;
// ponytail: a stretch over `long_paint` bytes (a minified line) is
// painted only around the caret, so a key typed in a 500 KB line
// parses 16 KB, not the line (190 ms a key in ReleaseSafe; 25 ms at
// 64 KB, so 16, still eight views of 80x25); its first
// tokens may be coloured as if the line began there. The upgrade: an
// incremental parse of the whole text, edited in place.
const caret = @min(f.content.len, lineStart(p.gpa, f, @intCast(@max(0, pane.body.cur_row))) + @as(usize, @intCast(@max(0, pane.body.cur_col))));
const around = struct {
fn clamp(a: usize, b: usize, at: usize) [2]usize {
if (b - a <= long_paint) return .{ a, b };
const lo = std.math.clamp(at -| long_paint / 2, a, b - long_paint);
return .{ lo, lo + long_paint };
}
};
const need = around.clamp(lineStart(p.gpa, f, f.scroll), @max(lineStart(p.gpa, f, f.scroll), lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)), caret);
const need_start = need[0];
const need_end = need[1];
if ((!f.tree_context or (f.highlight_start == 0 and f.highlights.len == f.content.len)) and
f.highlights.len > 0 and need_start >= f.highlight_start and
need_end <= f.highlight_start + f.highlights.len)
{
f.syntax_dirty = false;
if (!f.tree_context and pane.colorAlgo() == .source) paintAhead(p, pane, f);
continue;
}
if (f.layer.lines.len > 0) {
highlightLayered(p, pane, f);
continue;
}
// A view far from what is painted (a jump: ge, a Look) paints only
// itself on the frame, a third of the work; the stretch around it
// comes painted ahead (paintAhead) where there are workers.
const far = f.highlights.len == 0 or need_end <= f.highlight_start or need_start >= f.highlight_start + f.highlights.len;
const slack: usize = if (far and p.tape.has(p, .search)) 0 else if (f.highlights.len == 0) 0 else pane.rows;
const whole = pane.colorAlgo() == .locations or f.tree_context;
// Painted ahead on a worker (Stream.paintAhead): taken, no parse.
if (!whole and pane.colorAlgo() == .source) if (Stream.takeAhead(p, pane.serial, f.revision, need_start, need_end)) |got| {
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = got.styles;
f.highlight_start = got.start;
f.syntax_dirty = false;
p.stream.painted_ahead += 1;
paintAhead(p, pane, f);
continue;
};
if (pane.colorAlgo() == .source and !whole) p.stream.painted_on_loop += 1;
const wide_start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack);
const wide_end = if (whole)
f.content.len
else
@max(wide_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack));
const window = if (whole) [2]usize{ wide_start, wide_end } else around.clamp(wide_start, wide_end, caret);
const start = window[0];
const end = window[1];
const new_highlights = (switch (pane.colorAlgo()) {
.none => @as([]u8, &.{}),
.diff => syntax.highlightDiff(p.tree_sitter_gpa, f.content, start, end),
.locations => if (f.location_rows.len > 0)
syntax.highlightLocationRows(p.tree_sitter_gpa, f.content, f.location_rows)
else
syntax.highlightLocations(p.tree_sitter_gpa, f.content, start, end),
else => syntax.highlightFileRange(p.tree_sitter_gpa, langPath(f), f.content, start, end),
}) catch {
f.syntax_dirty = false;
continue;
};
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = new_highlights;
f.highlight_start = if (f.highlights.len > 0) start else 0;
f.syntax_dirty = false;
if (!whole and pane.colorAlgo() == .source) paintAhead(p, pane, f);
}
}
/// The stretch a scroll of `pane` is heading into, the view and three more
/// the way it last went, asked of a worker (Stream.paintAhead) so it is
/// painted by the time the view gets there. From the view itself: two
/// views out, an upward stretch stopped short of the view's own bottom
/// rows, and a half page up (or down) missed it by a line and painted on
/// the frame, 11-17 ms in ReleaseSafe.
fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void {
// A worker paints the buffer: with the layer's lines in it, never.
if (f.layer.lines.len > 0) return;
const seen = &p.stream.ahead_seen;
// A view standing still (typing in it) needs nothing ahead: each edit
// is a new revision, and a paint asked at every keystroke was a copy
// of the stretch and a worker's start on the loop per key.
if (seen.serial == pane.serial and f.scroll == seen.scroll) return;
if (seen.serial == pane.serial) seen.dir = if (f.scroll > seen.scroll) 1 else -1;
if (seen.serial != pane.serial) seen.dir = 1;
seen.serial = pane.serial;
seen.scroll = f.scroll;
const rows: usize = pane.rows;
const start = lineStart(p.gpa, f, if (seen.dir > 0) f.scroll else f.scroll -| 3 * rows);
const end = @max(start, lineStart(p.gpa, f, f.scroll + (if (seen.dir > 0) 4 * rows else rows) + SYNTAX_CONTEXT_AFTER_ROWS));
// Painted already, as far as that goes.
if (f.highlights.len > 0 and start >= f.highlight_start and end <= f.highlight_start + f.highlights.len) return;
Stream.paintAhead(p, pane.serial, f.revision, langPath(f), f.content, start, end);
}
/// The layer's lines shown (`read_only`): the file's text parsed for its
/// colours, never they (a line a change took away is no line of the
/// file's syntax: an unmatched brace in one would colour what follows),
/// the colours laid out in the buffer around them and none on them
/// (jj.paint inks them): the view's stretch and a view either side of it,
/// on the loop (a worker paints the buffer, paintAhead).
fn highlightLayered(p: *Pardes, pane: *Pane, f: *State) void {
f.syntax_dirty = false;
const rows: usize = pane.rows;
const start = if (f.tree_context) 0 else lineStart(p.gpa, f, f.scroll -| rows);
const end = if (f.tree_context) f.content.len else @max(start, lineStart(p.gpa, f, f.scroll + 2 * rows + SYNTAX_CONTEXT_AFTER_ROWS));
const text = fileText(f, p.scratch.allocator()) catch return;
const file_start = fileOffset(f, start);
const got = syntax.highlightFileRange(p.tree_sitter_gpa, langPath(f), text, file_start, fileOffset(f, end)) catch return;
defer p.tree_sitter_gpa.free(got);
const out = p.tree_sitter_gpa.alloc(u8, end - start) catch return;
@memset(out, 0);
// The file's bytes between the read-only lines, a stretch at a time.
var from: usize = 0;
var at = start;
for (f.layer.lines) |r| {
if (r.at + r.len <= start) continue;
if (r.at >= end) break;
const n = @min(r.at -| at, got.len -| from);
@memcpy(out[at - start ..][0..n], got[from..][0..n]);
from += n;
at = @max(at, @min(end, r.at + r.len));
}
const n = @min(end - at, got.len -| from);
@memcpy(out[at - start ..][0..n], got[from..][0..n]);
if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights);
f.highlights = out;
f.highlight_start = start;
}
/// The path a text's language is known by: a file at a revision's
/// (jj.zig) without its `@rev`.
pub fn langPath(f: *const State) []const u8 {
return if (jj.of(f)) |r| r.path else f.path;
}
pub fn supportsContext(pane: *const Pane) bool {
const file = pane.file orelse return false;
return file.output == null and file.mini == null and syntax.supportsPath(file.path);
}
fn prepareContextRows(pane: *Pane, file: *State) void {
pane.context_rows = 0;
if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return;
const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row
// The declarations are the file's lines; the rows, the buffer's.
const top_line = fileRow(file, file.scroll);
for (file.context.declarations) |declaration| {
if (declaration.start_line >= top_line) break;
if (declaration.end_line < top_line) continue;
var line = declaration.start_line;
while (line <= declaration.header_end_line and line < top_line) : (line += 1) {
if (pane.context_rows >= capacity) return;
const row = bufferRow(file, line);
if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue;
pane.wrap_line[pane.context_rows] = @intCast(row);
pane.context_rows += 1;
}
}
}
pub fn wrapWidth(pane: *const Pane, wrap: bool) usize {
if (!wrap or pane.rows > pane.wrap_line.len) return 0;
return @max(1, @as(usize, pane.cols -| gutterWidth(pane)) -| 1);
}
pub const VisualRow = struct { start: usize, end: usize };
pub fn visualRow(tab: u16, line: []const u8, col: usize, width: usize) VisualRow {
if (width == 0) return .{ .start = 0, .end = line.len };
var start: usize = 0;
while (true) {
const end = fitEnd(tab, line, start, width);
if (col < end or end >= line.len) return .{ .start = start, .end = end };
start = end;
}
}
/// The body's text as it is shown: its geometry's rows, each a line's
/// number and its stretch of the line.
pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const u8 {
geometry(tab, pane);
const out = try arena.alloc(u8, pane.geometry_len);
const width = wrapWidth(pane, pane.view.wrap);
const filled = if (f.layer.lines.len == 0) fillBody(false, tab, out, pane, f, width, false) else fillBody(true, tab, out, pane, f, width, false);
std.debug.assert(filled == out.len);
return out;
}
/// The pane's view geometry for its state as it is now: the wrap map (the
/// line, column and pad each body row starts at), the context rows, and how
/// many rows the body layer has. Made again when anything it is made of
/// changes (`geometryKey`), by whoever asks first, the render or a step that
/// reads it: so a core that never draws has the geometry of one that does
/// (docs/next-daemon.md). What it reads of the session is the pane's `view`,
/// which each step sets.
pub fn geometry(tab: u16, pane: *Pane) void {
const f = if (pane.file) |*file| file else return;
const key = geometryKey(tab, pane, f);
if (pane.geometry_key == key) return;
pane.geometry_key = key;
// The key of what the map was made from: the walk brings the text's
// index and tables up to it (`line_starts`, `tables.revision`, in the
// key), and with the key from before, a step's second ask made it all
// again. The top's row it found or took is that key's too.
defer {
const made = geometryKey(tab, pane, f);
pane.top_skip.key = made;
pane.geometry_key = made;
}
pane.body_rows = 0;
pane.body_visible_rows = 0;
pane.context_row_limit = null;
pane.geometry_len = mapRows(tab, pane, f);
// A body with context rows is a layer taller than the grid's rows, its
// context rows at the tagline's height (body_layer.joinBody).
const v = pane.view;
if (!v.layered or pane.collapsed or v.rect_h <= pane.tag_rows) return;
const logical_rows = @min(@as(usize, pane.rows) + pane.context_rows, pane.wrap_line.len);
if (pane.context_rows == 0 or logical_rows <= pane.context_rows) return;
pane.body_rows = @intCast(logical_rows);
const bh: usize = @max(1, v.body_h);
const th: usize = std.math.clamp(v.tagline_h, 1, bh);
const body_pixels = @as(usize, v.rect_h - pane.tag_rows) * bh;
const limit: u16 = @intCast(@min(pane.context_rows, (body_pixels -| bh) / th));
pane.context_row_limit = limit;
pane.body_visible_rows = @intCast(@min(logical_rows, limit + @max(1, (body_pixels -| @as(usize, limit) * th) / bh)));
pane.geometry_len = mapRows(tab, pane, f);
}
/// One walk of the rows the body shows, recording the wrap map: the bytes
/// its text takes.
fn mapRows(tab: u16, pane: *Pane, f: *State) usize {
const width = wrapWidth(pane, pane.view.wrap);
pane.body_wrapped = width > 0;
f.tables.ensure(tab, pane.gpa, f);
prepareContextRows(pane, f);
return if (f.layer.lines.len == 0) fillBody(false, tab, null, pane, f, width, true) else fillBody(true, tab, null, pane, f, width, true);
}
/// Everything the geometry is made of, hashed: the text (its revision and
/// length), where it is scrolled, the pane's size, the tab's width, its
/// tables, its context declarations, the session's view.
fn geometryKey(tab: u16, pane: *const Pane, f: *const State) u64 {
const t = &f.tables;
const facts = .{
f.revision, f.content.len, f.scroll, pane.hscroll,
pane.rows, pane.cols, pane.tag_rows, pane.collapsed,
pane.query != null, f.pager, f.mini != null, f.output != null,
if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0,
f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len,
pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h,
pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, tab,
};
// One hash of them laid out as words: every reader of the map asks for
// this key, a hundred times a frame.
var words: [facts.len]u64 = undefined;
inline for (facts, &words) |fact, *w| w.* = if (@TypeOf(fact) == bool) @intFromBool(fact) else if (@typeInfo(@TypeOf(fact)).int.signedness == .signed) @bitCast(@as(i64, fact)) else fact;
// Never the "made for nothing" key a reset leaves (`geometry_key = 0`).
return std.hash.Wyhash.hash(0x9e0, std.mem.sliceAsBytes(&words)) | 1;
}
/// Run the file-body row walk. With no destination it is the exact sizing
/// pass; with one it fills that allocation and records the wrapping map.
/// A read-only line (the `Changes` layer's) is a line as any, wrapped as
/// any; the numbers are the file's, and it has none (`layered`: a body with
/// none walks without asking: beside that walk its loop compiled worse, a
/// row walk of a file with no layer 2% dearer).
fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize {
if (record_wrap) pane.wrap_n = 0;
const prefix_width = gutterWidth(pane);
// Where a number ends: a blank, then the heat lane and the lanes after it.
const number_end = prefix_width -| laneCells(pane) -| pane.layers.heat -| 1;
const total = nlines(pane.gpa, f);
// The slot after the text's last newline, found once: every numbered
// row below asks whether it is that one.
const end_slot: usize = if (total > 0 and endSlot(pane, total - 1)) total - 1 else std.math.maxInt(usize);
var body_line: usize = f.scroll;
// The top line from the view's row in it (`top`): walked once a
// geometry (the map's pass), its text's pass a frame starting there.
var body_at: usize = topSkip(tab, pane).at;
var written: usize = 0;
var guide_buffer: [1024]u8 = undefined;
for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| {
if (i > 0) {
if (dst) |out| out[written] = '\n';
written += 1;
}
const context = i < pane.context_rows;
const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line;
const at = if (context) 0 else body_at;
const text = if (row < total) sourceLine(pane, @intCast(row)) else "";
const guide = guideOf(f, text, at, width, &guide_buffer);
const pad = displayWidth(tab, guide);
// Headers use one screen row per source row, preserving signatures
// without allowing a long ancestor to consume the whole viewport.
const end = if (width == 0 or context) text.len else fitEnd(tab, text, at, width - pad);
const cut = if (pane.hscroll > 0 and width == 0)
modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len))
else
at;
if ((width > 0 or pane.context_rows > 0) and record_wrap) {
pane.wrap_line[i] = @intCast(row);
pane.wrap_col[i] = @intCast(cut);
pane.wrap_pad[i] = @intCast(pad);
pane.wrap_n = @intCast(i + 1);
}
if (row < total) {
// The number only where the text is wanted: a geometry pass (no
// `dst`, a hundred a frame) counts its cells and nothing more.
if (dst) |out| {
const prefix = out[written..][0..prefix_width];
@memset(prefix, ' ');
// A read-only line has no number; the others, the file's.
const numbered = !layered or readOnlyRow(f, row) == null;
if (at == 0 and prefix.len > 0 and numbered) {
var lineno = (if (layered) fileRow(f, row) else row) + 1;
var digit: usize = number_end;
if (row == end_slot) {
prefix[digit - 1] = '~';
} else while (true) {
digit -= 1;
prefix[digit] = '0' + @as(u8, @intCast(lineno % 10));
lineno /= 10;
if (lineno == 0) break;
}
}
}
written += prefix_width;
if (dst) |out| @memcpy(out[written..][0..guide.len], guide);
written += guide.len;
// A table row's pads are blanks before their bytes: the row
// drawn as the column functions above measure it.
var pad_buf: [Tables.max_pads]Tables.Pad = undefined;
var from = cut;
for (rowPads(tab, pane, @intCast(row), &pad_buf)) |table_pad| {
if (table_pad.at <= cut) continue;
if (table_pad.at > end) break;
if (dst) |out| @memcpy(out[written..][0 .. table_pad.at - from], text[from..table_pad.at]);
written += table_pad.at - from;
if (dst) |out| @memset(out[written..][0..table_pad.cells], ' ');
written += table_pad.cells;
from = table_pad.at;
}
const shown = text[from..end];
if (dst) |out| @memcpy(out[written..][0..shown.len], shown);
written += shown.len;
}
if (!context) {
if (width > 0 and end < text.len) {
body_at = end;
} else {
body_line += 1;
body_at = 0;
}
}
}
return written;
}
/// The layers a file's body wears in a view (`Pane.layers`, each view its
/// own: views.zig). Not Layer.zig's band of cells: these are the painters
/// over a body's text, in this order, each in its own place:
///
/// 1. ink: each code cell's colour, from tree-sitter (syntax.zig's
/// highlightFileRange): on until `Syntax` turns it off;
/// 2. patch: a diff's or a patch's grounds, a `+`/`-` row's ground and
/// marker and the words a changed line changed (syntax.zig's
/// highlightDiff): always, in a diff (with `Syntax` off its bytes are
/// made without the language's ink: highlightDiffPlain).
///
/// Both are painted in recolorSyntax's one walk over the cells, each where
/// it says (one walk per painter cost a frame a sixth more).
///
/// 3. changes (`Changes [revset]`, jj.zig): while `lanes` is set, a
/// lane each of the pane's pinned changes after the line number (the
/// gutter `lanes` cells wider), a line one added whole green across
/// it, a changed line's words, and the ghost lines (the buffer's
/// read-only lines, `State.layer.lines`) inked (jj.paint).
/// 4. churn (`Churn`): a heat lane after the number and a strip by the
/// scroll thumb.
///
/// Two bytes, hashed in one update: a digest takes every view's of every
/// pane at every step.
pub const Layers = struct {
ink: bool = true,
/// Whether the pane shows its pinned changes (`Pardes.changes`: the
/// revset and jj's answers are the pane's, and shown, their lines are
/// its buffer's, so every view of it shows them or none does:
/// jj.setLanes), as the cells their lanes take in this view
/// (laneCells), 0 while it does not: by the view's frontend, in a window
/// two, which its strips of pixels fill one and a half of
/// (Surface.Lane), in a terminal three, a glyph each.
lanes: u8 = 0,
/// Whether this view shows the pane's churn (`Churn`, jj.Heat), as the
/// cells its lane takes: one after the number, before the lanes.
heat: u8 = 0,
pub fn digest(l: *const Layers, h: *pardes.walk.Hasher) void {
h.update(&.{ @intFromBool(l.ink), l.lanes, l.heat });
}
};
pub const SynStyle = struct { fg: [3]u8, bold: bool };
pub fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle {
if (sy == .none) return null;
return .{ .fg = p.chrome().syntax[@intFromEnum(sy)], .bold = false };
}
/// syntax colors: recolor each content cell from its tree-sitter style byte;
/// content starts after the lineno gutter
pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
// The ink off (`Syntax`): a file's style bytes are not read, so a cell
// asks nothing of it (a test a cell cost a frame 0.1 to 0.5%); a
// patch's are made again without the language's, once a paint, its
// grounds, markers and changed words kept.
const highlights: []const u8 = if (pane.layers.ink)
(if (f.mini) |mini| mini.colors else f.highlights)
else if (pane.colorAlgo() == .diff and f.highlights.len > 0)
syntax.highlightDiffPlain(p.scratch.allocator(), f.content, f.highlight_start, f.highlight_start + f.highlights.len) catch &.{}
else
&.{};
const highlight_start = if (f.mini != null) 0 else f.highlight_start;
const spans = f.pager_spans;
if (highlights.len == 0 and f.output == null and spans.len == 0) return;
const prefix_width = gutterWidth(pane);
const tz_recolor = tracy.zone(@src(), "synRecolor");
defer tz_recolor.end();
// A row whose first byte names a hue (syntax.ground_add, _del): its
// grounds, the chrome's (R10).
const chrome = p.chrome();
const ink = ansi.inkOf(p);
var filtered_storage: pardes.Term.Filter = undefined;
const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: {
filtered_storage = pardes.Term.filter(&ink, &p.tty_filter_palette);
break :blk &filtered_storage;
} else null;
// indexed start, same as bodyText — an empty tail simply paints nothing
var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n');
const total = nlines(p.gpa, f);
const body_y = p.bodyTop(pane, r);
var vr: u16 = 0;
while (vr < body_h) : (vr += 1) {
var base: usize = undefined;
var line: []const u8 = undefined;
var hs: usize = @intCast(@max(0, pane.hscroll));
var limit: usize = undefined;
if (pane.wrap_n == 0) {
line = flines.next() orelse break;
base = @intFromPtr(line.ptr) - @intFromPtr(f.content.ptr);
limit = line.len;
} else {
if (vr >= pane.wrap_n) break;
if (pane.wrap_col[vr] < 0) continue;
const lrow: usize = @intCast(@max(0, pane.wrap_line[vr]));
if (lrow >= total) break;
base = lineStart(p.gpa, f, lrow);
const lend = if (lrow + 1 < total) lineStart(p.gpa, f, lrow + 1) -| 1 else f.content.len;
line = f.content[base..lend];
hs = @intCast(pane.wrap_col[vr]);
limit = if (vr + 1 < pane.wrap_n and pane.wrap_line[vr + 1] == pane.wrap_line[vr])
@min(line.len, @as(usize, @intCast(pane.wrap_col[vr + 1])))
else
line.len;
}
hs = modal.graphemeStart(line, @min(hs, line.len));
const row_index: usize = @intCast(@max(0, pane.wrapAt(p.settings.tab, vr).line));
const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null;
const decoration = Output.decorateRow(f.output, line, metadata);
const decorated = !decoration.plain();
// The row's first byte: its hue and its ground, on every wrapped
// row of it (syntax.ground_add).
const lead: u8 = if (base >= highlight_start and base - highlight_start < highlights.len) highlights[base - highlight_start] else 0;
const tint: ?*const Colors.Chrome.Diff = if (lead & syntax.ground_add != 0) &chrome.add else if (lead & syntax.ground_del != 0) &chrome.del else null;
// 2, the patch: the row's ground.
if (tint) |t| if (prefix_width < tw) {
const ground: ?[3]u8 = if (lead & syntax.ground_emph != 0) t.row else if (lead & syntax.ground_line != 0) t.line else null;
if (ground) |g| s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), g, null);
};
// A +Pager's own colours (Term.page) on every row but one in a hue:
// an added or removed line is drawn as pardes draws a diff, and
// git's red and green on it would only fight the tint.
var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.Term.Span, spans, base + hs, struct {
fn before(at: usize, span: pardes.Term.Span) bool {
return span.end <= at;
}
}.before);
var c: usize = 0;
const pad: usize = if (vr < pane.wrap_n) pane.wrap_pad[vr] else 0;
for (0..@min(pad, tw -| prefix_width)) |col| {
s.at(tx + @as(u16, @intCast(prefix_width + col)), body_y + vr).style.fg = .{ .rgb = chrome.page.dim };
}
var screen_c: usize = pad;
var table_buf: [Tables.max_pads]Tables.Pad = undefined;
const table_pads = rowPads(p.settings.tab, pane, @intCast(row_index), &table_buf);
var table_at: usize = 0;
while (hs + c < limit and prefix_width + screen_c < tw) {
while (table_at < table_pads.len and table_pads[table_at].at < hs + c) table_at += 1;
if (table_at < table_pads.len and table_pads[table_at].at == hs + c and hs + c > hs) {
screen_c += table_pads[table_at].cells;
table_at += 1;
if (prefix_width + screen_c >= tw) break;
}
const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c));
const cells = graphemeDisplayWidth(p.settings.tab, line[hs + c .. grapheme_end]);
const idx = base + hs + c;
// Each painter (the syntax colour, a diff's emphasis ground, a
// result's emphasis, a +Pager's colours) loops over the cells
// only when it paints: one loop asking all four on every cell
// cost the frame a sixth more instructions (zig build perf,
// render on the medium file).
if (idx >= highlight_start) {
const hidx = idx - highlight_start;
if (hidx < highlights.len) {
// 1, the ink; a patch row's marker is 2's.
if (if (tint != null and hs + c == 0)
SynStyle{ .fg = tint.?.ink, .bold = true }
else
synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss|
{
var fill: usize = 0;
while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) {
const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr);
if (cell.default) continue;
cell.style.fg = .{ .rgb = ss.fg };
cell.style.bold = ss.bold;
}
}
// 2, the patch: a changed word's ground.
if (tint) |t| if (highlights[hidx] & syntax.ground_emph != 0 and hs + c > 0) {
var fill: usize = 0;
while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1)
s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph };
};
}
}
// Results keep their exact live text. Only the location,
// matched source range and diagnostic label gain emphasis.
if (if (decorated) decoration.styleAt(chrome, hs + c) else null) |style| {
var fill: usize = 0;
while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) {
const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr);
if (cell.default) continue;
cell.style.fg = style.fg;
cell.style.bold = style.bold;
if (style.bg != .default) cell.style.bg = style.bg;
}
}
while (span_at < spans.len and spans[span_at].end <= idx) span_at += 1;
if (span_at < spans.len and spans[span_at].start <= idx) {
const st = spans[span_at].style;
var fill: usize = 0;
while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) {
const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr);
if (cell.default) continue;
// As a terminal pane's cell: through Filter, or a
// palette colour through the theme's sixteen and
// truecolor as it is.
if (filtered) |colors| {
if (st.fg != .default) cell.style.fg = pardes.Term.spanColor(colors, st.fg, false);
if (st.bg != .default) cell.style.bg = pardes.Term.spanColor(colors, st.bg, true);
} else {
if (st.fg != .default) cell.style.fg = if (st.fg == .index) ink.palColor(st.fg.index) else st.fg;
if (st.bg != .default) cell.style.bg = if (st.bg == .index) ink.palColor(st.bg.index) else st.bg;
}
cell.style.bold = cell.style.bold or st.bold;
cell.style.dim = st.dim;
cell.style.italic = st.italic;
cell.style.blink = st.blink;
cell.style.reverse = st.reverse;
cell.style.invisible = st.invisible;
cell.style.strikethrough = st.strikethrough;
if (st.ul != .off) cell.style.ul = st.ul;
}
}
screen_c += cells;
c = grapheme_end - hs;
}
}
}
pub fn paintWordSelection(
p: *Pardes,
s: *Surface,
pane: *Pane,
r: pardes.Rect,
row: i32,
word_lo: i32,
word_hi: i32,
bg: [3]u8,
fg: ?[3]u8,
) void {
const tx = r.x + config.GUTTER;
const tw = r.w - config.GUTTER;
const prefix_width = gutterWidth(pane);
const body_y = p.bodyTop(pane, r);
var vr: i32 = 0;
while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) {
const here = pane.wrapAt(p.settings.tab, vr);
if (here.line != row) continue;
var hi = word_hi;
const next = pane.wrapAt(p.settings.tab, vr + 1);
if (next.line == row) hi = @min(hi, next.at);
const lo = @max(word_lo, here.at);
if (hi <= lo) continue;
const c0 = @as(i32, prefix_width) + here.pad + displayOffset(p.settings.tab, pane, row, here.at, lo);
const c1 = @as(i32, prefix_width) + here.pad + displayEndOffset(p.settings.tab, pane, row, here.at, hi - 1);
const col = @max(@as(i32, prefix_width), c0);
const end = @min(c1 + 1, @as(i32, tw));
if (col < end) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr)), @intCast(end - col), bg, fg);
}
}
test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" {
try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth(config.tab_width, "\xeee\xcc\x81"));
try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth(config.tab_width, "\xee\xffe"));
try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth(config.tab_width, "\u{4e16}\x80"));
// The whole path the 9P fuzzer took: a body holding it, fitted to a width.
const text = "\xeee\xcc\x81";
try std.testing.expectEqual(@as(usize, 4), fitEnd(config.tab_width, text, 0, 10));
}
test "indexed source rows match uncached scans across content changes" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("");
const file = &pane.file.?;
for ([_][]const u8{ "", "one", "one\n", "a\r\nλ界\nlast", "\n\n", "\tλ e\u{301}\n\r\n" }) |content| {
setContent(p, file, try p.gpa.dupe(u8, content));
// An edit carries a built index forward; it must equal a fresh one.
if (file.line_starts.len > 0) {
const carried = file.line_starts;
const room = indexRoom(file);
defer p.gpa.free(room);
file.line_starts = &.{};
try std.testing.expectEqualSlices(usize, try lineIndex(p.gpa, file), carried);
p.gpa.free(file.line_starts);
file.line_starts = &.{};
}
const rows = lineCount(content) + 2;
for ([_]bool{ false, true }) |indexed| {
if (indexed) _ = try lineIndex(p.gpa, file);
try std.testing.expectEqualStrings("", sourceLine(pane, -1));
for (0..rows) |row| try std.testing.expectEqualStrings(
modal.lineSlice(content, row),
sourceLine(pane, @intCast(row)),
);
if (!indexed) try std.testing.expectEqual(@as(usize, 0), file.line_starts.len);
}
}
}
test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" {
const ref = struct {
fn width(grapheme: []const u8) usize {
if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width;
return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode)));
}
}.width;
var one: [1]u8 = undefined;
var b: u8 = 0;
while (b < 0x80) : (b += 1) {
one[0] = b;
try std.testing.expectEqual(ref(one[0..1]), graphemeDisplayWidth(config.tab_width, one[0..1]));
}
for ([_][]const u8{
"e\u{301}", "a\u{903}", "1\u{fe0f}\u{20e3}", "\u{4e16}",
"\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff",
}) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(config.tab_width, g));
// Two invalid bytes are two cells, as surface.zig draws them, where
// vaxis's own count gives the pair one.
try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth(config.tab_width, "\xe4\xb8"));
}
test "the ASCII run in fitEnd survives an exhaustive byte sweep" {
const reference = struct {
fn fitEnd(text: []const u8, start: usize, width: usize) usize {
var end = start;
var used: usize = 0;
while (end < text.len) {
const next_end = modal.nextGrapheme(text, end);
const next_used = used +| graphemeDisplayWidth(config.tab_width, text[end..next_end]);
if (next_used > width) return if (end == start) next_end else end;
used = next_used;
end = next_end;
}
return end;
}
}.fitEnd;
const neighbours = [_][]const u8{
"", "z", "\u{301}", "\u{200d}\u{1f680}",
"\u{903}", "\u{fe0f}", "\u{4e16}", "\u{1f642}",
"\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", "\xe4\x28\xb8",
};
var buf: [16]u8 = undefined;
// The same pair again behind an ASCII prefix, so a break can land exactly at the run boundary
// as well as before it and inside the multi-byte cluster that follows it.
var prefixed: [18]u8 = undefined;
prefixed[0] = 'a';
prefixed[1] = 'b';
var b: u8 = 0;
while (b < 0x80) : (b += 1) {
buf[0] = b;
for (neighbours) |tail| {
@memcpy(buf[1..][0..tail.len], tail);
const pair = buf[0 .. 1 + tail.len];
@memcpy(prefixed[2..][0..pair.len], pair);
for ([_][]const u8{ pair, prefixed[0 .. 2 + pair.len] }) |text| {
var width: usize = 0;
while (width <= text.len + 3) : (width += 1) {
var start: usize = 0;
while (start <= text.len) : (start += 1) {
std.testing.expectEqual(
reference(text, start, width),
fitEnd(config.tab_width, text, start, width),
) catch |e| {
std.debug.print("fitEnd({any}, {d}, {d})\n", .{ text, start, width });
return e;
};
}
}
}
}
}
}
test "the ASCII run in fitEnd cuts where the grapheme walk would" {
const run = struct {
fn of(comptime c: u8, comptime n: usize) [n]u8 {
return @splat(c);
}
}.of;
const reference = struct {
fn fitEnd(text: []const u8, start: usize, width: usize) usize {
var end = start;
var used: usize = 0;
while (end < text.len) {
const next_end = modal.nextGrapheme(text, end);
const next_used = used +| graphemeDisplayWidth(config.tab_width, text[end..next_end]);
if (next_used > width) return if (end == start) next_end else end;
used = next_used;
end = next_end;
}
return end;
}
}.fitEnd;
const cases = [_][]const u8{
"",
"hello world",
// the fast path must hand over at the first non-ASCII byte, mid-run
"abc\u{00e9}def",
// a wide glyph is two columns, so a width boundary can land inside it
"ab\u{4e16}\u{754c}cd",
// a cluster the fast path must not split
"a\u{0301}bc",
// tabs and controls are excluded from the fast path by the range test
"ab\tcd",
"ab\rcd",
// an ASCII byte followed by a continuation byte is NOT its own cluster
"e\u{0301}x",
"\u{1f1e6}\u{1f1e7}ok",
// runs longer than a vector (the vector loop), each ending at a
// non-ASCII byte, a combining mark, a tab, or the text's end
&(run('x', 40) ++ "\u{00e9}".* ++ run('y', 40)),
&(run('a', 32) ++ "\u{0301}".* ++ run('b', 17)),
&(run('c', 47) ++ "\t".* ++ run('d', 20)),
&run('z', 100),
};
for (cases) |text| {
var width: usize = 0;
while (width <= text.len + 3) : (width += 1) {
var start: usize = 0;
while (start <= text.len) : (start += 1) {
try std.testing.expectEqual(
reference(text, start, width),
fitEnd(config.tab_width, text, start, width),
);
}
}
}
}
test "a line index shifted in place equals a rebuilt one, and the edit turned round gives the one before back" {
const gpa = std.testing.allocator;
var prng = std.Random.DefaultPrng.init(11);
const r = prng.random();
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
for (0..300) |_| try text.append(gpa, "ab\n"[r.uintLessThan(usize, 3)]);
var f: State = .{ .path = &.{}, .content = text.items, .history = undefined };
_ = try lineIndex(gpa, &f);
defer gpa.free(indexRoom(&f));
for (0..2000) |round| {
const at = r.uintAtMost(usize, text.items.len);
const del = r.uintAtMost(usize, @min(12, text.items.len - at));
var ins: [12]u8 = undefined;
const ins_len = r.uintAtMost(usize, 12);
for (ins[0..ins_len]) |*c| c.* = "ab\n\t"[r.uintLessThan(usize, 4)];
const before = try gpa.dupe(usize, f.line_starts);
defer gpa.free(before);
const cut = try gpa.dupe(u8, text.items[at..][0..del]);
defer gpa.free(cut);
f.content = text.items;
shiftIndex(gpa, &f, at, del, ins[0..ins_len]);
try text.replaceRange(gpa, at, del, ins[0..ins_len]);
var fresh: State = .{ .path = &.{}, .content = text.items, .history = undefined };
const want = try lineIndex(gpa, &fresh);
defer gpa.free(want);
try std.testing.expectEqualSlices(usize, want, f.line_starts);
// The kept widest is never less than the text's, made anew exact.
var widest: usize = 0;
var lines = std.mem.splitScalar(u8, text.items, '\n');
while (lines.next()) |line| widest = @max(widest, line.len);
try std.testing.expectEqual(Widest{ .bytes = widest, .tabbed = std.mem.indexOfScalar(u8, text.items, '\t') != null }, fresh.widest);
try std.testing.expect(f.widest.bytes >= widest and (f.widest.tabbed or !fresh.widest.tabbed));
// Every tenth turned round in a copy, as a rollback takes it back.
if (round % 10 == 0) {
const room = try gpa.alloc(usize, indexRoom(&f).len);
defer gpa.free(room);
@memcpy(room[0..f.line_starts.len], f.line_starts);
_ = shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut);
try std.testing.expectEqualSlices(usize, before, room[0..before.len]);
}
}
}
test "indexed text rows preserve fragment and allocation failure semantics" {
var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{});
const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("first\n\tλ界\n\nlast\n");
const text = pane.file.?.content;
allocator.fail_index = allocator.alloc_index;
for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(&pane.body, text, row));
try std.testing.expectEqual(@as(usize, 0), pane.file.?.line_starts.len);
allocator.fail_index = std.math.maxInt(usize);
_ = try lineIndex(p.gpa, &pane.file.?);
allocator.fail_index = allocator.alloc_index;
const allocations = allocator.allocations;
for ([_][]const u8{ text, text[2..], text[0..8], "other\nrows\n\n", "" }) |fragment| {
for (0..lineCount(fragment) + 2) |row| try std.testing.expectEqualStrings(
modal.lineSlice(fragment, row),
textLine(&pane.body, fragment, row),
);
}
try std.testing.expectEqual(allocations, allocator.allocations);
}
test "spanOf by blocks finds the byte loop's ends" {
var prng: std.Random.DefaultPrng = .init(5);
const random = prng.random();
var a: [160]u8 = undefined;
var b: [160]u8 = undefined;
for (0..4000) |_| {
const la = random.uintLessThan(usize, a.len);
const lb = random.uintLessThan(usize, b.len);
for (a[0..la]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)];
const keep = @min(la, lb);
@memcpy(b[0..keep], a[0..keep]);
for (b[keep..lb]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)];
if (lb > 0 and random.boolean()) b[random.uintLessThan(usize, lb)] ^= 1;
const old = a[0..la];
const new = b[0..lb];
const n = @min(old.len, new.len);
const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n;
var tail: usize = 0;
while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1;
try std.testing.expectEqual(Span{ .head = head, .tail = tail }, spanOf(old, new));
}
}
test "a +Pager pane holding a diff is drawn and looked at as one; holding other text, as text" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("");
const f = &pane.file.?;
p.gpa.free(f.path);
f.path = try p.gpa.dupe(u8, "/tmp/+Pager");
f.pager = true;
setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n"));
try std.testing.expect(pane.colorAlgo() == .diff);
try std.testing.expect(pardes.look.diffLines(p, pane) != null);
setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\n a plain log\n"));
try std.testing.expect(pane.colorAlgo() != .diff);
}
test "a pager's text is a diff when it holds a diff header or a unified hunk" {
try std.testing.expect(looksLikeDiff("commit abc\nAuthor: x\n\n msg\n\ndiff --git a/f b/f\n"));
try std.testing.expect(looksLikeDiff("--- a/f\n+++ b/f\n@@ -1 +1 @@\n-a\n+b\n"));
try std.testing.expect(!looksLikeDiff("commit abc\nAuthor: x\n\n plain log\n"));
}
test "a long line is painted only around the caret" {
if (comptime !syntax.full_grammars) return error.SkipZigTest; // JSON's
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const line = try std.testing.allocator.alloc(u8, 600 << 10);
defer std.testing.allocator.free(line);
for (line, 0..) |*c, i| c.* = if (i % 2 == 0) '1' else ',';
const pane = try p.setTestFile(line);
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/tmp/long.json");
pane.body.cur_col = 300 << 10;
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
_ = try p.render(arena.allocator());
const f = &pane.file.?;
try std.testing.expect(f.highlights.len == long_paint);
try std.testing.expect(f.highlight_start <= 300 << 10 and f.highlight_start + f.highlights.len >= 300 << 10);
}
test "a caret deep in a long line scrolls the view sideways to it, measured from the view's edge" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.settings.wrap = false;
const line = try std.testing.allocator.alloc(u8, 500 << 10);
defer std.testing.allocator.free(line);
@memset(line, 'a');
const pane = try p.setTestFile(line);
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
_ = try p.render(arena.allocator());
// Right, far: the caret ends a margin in from the right edge.
pane.body.cur_col = 400_000;
pane.ensureCursorVisible(config.tab_width);
const w: i32 = @as(i32, pane.cols) - @as(i32, gutterWidth(pane));
const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2));
try std.testing.expectEqual(@as(i32, 400_000 - (w - 1 - hmargin)), pane.hscroll);
// Back left of the view: a margin in from the left edge.
pane.body.cur_col = 100_000;
pane.ensureCursorVisible(config.tab_width);
try std.testing.expectEqual(@as(i32, 100_000 - hmargin), pane.hscroll);
// At the start: none.
pane.body.cur_col = 1;
pane.ensureCursorVisible(config.tab_width);
try std.testing.expectEqual(@as(i32, 0), pane.hscroll);
}
test "a caret left of a view scrolled sideways is not drawn in the gutter" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
p.settings.wrap = false;
const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n");
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
try std.testing.expect((try p.render(arena.allocator())).cursor != null);
// One wheel notch (4 columns) of the 7 the gutter is: the caret, at
// column 0, was drawn 3 columns into the gutter.
pane.hscroll = 4;
try std.testing.expect((try p.render(arena.allocator())).cursor == null);
}
test "undo and redo walk back and forth through every step of random edits, joined entries and all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const pane = try p.setTestFile("seed text\nof two lines\n");
const f = &pane.file.?;
const j = &f.history.journal;
var prng = std.Random.DefaultPrng.init(17);
const r = prng.random();
// The text at each step's edge, the last the text now.
var texts: std.ArrayList([]u8) = .empty;
defer {
for (texts.items) |t| gpa.free(t);
texts.deinit(gpa);
}
var at: usize = 0;
for (0..80) |_| {
const was = j.done;
try texts.append(gpa, try gpa.dupe(u8, f.content));
try pushUndo(p, pane);
// A step that changed nothing goes on, its edge where it was.
if (j.done == was) gpa.free(texts.pop().?);
// Up to six edits: most where the last ended, as typing goes on.
for (0..1 + r.uintLessThan(usize, 6)) |_| {
const len = f.content.len;
at = if (r.uintLessThan(u8, 4) == 0) r.uintAtMost(usize, len) else @min(at, len);
const del = r.uintAtMost(usize, @min(3, len - at));
var ins: [3]u8 = undefined;
const n = r.uintAtMost(usize, 3);
for (ins[0..n]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)];
try std.testing.expect(replace(p, f, at, del, ins[0..n]));
at += n;
}
}
try texts.append(gpa, try gpa.dupe(u8, f.content));
try std.testing.expectEqual(texts.items.len - 1, j.done);
var k = texts.items.len - 1;
while (k > 0) {
k -= 1;
try undoStep(p, pane, true);
try std.testing.expectEqualStrings(texts.items[k], f.content);
}
for (texts.items[1..]) |t| {
try undoStep(p, pane, false);
try std.testing.expectEqualStrings(t, f.content);
}
}
test "a text replaced whole keeps its old buffer for its undo, swapped back and forth, two at most" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const pane = try p.setTestFile("");
const f = &pane.file.?;
const j = &f.history.journal;
var texts: [5][]u8 = undefined;
for (&texts, 0..) |*t, i| {
t.* = try gpa.alloc(u8, swap_min + 1000 * i);
@memset(t.*, 'a' + @as(u8, @intCast(i)));
}
defer for (texts) |t| gpa.free(t);
setContent(p, f, try gpa.dupe(u8, texts[0]));
const first = f.content.ptr;
try pushUndo(p, pane);
setContent(p, f, try gpa.dupe(u8, texts[1]));
// The old buffer itself, kept: no byte of it copied, none counted.
const e = j.entries.items[j.entries.items.len - 1];
try std.testing.expect(e.swap and e.removed.ptr == first);
try std.testing.expectEqual(@as(usize, @sizeOf(Text.Entry)), j.bytes);
const second = f.content.ptr;
try undoStep(p, pane, true);
try std.testing.expect(f.content.ptr == first);
try std.testing.expectEqualStrings(texts[0], f.content);
try undoStep(p, pane, false);
try std.testing.expect(f.content.ptr == second);
try std.testing.expectEqualStrings(texts[1], f.content);
// A third and a fourth: two swaps kept, the steps before them gone, said.
for (texts[2..4]) |t| {
try pushUndo(p, pane);
setContent(p, f, try gpa.dupe(u8, t));
}
try std.testing.expectEqual(@as(usize, 2), j.done);
try std.testing.expect(std.mem.indexOf(u8, p.messages.saidBy(pane), "undo keeps the last two texts replaced whole") != null);
try undoStep(p, pane, true);
try undoStep(p, pane, true);
try std.testing.expectEqualStrings(texts[1], f.content);
try undoStep(p, pane, true);
try std.testing.expectEqualStrings(texts[1], f.content);
// A body emptied and written again on one open (a shell's >): its undo
// swaps the old text back and folds the step into one swap the other way.
try pushUndo(p, pane);
try std.testing.expect(replace(p, f, 0, f.content.len, ""));
try std.testing.expect(replace(p, f, 0, 0, "fresh\n"));
try undoStep(p, pane, true);
try std.testing.expectEqualStrings(texts[1], f.content);
try std.testing.expectEqual(@as(usize, 1), j.steps.items[j.done].n);
try undoStep(p, pane, false);
try std.testing.expectEqualStrings("fresh\n", f.content);
try undoStep(p, pane, true);
try std.testing.expectEqualStrings(texts[1], f.content);
}
test "undo keeps its steps within a byte bound, the newest always" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const step = limits.undo_bytes / 4 + 1;
// Each edit takes out the middle, under half the text: a copy each, not
// a swap of the whole.
const base = try gpa.alloc(u8, 2 * step + 1);
defer gpa.free(base);
@memset(base, 'z');
const pane = try p.setTestFile(base);
const f = &pane.file.?;
const text = try gpa.alloc(u8, step);
defer gpa.free(text);
for (0..8) |i| {
@memset(text, 'a' + @as(u8, @intCast(i)));
try pushUndo(p, pane);
try std.testing.expect(replace(p, f, step / 2, step, text));
}
try pushUndo(p, pane);
const j = &f.history.journal;
try std.testing.expect(j.done > 0 and j.done < 8);
try std.testing.expect(j.bytes <= limits.undo_bytes + step + @sizeOf(Text.Entry));
var sum: usize = 0;
for (j.entries.items) |e| {
try std.testing.expect(!e.swap);
sum += Text.Journal.held(e);
}
try std.testing.expectEqual(sum, j.bytes);
try undoStep(p, pane, true);
try std.testing.expectEqual(text[0], f.content[step / 2]);
// Back as far as the bound kept: each step's middle whole again.
while (j.done > 0) {
try undoStep(p, pane, true);
try std.testing.expect(std.mem.allEqual(u8, f.content[step / 2 ..][0..step], f.content[step / 2]));
}
}
test "context cache frees each allocation with its original allocator" {
var first: std.heap.DebugAllocator(.{}) = .init;
defer std.testing.expect(first.deinit() == .ok) catch @panic("first allocator leaked");
var second: std.heap.DebugAllocator(.{}) = .init;
defer std.testing.expect(second.deinit() == .ok) catch @panic("second allocator leaked");
var cache: ContextCache = .{};
defer cache.deinit();
cache.replace(first.allocator(), .{ .declarations = try first.allocator().alloc(syntax.ContextDeclaration, 1), .symbols = try first.allocator().alloc(syntax.Symbol, 1) }, 1);
cache.replace(second.allocator(), .{ .declarations = try second.allocator().alloc(syntax.ContextDeclaration, 2), .symbols = try second.allocator().alloc(syntax.Symbol, 2) }, 2);
try std.testing.expectEqual(@as(?u32, 2), cache.revision);
cache.deinit();
try std.testing.expect(cache.allocator == null);
try std.testing.expectEqual(@as(usize, 0), cache.declarations.len);
try std.testing.expectEqual(@as(usize, 0), cache.symbols.len);
}
/// The inks of row `row`'s first `n` text cells of pane `id` as `s` draws them.
fn rowInks(s: *pardes.Surface, pane: *const Pane, id: usize, row: u16, out: []pardes.Color) void {
const body = s.region(.body, id).?.rect;
const y: usize = body.y + row;
for (out, 0..) |*ink, i| {
const cell = s.cells[y * s.cols + body.x + gutterWidth(pane) + i];
ink.* = cell.style.fg;
}
}
test "Syntax takes a text's ink off in this view and puts it back, and another view keeps its own" {
if (!syntax.supportsPath("/test.zig")) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
defer p.deinit();
const pane = try p.setTestFile("pub const x = 1;\n");
gpa.free(pane.file.?.path);
pane.file.?.path = try gpa.dupe(u8, "/test.zig");
pane.file.?.syntax_dirty = true;
const id = p.view().active;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const plain: pardes.Color = if (p.theme().fg) |c| .{ .rgb = c } else .default;
var inks: [16]pardes.Color = undefined;
const Frame = struct {
fn take(q: *Pardes, a: *std.heap.ArenaAllocator, shown: *const Pane, at: usize, out: []pardes.Color) !void {
q.sync();
_ = a.reset(.retain_capacity);
rowInks(try q.render(a.allocator()), shown, at, 0, out);
}
fn colored(out: []const pardes.Color, fg: pardes.Color) bool {
for (out) |c| if (!std.meta.eql(c, fg)) return true;
return false;
}
};
try Frame.take(p, &arena, pane, id, &inks);
try std.testing.expect(Frame.colored(&inks, plain));
const other = p.openView().?;
p.update(.{ .command = "Syntax" });
try std.testing.expect(!pane.layers.ink);
try Frame.take(p, &arena, pane, id, &inks);
try std.testing.expect(!Frame.colored(&inks, plain));
// The other view's text keeps its ink; this one's stays off.
p.toView(other);
try Frame.take(p, &arena, pane, id, &inks);
try std.testing.expect(Frame.colored(&inks, plain));
p.toView(.at(0));
try std.testing.expect(!pane.layers.ink);
p.update(.{ .command = "Syntax" });
try Frame.take(p, &arena, pane, id, &inks);
try std.testing.expect(Frame.colored(&inks, plain));
}
test "Syntax off in a patch's pane takes the language's ink and leaves the patch: every ground as it was" {
if (!syntax.supportsPath("/x.zig")) return error.SkipZigTest;
const gpa = std.testing.allocator;
// A patch's hunks take their language's ink once the parsers run.
syntax.start(gpa);
defer syntax.stop();
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 14 });
defer p.deinit();
const pane = try p.setTestFile("diff --git a/x.zig b/x.zig\n--- a/x.zig\n+++ b/x.zig\n@@ -1,2 +1,2 @@\n const a = 1;\n-const b = 2;\n+pub const b = 3;\n");
gpa.free(pane.file.?.path);
pane.file.?.path = try gpa.dupe(u8, "/change.diff");
pane.file.?.syntax_dirty = true;
try std.testing.expect(pane.colorAlgo() == .diff);
const id = p.view().active;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var on: [7][2][24]pardes.Color = undefined;
for (0..2) |pass| {
if (pass == 1) p.update(.{ .command = "Syntax" });
p.sync();
_ = arena.reset(.retain_capacity);
const s = try p.render(arena.allocator());
const body = s.region(.body, id).?.rect;
var differ = false;
for (0..7) |row| for (0..24) |col| {
const cell = s.cells[(body.y + row) * s.cols + body.x + gutterWidth(pane) + col];
if (pass == 0) {
on[row][0][col] = cell.style.bg;
on[row][1][col] = cell.style.fg;
} else {
// The grounds stay; the ink of the code goes.
try std.testing.expect(std.meta.eql(on[row][0][col], cell.style.bg));
differ = differ or !std.meta.eql(on[row][1][col], cell.style.fg);
}
};
if (pass == 1) try std.testing.expect(differ);
}
}
test "a view scrolled by rows into a line of tabs, the tab width changed after a frame: its body drawn from the row the new width makes, as a core loaded from it draws it" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
try text.appendSlice(gpa, "head\n");
for (0..40) |i| try text.print(gpa, "\tw{d}", .{i});
try text.appendSlice(gpa, "\ntail\n");
const pane = try p.setTestFile(text.items);
try std.testing.expect(p.executeBuiltinLine(0, "Tab 8"));
// The top on line 1's fourth row (at 8 cells a tab), drawn.
const f = &pane.file.?;
f.scroll = 1;
f.scroll_row = 3;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
_ = try p.render(arena.allocator());
try std.testing.expect(p.executeBuiltinLine(0, "Tab 2"));
const drawn = try bodyText(p.settings.tab, arena.allocator(), pane, f);
const bytes = try pardes.dump.dumpBytes(p);
defer gpa.free(bytes);
const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, null);
defer loaded.deinit();
const lp = loaded.panes[0].?;
try std.testing.expectEqualStrings(try bodyText(loaded.settings.tab, arena.allocator(), lp, &lp.file.?), drawn);
}
|