1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
|
//! The pardes core: a text environment as a library, the way ghostty-vt is a
//! library. The platform shell owns the event loop and all IO; it feeds this
//! core events (input, pty bytes, resizes) and reads back two plain values:
//! a Surface — the canonical cell-grid interface, which the tty shell hands to
//! vaxis nearly verbatim and the SDL shells rasterize — and a queue of Effects,
//! the IO the core wants performed (spawn a shell, write a pty, open a link).
//! The core never does IO and never blocks; it is a state machine.
//!
//! Platform divergence inside the core is the `platform` comptime tag, used
//! the way the stdlib uses os.tag. Click-on-text semantics live in look.zig.
//!
//! src/ layout: the core lies flat at src/, and every SUBDIRECTORY is one
//! backend (tty/ gui/ lsp/) — so a file being in no directory at all is what
//! says it is core, and nothing needs a header to claim it.
//!
//! Not one key, button or piece of Look syntax is spelled in this file: every
//! one of them is a named binding in config.zig, and `hit`/`isPrefix` below are
//! the only two matchers. That is so retargeting anything is an edit in one
//! file, and so a later builtin can enumerate the bindings the way Help already
//! enumerates the leader.
const std = @import("std");
pub const animation = @import("animation.zig");
const ghostty_vt = @import("ghostty-vt");
const uucode = @import("uucode");
const mvzr = @import("mvzr");
const modal = @import("modal.zig");
const normal_input = @import("normal_input.zig");
const look = @import("look.zig");
const syntax = @import("syntax.zig");
const tracy = @import("tracy.zig");
const term_pane = @import("term_pane.zig");
const file_pane = @import("file_pane.zig");
const output_pane = @import("output_pane.zig");
const builtins = @import("builtins.zig");
const selection_pipe = @import("selection_pipe.zig");
pub const config = @import("config.zig");
pub const pdf_enabled = @import("pardes_config").mupdf;
const pdf_impl = if (pdf_enabled) @import("mupdf") else struct {};
pub const image = @import("image.zig");
pub const dump = @import("dump.zig");
pub const lsp = @import("lsp/lsp.zig");
pub const Platform = enum { tty, gui, web };
pub const platform: Platform = @field(Platform, @tagName(@import("pardes_config").platform));
/// Native PDF quality is a shell property, but the core owns MuPDF and the
/// RGBA cache. Kitty favors wire bandwidth; SDL favors physical-pixel text
/// quality and asks the renderer to cover either fit axis without upscaling.
pub const PdfRasterPolicy = struct {
dpi: u16,
max_dimension: u16,
match_viewport: bool,
};
pub const kitty_pdf_raster_policy: PdfRasterPolicy = .{
.dpi = 96,
.max_dimension = 1200,
.match_viewport = false,
};
pub const sdl_pdf_raster_policy: PdfRasterPolicy = .{
.dpi = 192,
.max_dimension = 4096,
.match_viewport = true,
};
pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) {
.tty => kitty_pdf_raster_policy,
.gui => sdl_pdf_raster_policy,
.web => kitty_pdf_raster_policy,
};
test "SDL PDF raster policy is materially denser than Kitty" {
try std.testing.expect(sdl_pdf_raster_policy.dpi >= kitty_pdf_raster_policy.dpi * 2);
try std.testing.expect(sdl_pdf_raster_policy.max_dimension >
kitty_pdf_raster_policy.max_dimension * 3);
try std.testing.expect(!kitty_pdf_raster_policy.match_viewport);
try std.testing.expect(sdl_pdf_raster_policy.match_viewport);
}
// The capacities and the two heights that are STRUCTURE, not taste: the
// fixed-size pane/column arrays, and the fact that the topbar and a tag are
// one row each (nothing here works at any other value). The layout numbers
// that ARE taste — the gutter, the line-number prefix, scrolloff, the pane
// minimums — live in config.zig with everything else a user retargets.
pub const MAX_PANES = 16;
pub const PDF_PAGE_GAP_PX: u32 = 8;
pub const MAX_COLS = 6;
/// how far back the jump stack remembers. Vim keeps 100; this is a session of
/// at most sixteen panes, so the depth that matters is "more visits than you
/// can hold in your head" and the oldest entry falls off the bottom.
pub const MAX_JUMPS = 64;
pub const TOPBAR_H: u16 = 1;
pub const BOX_H: u16 = 1;
/// A place the keyboard has been: a pane AND a spot in it, which is the whole
/// upgrade over the stack of bare pane ids this replaces — Ctrl-o can now
/// rewind WITHIN a pane, and a Jumplist row can name a line.
///
/// It is SAFE against the pane it names dying: `serial` is the pane's own
/// identity, so an entry whose slot has since been handed to a different pane
/// reads as dead rather than silently retargeting itself at the newcomer, and
/// sync() drops it. What it does not do is outlive the pane — ponytail: a
/// location is a place in the SESSION, not on disk, so closing a file forgets
/// the entries pointing into it. To make Ctrl-o RE-OPEN a closed file, this
/// grows a path field and jumpBy looks it when the pane is gone.
pub const Loc = struct {
pane: u16,
serial: u32,
/// 1-based, both — this is the `path:LINE:COL` a look word spells, and
/// focusPaneLine takes exactly these. 0 = no spot, just the pane (see
/// trackJump: a shell whose cursor is still the program's).
line: u32,
col: u32,
};
test "MuPDF pane renders, navigates, searches, and round-trips its page" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
try std.testing.expect(hasPdf(pane));
try std.testing.expect(pane.pdf.?.page_count > 1);
try std.testing.expectEqual(PdfFitMode.width, pane.pdf.?.fit);
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
try std.testing.expectEqual(@as(u16, 8), p.cell_pixels.w);
try std.testing.expectEqual(@as(u16, 16), p.cell_pixels.h);
const initial_tag = try p.tagText(p.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(u8, initial_tag, "pdf 1/") != null);
try std.testing.expect(std.mem.indexOf(u8, initial_tag, " width ") != null);
try std.testing.expect(std.mem.indexOf(u8, initial_tag, " height ") == null);
try std.testing.expect(std.mem.indexOf(u8, initial_tag, "PdfFit") != null);
try std.testing.expect(std.mem.endsWith(u8, initial_tag, pane_tail));
p.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const first = try p.render(frame.allocator());
try std.testing.expectEqual(@as(usize, 1), first.nimages);
const first_place = first.images[0].?;
try std.testing.expect(first_place.rgba.len == first_place.iw * first_place.ih * 4);
try std.testing.expectEqual(image.NativeFit.width, first_place.native.fit);
const request = p.pdfRenderRequest(pane) orelse return error.MissingPdfRenderRequest;
try std.testing.expectEqual(pdf_raster_policy.dpi, request.dpi);
try std.testing.expectEqual(pdf_raster_policy.max_dimension, request.max_dimension);
try std.testing.expectEqual(request, pane.pdf.?.render_request);
try std.testing.expect(@max(first_place.iw, first_place.ih) <= request.max_dimension);
if (pdf_raster_policy.match_viewport) {
const viewport = p.pdfViewport(pane) orelse return error.MissingPdfViewport;
try std.testing.expectEqual(viewport.pixel_w, request.minimum_width);
try std.testing.expectEqual(viewport.pixel_h, request.minimum_height);
try std.testing.expect(first_place.iw >= viewport.pixel_w or
@max(first_place.iw, first_place.ih) == request.max_dimension);
try std.testing.expect(first_place.ih >= viewport.pixel_h or
@max(first_place.iw, first_place.ih) == request.max_dimension);
} else {
try std.testing.expectEqual(@as(u32, 0), request.minimum_width);
try std.testing.expectEqual(@as(u32, 0), request.minimum_height);
}
// SDL's raw dy path retains fractions in the placement itself; it does
// not leave native pixels fixed while only the underlying cells slide.
p.update(.{ .pdf_scroll = .{ .pane = 0, .delta_pixels = 0.25 } });
try std.testing.expectEqual(@as(f64, 0.25), pane.pdf.?.document_scroll_y);
_ = frame.reset(.retain_capacity);
const fractional = try p.render(frame.allocator());
try std.testing.expectEqual(first_place.native.revision, fractional.images[0].?.native.revision);
try std.testing.expectEqual(@as(f32, -0.25), fractional.images[0].?.native.pixel_offset_y);
pane.pdf.?.document_scroll_y = 0;
// The default reading view moves one exact display-cell distance without
// replacing page pixels. Document placement, not texture identity, moves.
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
try std.testing.expectEqual(@as(f64, p.cell_pixels.h), pane.pdf.?.document_scroll_y);
try std.testing.expectEqual(first_place.native.revision, pane.pdf.?.render_revision);
_ = frame.reset(.retain_capacity);
const panned = try p.render(frame.allocator());
try std.testing.expectEqual(first_place.native.revision, panned.images[0].?.native.revision);
try std.testing.expect(panned.images[0].?.native.geometry.?.src.y > first_place.native.geometry.?.src.y);
const row_scroll = pane.pdf.?.document_scroll_y;
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = '3' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(f64, p.cell_pixels.h * 3), pane.pdf.?.document_scroll_y);
// Counts survive a shared multi-key prefix. An invalid continuation is
// consumed and clears both prefix and count before the following action.
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(f64, p.cell_pixels.h * 2), pane.pdf.?.document_scroll_y);
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = '4' } });
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = '?' } });
try std.testing.expectEqual(@as(u21, 0), pane.pending);
try std.testing.expectEqual(@as(u32, 0), pane.count);
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
const half_scroll = pane.pdf.?.document_scroll_y;
try std.testing.expect(half_scroll > row_scroll);
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
const counted_half = pane.pdf.?.document_scroll_y;
try std.testing.expectEqual(half_scroll * 2, counted_half);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'u', .ctrl = true } });
try std.testing.expectEqual(@as(f64, 0), pane.pdf.?.document_scroll_y);
pane.pdf.?.document_scroll_y = @as(f64, p.cell_pixels.h) * 4;
p.update(.{ .key = .{ .cp = '3' } });
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
try std.testing.expect(pane.pdf.?.document_scroll_y >= half_scroll);
pane.pdf.?.document_scroll_y = 0;
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
const key_viewport = p.pdfViewport(pane).?;
const max_key_scroll = @as(f64, @floatFromInt(pane.pdf.?.document_height -| key_viewport.pixel_h));
const counted_full = @min(@as(f64, @floatFromInt(key_viewport.pixel_h * 2)), max_key_scroll);
try std.testing.expectEqual(counted_full, pane.pdf.?.document_scroll_y);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
try std.testing.expectEqual(@max(@as(f64, 0), counted_full - @as(f64, @floatFromInt(key_viewport.pixel_h * 2))), pane.pdf.?.document_scroll_y);
try std.testing.expectEqual(first_place.native.revision, pane.pdf.?.render_revision);
// At a page boundary both page rasters coexist, the gap remains uncovered,
// and a row step crosses it without snapping either page to an edge.
const viewport = p.pdfViewport(pane).?;
pane.pdf.?.document_scroll_y = @floatFromInt(
pane.pdf.?.page_starts[1] -| viewport.pixel_h / 2,
);
_ = frame.reset(.retain_capacity);
const boundary = try p.render(frame.allocator());
try std.testing.expectEqual(@as(usize, 2), boundary.nimages);
try std.testing.expectEqual(@as(u32, 0), boundary.images[0].?.native.page);
try std.testing.expectEqual(@as(u32, 1), boundary.images[1].?.native.page);
const first_bottom = @as(f32, @floatFromInt(
boundary.images[0].?.native.geometry.?.dst.y +
boundary.images[0].?.native.geometry.?.dst.h,
)) + boundary.images[0].?.native.pixel_offset_y;
const second_top = @as(f32, @floatFromInt(
boundary.images[1].?.native.geometry.?.dst.y,
)) + boundary.images[1].?.native.pixel_offset_y;
const visible_gap = second_top - first_bottom;
try std.testing.expect(visible_gap >= @as(f32, PDF_PAGE_GAP_PX));
try std.testing.expect(visible_gap <= @as(f32, PDF_PAGE_GAP_PX + 1));
const before_boundary_scroll = pane.pdf.?.document_scroll_y;
const page0_revision = boundary.images[0].?.native.revision;
const page1_revision = boundary.images[1].?.native.revision;
// A scroll can activate the already-cached neighbor before the shell's
// next draw. Publish that page's aliases immediately so a queued click in
// the same input batch cannot use page zero's dimensions.
pane.pdf.?.document_scroll_y = @as(f64, @floatFromInt(pane.pdf.?.page_starts[1])) - 0.5;
Pardes.syncPdfRasterAliases(&pane.pdf.?, Pardes.pdfRasterForPage(&pane.pdf.?, 0).?);
try std.testing.expectEqual(page0_revision, pane.pdf.?.render_revision);
try std.testing.expect(p.scrollPdfDocument(pane, 1));
try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
try std.testing.expectEqual(page1_revision, pane.pdf.?.render_revision);
p.activatePdfPage(pane, 0, false);
pane.pdf.?.document_scroll_y = before_boundary_scroll;
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(before_boundary_scroll + p.cell_pixels.h, pane.pdf.?.document_scroll_y);
_ = frame.reset(.retain_capacity);
const second = try p.render(frame.allocator());
try std.testing.expectEqual(@as(usize, 2), second.nimages);
try std.testing.expectEqual(page0_revision, second.images[0].?.native.revision);
try std.testing.expectEqual(page1_revision, second.images[1].?.native.revision);
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(before_boundary_scroll, pane.pdf.?.document_scroll_y);
// Once page zero is wholly outside the viewport, both its owned RGBA and
// backend placement disappear; returning later must allocate a new raster.
p.setPdfPage(pane, 1);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
try std.testing.expect(Pardes.pdfRasterForPage(&pane.pdf.?, 0) == null);
p.setPdfPage(pane, 0);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
// PdfFit exists as a real builtin in this build. It resets placement but
// preserves the current page pixels; fit-height j/k remains continuous in
// the same document-pixel coordinate space.
const fit_builtin = std.meta.stringToEnum(Builtin, "PdfFit") orelse
return error.MissingPdfFitBuiltin;
const revision_before_toggle = pane.pdf.?.render_revision;
p.runBuiltin(fit_builtin, 0, "", null);
try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
try std.testing.expectEqual(revision_before_toggle, pane.pdf.?.render_revision);
const height_tag = try p.tagText(p.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(u8, height_tag, "pdf 1/") != null);
try std.testing.expect(std.mem.indexOf(u8, height_tag, " width ") == null);
try std.testing.expect(std.mem.indexOf(u8, height_tag, " height ") != null);
try std.testing.expect(std.mem.indexOf(u8, height_tag, "PdfFit") != null);
for (p.panes) |slot| {
const other = slot orelse continue;
if (hasPdf(other)) continue;
p.togglePdfFit(other); // pane-scoped and deliberately inert here
try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
break;
}
// A fit-height landscape page exposes horizontal overflow to a horizontal
// wheel without rerasterizing. Use synthetic dimensions only for the
// geometry check; no frame is drawn while they differ from the buffer.
const active_raster = Pardes.pdfRasterForPage(&pane.pdf.?, pane.pdf.?.page).?;
const saved_iw = active_raster.iw;
const saved_ih = active_raster.ih;
active_raster.iw = 2000;
active_raster.ih = 500;
Pardes.syncPdfRasterAliases(&pane.pdf.?, active_raster);
p.pdfHorizontalWheel(pane, 1);
try std.testing.expect(pane.pdf.?.pan_x > 0);
try std.testing.expectEqual(revision_before_toggle, pane.pdf.?.render_revision);
pane.pdf.?.pan_x = 0;
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'l' } });
try std.testing.expect(pane.pdf.?.pan_x > 0);
p.update(.{ .key = .{ .cp = '$' } });
try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'h' } });
try std.testing.expect(pane.pdf.?.pan_x < std.math.maxInt(u16));
p.update(.{ .key = .{ .cp = '0' } });
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'l' } });
try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'h' } });
try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
active_raster.iw = saved_iw;
active_raster.ih = saved_ih;
Pardes.syncPdfRasterAliases(&pane.pdf.?, active_raster);
pane.pdf.?.pan_x = 0;
const before_height_scroll = pane.pdf.?.document_scroll_y;
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expect(pane.pdf.?.document_scroll_y > before_height_scroll);
const revision_before_search = pane.pdf.?.render_revision;
p.runSearch(0, "Pardes", .text, .top);
try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
try std.testing.expectEqual(revision_before_search, pane.pdf.?.render_revision);
const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
const results = p.panes[results_id].?.file.?.content;
try std.testing.expect(std.mem.indexOf(u8, results, "design.pdf:") != null);
p.update(.{ .key = .{ .cp = 'n' } });
try std.testing.expect(pane.search_row != null);
try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
// Search state is owned and untruncated, and changing pages invalidates
// only page-local state while retaining the document query.
const long_query = "a query deliberately longer than any tag display budget: " ++
"012345678901234567890123456789012345678901234567890123456789" ++
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
p.setPdfSearchQuery(&pane.pdf.?, long_query);
try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
const next_page = if (pane.pdf.?.page == 0) @as(usize, 1) else 0;
p.setPdfPage(pane, next_page);
try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
// PDF dumps intentionally retain the existing image-compatible schema:
// page/path are restored, while pane-local tint starts from the fresh-PDF
// default rather than being serialized in the image record.
p.togglePdfTint(pane);
try std.testing.expectEqual(PdfTintMode.full, pane.pdf.?.tint);
try p.dumpState();
const restored = try Pardes.initFromDump(gpa, .{}, p.dump_out.?);
defer restored.deinit();
try std.testing.expect(hasPdf(restored.panes[0].?));
try std.testing.expectEqual(pane.pdf.?.page, restored.panes[0].?.pdf.?.page);
try std.testing.expectEqual(PdfTintMode.filtered, restored.panes[0].?.pdf.?.tint);
}
test "PDF normal adapter consumes unsupported actions and navigates page fallback" {
if (!pdf_enabled or platform == .web) return;
const p = try Pardes.init(std.testing.allocator, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
try std.testing.expect(pv.page_count > 3);
p.native_images = false;
// Every vertical vocabulary falls back to counted page changes when the
// shell cannot place native pixels.
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(usize, 2), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(@as(usize, 0), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
try std.testing.expectEqual(@as(usize, 2), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'u', .ctrl = true } });
try std.testing.expectEqual(@as(usize, 0), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
try std.testing.expectEqual(@as(usize, 2), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
try std.testing.expectEqual(@as(usize, 0), pv.page);
// Prefix actions and the counted text goto-line action map to pages.
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'e' } });
try std.testing.expectEqual(pv.page_count - 1, pv.page);
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'g' } });
try std.testing.expectEqual(@as(usize, 0), pv.page);
p.update(.{ .key = .{ .cp = '3' } });
p.update(.{ .key = .{ .cp = 'g' } });
p.update(.{ .key = .{ .cp = 'g' } });
try std.testing.expectEqual(@as(usize, 2), pv.page);
p.update(.{ .key = .{ .cp = '2' } });
p.update(.{ .key = .{ .cp = 'G' } });
try std.testing.expectEqual(@as(usize, 1), pv.page);
// Editing/selection actions are consumed no-ops: parser state clears,
// placeholder cells never acquire a range, and PDF state stays intact.
const page_before_noop = pv.page;
const revision_before_noop = pv.render_revision;
p.update(.{ .key = .{ .cp = '4' } });
p.update(.{ .key = .{ .cp = 'd' } });
p.update(.{ .key = .{ .cp = 'v' } });
p.update(.{ .key = .{ .cp = '|' } });
try std.testing.expectEqual(page_before_noop, pv.page);
try std.testing.expectEqual(revision_before_noop, pv.render_revision);
try std.testing.expectEqual(@as(u32, 0), pane.count);
try std.testing.expectEqual(@as(u21, 0), pane.pending);
try std.testing.expect(!pane.vsel.active and !pane.msel.active and pane.nsel == 0);
try std.testing.expect(!pane.pipe_edit and !pane.tag_edit);
// Cross-pane BODY-NORMAL actions keep their established shared paths.
p.update(.{ .key = .{ .cp = ':' } });
try std.testing.expect(pane.tag_edit);
try std.testing.expectEqual(Mode.normal, pane.mode);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(!pane.tag_edit);
p.update(.{ .key = .{ .cp = ' ' } });
try std.testing.expect(p.leader_on);
p.update(.{ .key = .{ .cp = '!' } });
try std.testing.expect(!p.leader_on);
p.update(.{ .key = .{ .cp = '/' } });
try std.testing.expect(pane.search_edit and pane.tag_edit);
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(!pane.search_edit and !pane.tag_edit);
}
test "PDF continuous strip renders every intersecting short page" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
try std.testing.expect(pv.page_count > 3);
p.native_images = true;
// A legal wide MediaBox can make more than three pages intersect one
// viewport. Seed tiny matching rasters so this tests transport/cache
// cardinality without spending the unit test rendering fake page sizes.
for (pv.page_sizes) |*size| size.* = .{ .width = 100_000, .height = 1 };
pv.layout_valid = false;
pv.scroll_to_page_pending = true;
const viewport = p.ensurePdfLayout(pane, pv).?;
const visible = Pardes.pdfVisiblePages(pv, viewport);
try std.testing.expectEqual(pv.page_count, visible.len);
const request = p.pdfRenderRequest(pane).?;
for (0..pv.page_count) |page| {
const rgba = try gpa.alloc(u8, @as(usize, viewport.pixel_w) * 4);
@memset(rgba, @intCast(page));
try pv.rasters.append(gpa, .{
.valid = true,
.page = page,
.rgba = rgba,
.iw = viewport.pixel_w,
.ih = 1,
.request = request,
.request_valid = true,
.tried = true,
.tint_key = p.pdfTintKey(pv),
.revision = @intCast(page + 1),
});
}
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
const surface = try p.render(frame.allocator());
try std.testing.expectEqual(pv.page_count, surface.nimages);
try std.testing.expectEqual(pv.page_count, pv.rasters.items.len);
for (surface.images[0..surface.nimages], 0..) |maybe, page| {
const place = maybe orelse return error.MissingShortPdfPage;
try std.testing.expectEqual(@as(u32, @intCast(page)), place.native.page);
try std.testing.expectEqual(@as(u32, 1), place.native.geometry.?.dst.h);
}
}
test "PdfTint cycles pane-local state and exposes it in the live PDF tag" {
if (!pdf_enabled or platform == .web) return;
const p = try Pardes.init(std.testing.allocator, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
const tint_builtin = std.meta.stringToEnum(Builtin, "PdfTint") orelse
return error.MissingPdfTintBuiltin;
try std.testing.expectEqual(PdfTintMode.filtered, pv.tint);
const initial_tag = try p.tagText(p.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(
u8,
initial_tag,
"width PdfFit filtered PdfTint",
) != null);
p.runBuiltin(tint_builtin, 0, "", null);
try std.testing.expectEqual(PdfTintMode.full, pv.tint);
const full_tag = try p.tagText(p.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(u8, full_tag, "full PdfTint") != null);
// Running the same pane-scoped word in a terminal cannot mutate the PDF
// next to it. A FILE boot is one pane now, so that terminal is asked for
// here rather than inherited from init.
_ = try p.newPane(1);
p.layoutAppendColumn(1);
p.sync(); // rects for the new column, exactly as the two-pane boot did
try std.testing.expect(!hasPdf(p.panes[1].?));
p.runBuiltin(tint_builtin, 1, "", null);
try std.testing.expectEqual(PdfTintMode.full, pv.tint);
p.runBuiltin(tint_builtin, 0, "", null);
try std.testing.expectEqual(PdfTintMode.disabled, pv.tint);
const disabled_tag = try p.tagText(p.scratch.allocator(), pane);
try std.testing.expect(std.mem.indexOf(u8, disabled_tag, "disabled PdfTint") != null);
p.runBuiltin(tint_builtin, 0, "", null);
try std.testing.expectEqual(PdfTintMode.filtered, pv.tint);
try std.testing.expectEqual(PdfFitMode.width, pv.fit);
// `dark` intentionally leaves page bg/fg null. PDF tint resolves those
// deterministically to its chrome colors rather than host defaults.
const dark_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "dark")) break i;
} else return error.MissingDarkTheme;
p.setThemeIndex(dark_index);
const colors = p.pdfTintColors();
try std.testing.expectEqual(p.theme().tag_bg, colors.background);
try std.testing.expectEqual(p.theme().tag_fg, colors.foreground);
}
test "PDF tint and tinted theme changes rebuild every visible raster only" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
p.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
_ = try p.render(frame.allocator());
const viewport = p.pdfViewport(pane).?;
pv.document_scroll_y = @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 2);
_ = frame.reset(.retain_capacity);
const default_surface = try p.render(frame.allocator());
try std.testing.expectEqual(PdfTintMode.filtered, pv.tint);
try std.testing.expectEqual(@as(usize, 2), default_surface.nimages);
try std.testing.expectEqual(@as(usize, 2), pv.rasters.items.len);
const Snapshot = struct {
page: u32,
revision: u32,
geometry: image.NativeGeometry,
pixel_offset_y: f32,
iw: usize,
ih: usize,
checksum: u64,
};
const Capture = struct {
fn get(surface: *const Surface) ![2]Snapshot {
if (surface.nimages != 2) return error.UnexpectedVisiblePdfCount;
var out: [2]Snapshot = undefined;
for (&out, 0..) |*snapshot, i| {
const place = surface.images[i] orelse return error.MissingVisiblePdf;
snapshot.* = .{
.page = place.native.page,
.revision = place.native.revision,
.geometry = place.native.geometry orelse return error.MissingPdfGeometry,
.pixel_offset_y = place.native.pixel_offset_y,
.iw = place.iw,
.ih = place.ih,
.checksum = std.hash.Wyhash.hash(0x5044_4654_494e_5421, place.rgba),
};
}
return out;
}
fn expectGeometry(before: [2]Snapshot, after: [2]Snapshot) !void {
for (before, after) |old, new| {
try std.testing.expectEqual(old.page, new.page);
try std.testing.expectEqual(old.geometry, new.geometry);
try std.testing.expectEqual(old.pixel_offset_y, new.pixel_offset_y);
try std.testing.expectEqual(old.iw, new.iw);
try std.testing.expectEqual(old.ih, new.ih);
}
}
};
const default_filtered = try Capture.get(default_surface);
for (pv.rasters.items) |raster|
try std.testing.expectEqual(PdfTintMode.filtered, raster.tint_key.?.mode);
const dark_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "dark")) break i;
} else return error.MissingDarkTheme;
p.setThemeIndex(dark_index);
for (pv.rasters.items) |raster| try std.testing.expect(!raster.tried);
_ = frame.reset(.retain_capacity);
const themed_surface = try p.render(frame.allocator());
const themed = try Capture.get(themed_surface);
try Capture.expectGeometry(default_filtered, themed);
for (default_filtered, themed) |old, new| {
try std.testing.expect(new.revision > old.revision);
try std.testing.expect(new.checksum != old.checksum);
}
// Chrome animation reads a separate palette. Its ticks must never disturb
// the target-theme tint key or ask MuPDF for the same pixels again.
try std.testing.expect(p.themeAnimationActive());
for (0..animation.transition_steps) |_| {
p.update(.tick);
_ = frame.reset(.retain_capacity);
const tick_surface = try p.render(frame.allocator());
const ticked = try Capture.get(tick_surface);
try Capture.expectGeometry(themed, ticked);
for (themed, ticked) |once, after_tick| {
try std.testing.expectEqual(once.revision, after_tick.revision);
try std.testing.expectEqual(once.checksum, after_tick.checksum);
}
}
try std.testing.expect(!p.themeAnimationActive());
p.togglePdfTint(pane);
try std.testing.expectEqual(PdfTintMode.full, pv.tint);
_ = frame.reset(.retain_capacity);
const full_surface = try p.render(frame.allocator());
const full = try Capture.get(full_surface);
try Capture.expectGeometry(themed, full);
for (themed, full) |old, new| {
try std.testing.expect(new.revision > old.revision);
}
for (pv.rasters.items) |raster|
try std.testing.expectEqual(PdfTintMode.full, raster.tint_key.?.mode);
p.togglePdfTint(pane);
try std.testing.expectEqual(PdfTintMode.disabled, pv.tint);
_ = frame.reset(.retain_capacity);
const disabled_surface = try p.render(frame.allocator());
const disabled = try Capture.get(disabled_surface);
try Capture.expectGeometry(full, disabled);
for (full, disabled) |old, source| {
try std.testing.expect(source.revision > old.revision);
try std.testing.expect(source.checksum != old.checksum);
}
const acme_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "acme")) break i;
} else return error.MissingAcmeTheme;
for (pv.rasters.items) |raster| try std.testing.expect(raster.tried);
p.setThemeIndex(acme_index);
// Disabled keys ignore theme colors, so neither explicit invalidation nor
// the per-raster key comparison asks MuPDF for replacement pixels.
for (pv.rasters.items) |raster| try std.testing.expect(raster.tried);
_ = frame.reset(.retain_capacity);
const unchanged_surface = try p.render(frame.allocator());
const unchanged = try Capture.get(unchanged_surface);
try Capture.expectGeometry(disabled, unchanged);
for (disabled, unchanged) |old, new| {
try std.testing.expectEqual(old.revision, new.revision);
try std.testing.expectEqual(old.checksum, new.checksum);
}
try std.testing.expectEqual(@as(usize, 2), pv.rasters.items.len);
}
test "PDF resize preserves page-relative document position" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
p.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
p.setPdfPage(pane, 1);
_ = try p.render(frame.allocator());
const fraction: f64 = 0.375;
pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
p.update(.{ .resize = .{
.cols = 100,
.rows = 24,
.cell_pixels = p.cell_pixels,
} });
try std.testing.expect(!pv.layout_valid);
try std.testing.expect(pv.layout_anchor_pending);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
const resized_fraction = (pv.document_scroll_y -
@as(f64, @floatFromInt(pv.page_starts[1]))) /
@as(f64, @floatFromInt(pv.page_heights[1]));
try std.testing.expectApproxEqAbs(fraction, resized_fraction, 0.000_001);
try std.testing.expectEqual(@as(usize, 1), pv.page);
const held = pv.document_scroll_y;
p.update(.{ .resize = .{
.cols = 100,
.rows = 24,
.cell_pixels = p.cell_pixels,
} });
try std.testing.expectEqual(held, pv.document_scroll_y);
try std.testing.expect(pv.layout_valid);
}
test "PDF pane geometry change preserves its page-relative position" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
// A FILE boot is one pane now and a lone column always fills the window,
// so the divider drag below needs a second column to take the width from.
_ = try p.newPane(1);
p.layoutAppendColumn(1);
p.sync(); // rects for the new column, exactly as the two-pane boot did
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
p.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
p.setPdfPage(pane, 1);
_ = try p.render(frame.allocator());
const fraction: f64 = 0.625;
pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
const old_width = pv.layout_viewport_w;
// A divider/split changes rects through computeGeom without emitting a
// shell resize. ensurePdfLayout must anchor against the old valid layout
// before rebuilding it for this wider pane.
p.col_weight[0] = 3;
p.computeGeom();
try std.testing.expect(p.pdfViewport(pane).?.pixel_w != old_width);
try std.testing.expect(pv.layout_valid);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
const changed_fraction = (pv.document_scroll_y -
@as(f64, @floatFromInt(pv.page_starts[1]))) /
@as(f64, @floatFromInt(pv.page_heights[1]));
try std.testing.expectApproxEqAbs(fraction, changed_fraction, 0.000_001);
try std.testing.expectEqual(@as(usize, 1), pv.page);
// An explicit pending reveal wins over an implicit layout anchor.
pv.page = 2;
pv.scroll_to_page_pending = true;
p.col_weight[0] = 1;
p.computeGeom();
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
try std.testing.expectEqual(
@as(f64, @floatFromInt(pv.page_starts[2])),
pv.document_scroll_y,
);
}
test "PDF n/N addresses and reveals distinct MuPDF hits on one page" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 120,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
p.native_images = true;
var page_hits = try pv.document.search(gpa, 0, "Pardes");
defer page_hits.deinit(gpa);
try std.testing.expect(page_hits.hit_count >= 3);
p.runSearch(0, "Pardes", .text, .top);
const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
const rows = p.panes[results_id].?.file.?.content;
try std.testing.expect(std.mem.indexOf(u8, rows, "design.pdf:1:1 Pardes\n") != null);
try std.testing.expect(std.mem.indexOf(u8, rows, "design.pdf:1:2 Pardes\n") != null);
try std.testing.expect(std.mem.indexOf(u8, rows, "design.pdf:1:3 Pardes\n") != null);
// Exaggerate the cell aspect only to make the three fixture hits occupy
// distinct fit-width crops. The search/reveal math must use the same
// reported metrics as placement, whatever a backend reports.
p.update(.{ .resize = .{
.cols = p.screen_w,
.rows = p.screen_h,
.cell_pixels = .{ .w = 16, .h = 4 },
} });
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
try std.testing.expect(p.searchStep(0, 1));
try std.testing.expectEqual(@as(usize, 0), pv.search_hit);
const first = try p.render(frame.allocator());
const revision = first.images[0].?.native.revision;
const first_scroll = pv.document_scroll_y;
const first_results = pv.search_results orelse return error.MissingPdfPageSearch;
const first_quad = for (first_results.quads) |item| {
if (item.hit == 0) break item.quad;
} else return error.MissingFirstPdfHit;
const first_y = Pardes.normalizedPdfPixel(
(first_quad.ul.y + first_quad.ur.y + first_quad.ll.y + first_quad.lr.y) / 4,
pv.ih,
);
const first_geometry = p.pdfGeometry(pane) orelse return error.MissingPdfGeometry;
try std.testing.expect(first_y >= first_geometry.src.y and
first_y < first_geometry.src.y + first_geometry.src.h);
try std.testing.expect(p.searchStep(0, 1));
try std.testing.expectEqual(@as(usize, 1), pv.search_hit);
_ = frame.reset(.retain_capacity);
const second = try p.render(frame.allocator());
try std.testing.expectEqual(revision, second.images[0].?.native.revision);
try std.testing.expect(p.searchStep(0, 1));
try std.testing.expectEqual(@as(usize, 2), pv.search_hit);
_ = frame.reset(.retain_capacity);
const third = try p.render(frame.allocator());
try std.testing.expectEqual(revision, third.images[0].?.native.revision);
try std.testing.expect(pv.document_scroll_y != first_scroll);
const third_results = pv.search_results orelse return error.MissingPdfPageSearch;
const third_quad = for (third_results.quads) |item| {
if (item.hit == 2) break item.quad;
} else return error.MissingThirdPdfHit;
const third_y = Pardes.normalizedPdfPixel(
(third_quad.ul.y + third_quad.ur.y + third_quad.ll.y + third_quad.lr.y) / 4,
pv.ih,
);
const third_geometry = p.pdfGeometry(pane) orelse return error.MissingPdfGeometry;
try std.testing.expect(third_y >= third_geometry.src.y and
third_y < third_geometry.src.y + third_geometry.src.h);
}
test "PDF native mouse selection, Look, and highlights share page geometry" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
// A host without Kitty/native pixels keeps the projected-text contract:
// j/k can still change pages and a body drag remains a generic selection.
const fallback = try p.render(frame.allocator());
try std.testing.expectEqual(@as(usize, 0), fallback.nimages);
p.update(.{ .key = .{ .cp = 'j' } });
try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
p.update(.{ .key = .{ .cp = 'k' } });
try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
const fallback_rect = p.rects[0];
const fallback_col = fallback_rect.x + config.GUTTER + 1;
const fallback_row = fallback_rect.y + BOX_H + 1;
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = fallback_col, .row = fallback_row } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = fallback_col + 4, .row = fallback_row } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = fallback_col + 4, .row = fallback_row } });
try std.testing.expectEqual(.done, pane.sel[sel_slot].state);
try std.testing.expect(pane.pdf.?.selection == null);
pane.sel[sel_slot].state = .none;
p.native_images = true;
_ = frame.reset(.retain_capacity);
const plain = try p.render(frame.allocator());
const plain_revision = plain.images[0].?.native.revision;
var found = try pane.pdf.?.document.search(gpa, 0, "Pardes");
defer found.deinit(gpa);
const quad = found.quads[0].quad;
const nx = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4;
const ny = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4;
const pv = &pane.pdf.?;
const source_x: u32 = @intCast(@min(
pv.iw - 1,
@as(usize, @intFromFloat(nx * @as(f32, @floatFromInt(pv.iw)))),
));
const source_y: u32 = @intCast(@min(
pv.ih - 1,
@as(usize, @intFromFloat(ny * @as(f32, @floatFromInt(pv.ih)))),
));
// Bring the known word into the fit-width crop, then invert the shared
// source/destination geometry to the nearest body cell.
var geometry = p.pdfGeometry(pane).?;
if (source_y < geometry.src.y or source_y >= geometry.src.y + geometry.src.h) {
const overflow = @as(u32, @intCast(pv.ih)) - geometry.src.h;
const wanted = @min(overflow, source_y -| geometry.src.h / 2);
pv.pan_y = if (overflow == 0) 0 else @intCast(
(@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow,
);
geometry = p.pdfGeometry(pane).?;
}
const pixel_x = geometry.dst.x + @as(u32, @intCast(
@as(u64, source_x - geometry.src.x) * geometry.dst.w / geometry.src.w,
));
const pixel_y = geometry.dst.y + @as(u32, @intCast(
@as(u64, source_y - geometry.src.y) * geometry.dst.h / geometry.src.h,
));
const r = p.rects[0];
const base_col: i32 = @intCast(r.x + config.GUTTER + pixel_x / p.cell_pixels.w);
const base_row: i32 = @intCast(r.y + BOX_H + pixel_y / p.cell_pixels.h);
var selected_col: ?u16 = null;
var selected_row: u16 = 0;
const nearby = [_]i32{ 0, -1, 1, -2, 2 };
find_word: for (nearby) |dy| for (nearby) |dx| {
const col: u16 = @intCast(std.math.clamp(
base_col + dx,
@as(i32, r.x + config.GUTTER),
@as(i32, r.x + r.w - 1),
));
const row: u16 = @intCast(std.math.clamp(
base_row + dy,
@as(i32, r.y + BOX_H),
@as(i32, r.y + r.h - 1),
));
if (!p.beginPdfSelection(pane, col, row)) continue;
if (std.ascii.indexOfIgnoreCase(pv.selection_text, "Pardes") != null) {
selected_col = col;
selected_row = row;
break :find_word;
}
};
const word_col = selected_col orelse return error.PdfMouseMappingMissedWord;
try std.testing.expect(std.ascii.indexOfIgnoreCase(p.heldSelection(0).?, "Pardes") != null);
_ = frame.reset(.retain_capacity);
const selected_frame = try p.render(frame.allocator());
const selected_revision = selected_frame.images[0].?.native.revision;
try std.testing.expect(selected_revision != plain_revision);
// Repeating an identical drag endpoint is a no-op: Kitty/SDL keep the
// same texture generation instead of retransmitting identical pixels.
try std.testing.expect(p.beginPdfSelection(pane, word_col, selected_row));
try std.testing.expect(pv.render_tried);
_ = frame.reset(.retain_capacity);
const duplicate = try p.render(frame.allocator());
try std.testing.expectEqual(selected_revision, duplicate.images[0].?.native.revision);
// A native right-click resolves the same MuPDF-snapped word and feeds it
// to Look. Search highlights precede selection highlights so the live
// selection remains visually authoritative where they overlap.
p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = word_col, .row = selected_row } });
p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = word_col, .row = selected_row } });
try std.testing.expect(std.ascii.indexOfIgnoreCase(pv.search_query, "Pardes") != null);
p.resolvePdfSearch(pv);
const highlights = try p.pdfHighlights(pv);
try std.testing.expect(highlights.len > 1);
try std.testing.expectEqual(pdf_impl.HighlightKind.search, highlights[0].kind);
try std.testing.expectEqual(pdf_impl.HighlightKind.selection, highlights[highlights.len - 1].kind);
const revision_before_reveal = pv.render_revision;
const max_document_scroll = @as(f64, @floatFromInt(
pv.document_height -| p.pdfViewport(pane).?.pixel_h,
));
pv.document_scroll_y = max_document_scroll;
p.revealPdfSearch(pane, pv);
const revealed_scroll = pv.document_scroll_y;
try std.testing.expect(revealed_scroll != max_document_scroll);
try std.testing.expectEqual(revision_before_reveal, pv.render_revision);
pv.document_scroll_y = max_document_scroll;
p.revealPdfSearch(pane, pv); // one shot: subsequent manual pan stays put
try std.testing.expectEqual(max_document_scroll, pv.document_scroll_y);
pv.document_scroll_y = revealed_scroll;
_ = frame.reset(.retain_capacity);
const searched = try p.render(frame.allocator());
try std.testing.expect(searched.images[0].?.native.revision != selected_revision);
// Fit and viewport changes can crop a hit which was already revealed.
// Fit remains placement-only. SDL's physical-viewport quality request
// changes with a resize and therefore replaces pixels; Kitty's fixed,
// bandwidth-conscious request retains them.
const revision_before_geometry_change = searched.images[0].?.native.revision;
pv.search_reveal_pending = false;
p.togglePdfFit(pane);
try std.testing.expect(pv.search_reveal_pending);
pv.search_reveal_pending = false;
p.togglePdfFit(pane); // restore the reading-width geometry
try std.testing.expect(pv.search_reveal_pending);
pv.search_reveal_pending = false;
const original_cell_pixels = p.cell_pixels;
p.update(.{ .resize = .{
.cols = p.screen_w,
.rows = p.screen_h,
.cell_pixels = p.cell_pixels,
} });
try std.testing.expect(!pv.search_reveal_pending);
p.update(.{ .resize = .{
.cols = p.screen_w,
.rows = p.screen_h,
.cell_pixels = .{
.w = original_cell_pixels.w,
.h = original_cell_pixels.h + 1,
},
} });
try std.testing.expect(pv.search_reveal_pending);
_ = frame.reset(.retain_capacity);
const geometry_changed = try p.render(frame.allocator());
if (pdf_raster_policy.match_viewport)
try std.testing.expect(geometry_changed.images[0].?.native.revision !=
revision_before_geometry_change)
else
try std.testing.expectEqual(
revision_before_geometry_change,
geometry_changed.images[0].?.native.revision,
);
p.update(.{ .resize = .{
.cols = p.screen_w,
.rows = p.screen_h,
.cell_pixels = original_cell_pixels,
} });
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
// Unsupported text-selection actions are consumed by the PDF adapter:
// they neither invent a range over placeholder cells nor disturb the
// native MuPDF selection. The select-button's no-drag click still clears.
p.update(.{ .key = .{ .cp = 'v' } });
try std.testing.expect(pv.selection != null);
try std.testing.expect(!pane.vsel.active);
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = word_col, .row = selected_row } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = word_col, .row = selected_row } });
try std.testing.expect(pv.selection == null);
try std.testing.expect(p.beginPdfSelection(pane, word_col, selected_row));
// Native drag events update MuPDF quads and copied text immediately, but
// keep the already transmitted page generation stable until release.
_ = frame.reset(.retain_capacity);
const before_drag = try p.render(frame.allocator());
const before_drag_revision = before_drag.images[0].?.native.revision;
const drag_col = @min(r.x + r.w - 1, word_col +| 12);
const drag_row = @min(r.y + r.h - 1, selected_row +| 4);
p.update(.{ .mouse = .{
.button = config.select_button,
.kind = .press,
.col = word_col,
.row = selected_row,
} });
p.update(.{ .mouse = .{
.button = config.select_button,
.kind = .drag,
.col = @min(drag_col, word_col +| 4),
.row = @min(drag_row, selected_row +| 2),
} });
_ = frame.reset(.retain_capacity);
const during_first_drag = try p.render(frame.allocator());
try std.testing.expectEqual(
before_drag_revision,
during_first_drag.images[0].?.native.revision,
);
p.update(.{ .mouse = .{
.button = config.select_button,
.kind = .drag,
.col = drag_col,
.row = drag_row,
} });
try std.testing.expect(p.drag.select.pdf.selection_changed);
_ = frame.reset(.retain_capacity);
const during_second_drag = try p.render(frame.allocator());
try std.testing.expectEqual(
before_drag_revision,
during_second_drag.images[0].?.native.revision,
);
p.update(.{ .mouse = .{
.button = config.select_button,
.kind = .release,
.col = drag_col,
.row = drag_row,
} });
try std.testing.expect(!pv.render_tried);
_ = frame.reset(.retain_capacity);
const committed_drag = try p.render(frame.allocator());
try std.testing.expectEqual(
before_drag_revision + 1,
committed_drag.images[0].?.native.revision,
);
_ = frame.reset(.retain_capacity);
const stable_drag = try p.render(frame.allocator());
try std.testing.expectEqual(
committed_drag.images[0].?.native.revision,
stable_drag.images[0].?.native.revision,
);
const saved_query = try gpa.dupe(u8, pv.search_query);
defer gpa.free(saved_query);
p.setPdfPage(pane, 1);
try std.testing.expect(pv.selection == null);
try std.testing.expectEqual(@as(usize, 0), pv.selection_text.len);
try std.testing.expectEqualStrings(saved_query, pv.search_query);
}
test "PDF native Exec release may delete its own pane safely" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
const pv = &pane.pdf.?;
pv.selection_text = try gpa.dupe(u8, "Del");
pv.drag_anchor = .{ .x = 0.5, .y = 0.5 };
pv.drag_head = pv.drag_anchor;
p.pdfDragRelease(pane, .{
.id = 0,
.button = config.exec_button,
.pdf = .{ .native = true },
});
try std.testing.expect(p.panes[0] == null);
}
test "feature-off .pdf argv opens an ordinary file pane" {
if (comptime pdf_enabled or platform == .web) return;
const p = try Pardes.init(std.testing.allocator, .{
.file = "docs/design.pdf",
.cols = 80,
.rows = 24,
});
defer p.deinit();
const pane = p.panes[0].?;
try std.testing.expect(pane.file != null);
try std.testing.expect(pane.image == null);
try std.testing.expect(!hasPdf(pane));
}
const pane_tail = " " ++ config.pane_builtins_str;
const file_pane_tail = " " ++ config.file_pane_builtins_str;
// Dumps persist the whole rendered tag. These were the two canonical tails
// before New joined every pane; restoreTail recognizes exactly these spellings
// as defaults so an old session upgrades, without mistaking an edited tail for
// chrome it may replace.
const legacy_pane_tail = " Del";
const legacy_file_pane_tail = " Save Del";
// Builtins: executing the name (middle-click / Tab) runs it through the ONE
// dispatcher (runBuiltin, reached from execute), no matter where the name
// appears — and Look and Exec are two of them, so the click itself is a
// builtin. One STRUCT per builtin in builtins.zig — name, comment and
// body in one place — and this enum is folded out of THAT FILE'S declarations
// at comptime, so the enum FIELD NAME is still the user-visible word (the one
// in the topbar, the one sitting in a tag, the one Help prints, the one you
// execute) and `std.meta.stringToEnum` is still the lookup with no name table
// to keep in sync. It lands here rather than in builtins.zig because a
// container cannot hold a decl folded out of its own decl list, and here it
// sits with the other two comptime folds (builtin_rows, the topbar check).
const Builtin = builtins.Builtin();
test "PDF builtins and leader paths follow the MuPDF feature gate" {
const maybe_fit = std.meta.stringToEnum(Builtin, "PdfFit");
const maybe_tint = std.meta.stringToEnum(Builtin, "PdfTint");
const maybe_sections = std.meta.stringToEnum(Builtin, "PdfSections");
try std.testing.expectEqual(pdf_enabled, maybe_fit != null);
try std.testing.expectEqual(pdf_enabled, maybe_tint != null);
try std.testing.expectEqual(pdf_enabled, maybe_sections != null);
if (pdf_enabled) {
const fit_path = config.leader_path.get(maybe_fit.?) orelse
return error.MissingPdfFitLeaderPath;
const tint_path = config.leader_path.get(maybe_tint.?) orelse
return error.MissingPdfTintLeaderPath;
const sections_path = config.leader_path.get(maybe_sections.?) orelse
return error.MissingPdfSectionsLeaderPath;
try std.testing.expectEqualStrings("tz", fit_path);
try std.testing.expectEqualStrings("ti", tint_path);
try std.testing.expectEqualStrings("ts", sections_path);
const traits = output_pane.traits(.{ .cmd = maybe_sections.? });
try std.testing.expectEqualStrings(config.pdf_sections_buffer, traits.name);
try std.testing.expect(traits.steps);
try std.testing.expect(!traits.executes);
const help_row = for (builtin_rows) |row| {
if (row.cmd == maybe_sections.?) break row;
} else return error.MissingPdfSectionsHelpRow;
try std.testing.expectEqualStrings("ts", help_row.path.?);
try std.testing.expect(std.mem.indexOf(u8, help_row.line, "PdfSections") != null);
}
}
test "PDF section rows preserve DFS ordinals and sanitise hierarchy" {
if (!pdf_enabled) return;
const E = pdf_impl.OutlineEntry;
const entries = [_]E{
.{ .depth = 0, .title = null, .is_open = true, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 1, .title = " Child\n\tTitle\x01 Café \u{2028} Next ", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .internal = .{ .page = 2, .x = 12, .y = 34 } } },
.{ .depth = 0, .title = "", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .internal = .{ .page = 0, .x = null, .y = null } } },
.{ .depth = 0, .title = "External", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .external = "https://example.com/manual" } },
.{ .depth = 0, .title = "Dead branch", .is_open = false, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 0, .title = "Unsafe", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .external = "javascript:alert" } },
.{ .depth = 0, .title = "Linked branch", .is_open = true, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 1, .title = "Deep link", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .external = "https://example.com/deep" } },
};
const rows = try PdfSectionRows.render(std.testing.allocator, "/tmp/manual.pdf", &entries);
defer std.testing.allocator.free(rows);
try std.testing.expectEqualStrings(
"manual.pdf:3:1 [untitled]\n" ++
"manual.pdf:3:2 Child Title Café Next\n" ++
"manual.pdf:1:3 [empty title]\n" ++
"https://example.com/manual External\n" ++
"https://example.com/deep Linked branch\n" ++
"https://example.com/deep Deep link\n",
rows,
);
try std.testing.expect(PdfSectionRows.resolve(&entries, 4) == null);
try std.testing.expect(PdfSectionRows.resolve(&entries, 5) == null);
const resolved = try PdfSectionRows.resolveOrdinals(std.testing.allocator, &entries);
defer std.testing.allocator.free(resolved);
for (entries, 0..) |_, ordinal| {
const single = PdfSectionRows.resolve(&entries, ordinal);
if (resolved[ordinal] == std.math.maxInt(usize)) {
try std.testing.expect(single == null);
} else {
const bulk = PdfSectionRows.usableDestination(entries[resolved[ordinal]].destination) orelse
return error.MissingBulkPdfSectionDestination;
try std.testing.expect(single != null);
try std.testing.expect(std.meta.eql(single.?, bulk));
}
}
// Every allocation site in the ordinal table and output growth remains
// atomic: the testing allocator sees each induced failure cleaned up
// before the first index at which the whole render can succeed.
var rendered = false;
for (0..64) |fail_index| {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
.fail_index = fail_index,
});
const failure_gpa = failing.allocator();
const attempt = PdfSectionRows.render(failure_gpa, "/tmp/manual.pdf", &entries) catch |err| {
try std.testing.expectEqual(error.OutOfMemory, err);
continue;
};
failure_gpa.free(attempt);
rendered = true;
break;
}
try std.testing.expect(rendered);
}
test "bulk PDF section resolution matches single Look policy across DFS boundaries" {
if (!pdf_enabled) return;
const E = pdf_impl.OutlineEntry;
const entries = [_]E{
.{ .depth = 0, .title = "Resolved root", .is_open = true, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 1, .title = "Unsafe branch", .is_open = true, .flags = 0, .color = @splat(0), .destination = .{ .external = "javascript:unsafe" } },
.{ .depth = 2, .title = "Safe grandchild", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .internal = .{ .page = 1, .x = 4, .y = 8 } } },
.{ .depth = 1, .title = "Unresolved child", .is_open = false, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 1, .title = "Sibling", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .internal = .{ .page = 2, .x = null, .y = null } } },
.{ .depth = 0, .title = "Unresolved root", .is_open = false, .flags = 0, .color = @splat(0), .destination = .none },
.{ .depth = 0, .title = "Next root", .is_open = false, .flags = 0, .color = @splat(0), .destination = .{ .internal = .{ .page = 3, .x = null, .y = null } } },
};
const bulk = try PdfSectionRows.resolveOrdinals(std.testing.allocator, &entries);
defer std.testing.allocator.free(bulk);
const none = std.math.maxInt(usize);
try std.testing.expectEqualSlices(usize, &.{ 2, none, 2, none, 4, none, 6 }, bulk);
for (entries, 0..) |_, ordinal| {
const single = PdfSectionRows.resolve(&entries, ordinal);
if (bulk[ordinal] == none) {
try std.testing.expect(single == null);
} else {
const destination = PdfSectionRows.usableDestination(entries[bulk[ordinal]].destination) orelse
return error.MissingBoundaryPdfSectionDestination;
try std.testing.expect(single != null);
try std.testing.expect(std.meta.eql(single.?, destination));
}
}
}
test "PdfSections output, Look, and n/N share exact cached outline destinations" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const fixture = try pdf_impl.makeOutlineTestPdf(gpa);
defer gpa.free(fixture);
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
var path_buf: [256]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
defer p.deinit();
// A FILE boot is one pane now, so the launch shell this leans on twice has
// to be asked for: an empty slot 1 would satisfy the inertness check below
// for the wrong reason (runBuiltin drops a null pane before any builtin
// runs) AND would then be handed to the +PdfSections output, which is the
// one pane the look at the end must NOT come from.
_ = try p.newPane(1);
p.layoutAppendColumn(1);
p.sync(); // rects for the new column, exactly as the two-pane boot did
while (p.nextEffect()) |_| {}
const pdf_pane = p.panes[0].?;
const sections = std.meta.stringToEnum(Builtin, "PdfSections") orelse
return error.MissingPdfSectionsBuiltin;
// Pane-scoped: a shell invocation is inert; the PDF invocation opens one
// output immediately below it and leaves focus/step ownership on the PDF.
p.runBuiltin(sections, 1, "", null);
try std.testing.expect(pdf_pane.search_pane == null);
p.runBuiltin(sections, 0, "", null);
const output_id = pdf_pane.search_pane orelse return error.MissingPdfSectionsOutput;
const output = p.panes[output_id].?;
try std.testing.expectEqual(@as(usize, 0), p.active);
const pdf_layout = p.layoutFindTerm(0) orelse return error.MissingPdfLayout;
const output_layout = p.layoutFindTerm(output_id) orelse return error.MissingPdfSectionsLayout;
try std.testing.expectEqual(pdf_layout.col, output_layout.col);
try std.testing.expectEqual(pdf_layout.idx + 1, output_layout.idx);
try std.testing.expect(Pardes.isPdfSectionsOutput(output));
try std.testing.expect(std.mem.endsWith(u8, output.file.?.path, "/+PdfSections"));
const tag = try p.tagText(p.scratch.allocator(), pdf_pane);
try std.testing.expect(std.mem.indexOf(u8, tag, "PdfSections") != null);
const expected = try std.fmt.allocPrint(
gpa,
"{s}:2:1 [untitled]\n" ++
"{s}:2:2 Café 子\n" ++
"{s}:3:3 [empty title]\n" ++
"https://example.com/manual External\n",
.{ "outline.pdf", "outline.pdf", "outline.pdf" },
);
defer gpa.free(expected);
try std.testing.expectEqualStrings(expected, output.file.?.content);
// The outline is loaded once and a clean live output is reused in place.
try std.testing.expect(pdf_pane.pdf.?.outline_tried);
const outline_ptr = pdf_pane.pdf.?.outline.?.entries.ptr;
const output_serial = output.serial;
const output_revision = output.file.?.revision;
p.runBuiltin(sections, 0, "", null);
try std.testing.expectEqual(output_id, pdf_pane.search_pane.?);
try std.testing.expectEqual(output_serial, p.panes[output_id].?.serial);
try std.testing.expectEqual(output_revision, p.panes[output_id].?.file.?.revision);
try std.testing.expectEqual(outline_ptr, pdf_pane.pdf.?.outline.?.entries.ptr);
// The clean remembered path is a pure re-arm: even an allocator which
// rejects its first request is never consulted, and the outline/content
// identities remain untouched.
var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
const ordinary_gpa = p.gpa;
p.gpa = failing.allocator();
p.openPdfSections(0);
p.gpa = ordinary_gpa;
try std.testing.expectEqual(@as(usize, 0), failing.alloc_index);
try std.testing.expect(!failing.has_induced_failure);
try std.testing.expectEqual(outline_ptr, pdf_pane.pdf.?.outline.?.entries.ptr);
try std.testing.expectEqual(output_revision, p.panes[output_id].?.file.?.revision);
// n and N execute the generated row through ordinary Look. The root and
// child intentionally resolve to the same exact XYZ destination.
p.active = 0;
p.update(.{ .key = .{ .cp = 'n' } });
try std.testing.expectEqual(@as(?usize, 0), pdf_pane.search_row);
try std.testing.expectEqual(@as(usize, 1), pdf_pane.pdf.?.page);
const child_destination = pdf_pane.pdf.?.outline.?.entries[1].destination.internal;
const expected_y = @as(f64, @floatFromInt(pdf_pane.pdf.?.page_starts[1])) +
@as(f64, child_destination.y.?) / @as(f64, pdf_pane.pdf.?.page_sizes[1].height) *
@as(f64, @floatFromInt(pdf_pane.pdf.?.page_heights[1]));
try std.testing.expectApproxEqAbs(expected_y, pdf_pane.pdf.?.document_scroll_y, 0.001);
p.update(.{ .key = .{ .cp = 'n' } });
try std.testing.expectEqual(@as(?usize, 1), pdf_pane.search_row);
try std.testing.expectApproxEqAbs(expected_y, pdf_pane.pdf.?.document_scroll_y, 0.001);
p.update(.{ .key = .{ .cp = 'n' } });
try std.testing.expectEqual(@as(usize, 2), pdf_pane.pdf.?.page);
p.update(.{ .key = .{ .cp = 'N' } });
try std.testing.expectEqual(@as(?usize, 1), pdf_pane.search_row);
try std.testing.expectEqual(@as(usize, 1), pdf_pane.pdf.?.page);
try std.testing.expectApproxEqAbs(expected_y, pdf_pane.pdf.?.document_scroll_y, 0.001);
// Re-looking the same ordinal changes placement only, never pixel identity.
p.native_images = true;
var frame = std.heap.ArenaAllocator.init(gpa);
defer frame.deinit();
_ = try p.render(frame.allocator());
const revision = pdf_pane.pdf.?.render_revision;
const child_row = modal.lineSlice(output.file.?.content, 1);
const child_target = child_row[0 .. std.mem.indexOfScalar(u8, child_row, ' ') orelse child_row.len];
p.lookAt(output_id, child_target);
try std.testing.expectEqual(revision, pdf_pane.pdf.?.render_revision);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
try std.testing.expectEqual(revision, pdf_pane.pdf.?.render_revision);
// The same path:page:col token from any non-PdfSections pane retains the
// established PDF-search meaning for col; no outline reveal is installed.
p.setPdfSearchQuery(&pdf_pane.pdf.?, "ordinary search semantics");
p.lookAt(1, child_target);
try std.testing.expectEqual(@as(usize, 1), pdf_pane.pdf.?.search_hit);
try std.testing.expect(pdf_pane.pdf.?.outline_reveal_pending == null);
p.setPdfSearchQuery(&pdf_pane.pdf.?, "");
// Step forward onto the external row: it uses the existing open_link
// effect and searchStep restores focus to the owning PDF.
p.active = 0;
p.update(.{ .key = .{ .cp = 'n' } });
p.update(.{ .key = .{ .cp = 'n' } });
var opened = false;
while (p.nextEffect()) |effect| switch (effect) {
.open_link => |uri| opened = std.mem.eql(u8, uri.slice(), "https://example.com/manual"),
else => {},
};
try std.testing.expect(opened);
try std.testing.expectEqual(@as(usize, 0), p.active);
// Missing/hostile coordinates clamp to page space. x affects only a
// layout with horizontal overflow and still does not touch raster state.
const saved_size = pdf_pane.pdf.?.page_sizes[1];
pdf_pane.pdf.?.fit = .width;
pdf_pane.pdf.?.layout_valid = false;
pdf_pane.pdf.?.pan_x = 123;
p.revealPdfOutlineDestination(pdf_pane, .{ .page = 1, .x = 190, .y = null });
try std.testing.expectEqual(@as(u16, 123), pdf_pane.pdf.?.pan_x);
try std.testing.expectEqual(@as(f64, @floatFromInt(pdf_pane.pdf.?.page_starts[1])), pdf_pane.pdf.?.document_scroll_y);
pdf_pane.pdf.?.page_sizes[1] = .{ .width = 400, .height = 100 };
pdf_pane.pdf.?.fit = .height;
pdf_pane.pdf.?.layout_valid = false;
pdf_pane.pdf.?.pan_x = 0;
p.revealPdfOutlineDestination(pdf_pane, .{ .page = 1, .x = 390, .y = -500 });
try std.testing.expect(pdf_pane.pdf.?.pan_x > 0);
try std.testing.expectEqual(@as(f64, @floatFromInt(pdf_pane.pdf.?.page_starts[1])), pdf_pane.pdf.?.document_scroll_y);
p.revealPdfOutlineDestination(pdf_pane, .{ .page = 1, .x = std.math.inf(f32), .y = std.math.inf(f32) });
try std.testing.expectEqual(@as(f64, @floatFromInt(pdf_pane.pdf.?.page_starts[1])), pdf_pane.pdf.?.document_scroll_y);
try std.testing.expectEqual(revision, pdf_pane.pdf.?.render_revision);
pdf_pane.pdf.?.page_sizes[1] = saved_size;
// An edited output is preserved. Closing the replacement and reusing its
// slot for an unrelated pane cannot trick the remembered id into a refill.
file_pane.setContent(p, &output.file.?, try gpa.dupe(u8, "edited by user\n"));
p.openPdfSections(0);
const replacement_id = pdf_pane.search_pane orelse return error.MissingReplacementSections;
try std.testing.expect(replacement_id != output_id);
try std.testing.expectEqualStrings("edited by user\n", output.file.?.content);
const replacement_serial = p.panes[replacement_id].?.serial;
p.runBuiltin(.Del, replacement_id, "", null);
try std.testing.expect(p.panes[replacement_id] == null);
const unrelated = try p.openTutorView(replacement_id);
p.placeDoc(0, replacement_id, unrelated);
try std.testing.expect(unrelated.serial != replacement_serial);
p.openPdfSections(0);
try std.testing.expect(pdf_pane.search_pane.? != replacement_id);
try std.testing.expect(Pardes.isPdfSectionsOutput(p.panes[pdf_pane.search_pane.?].?));
}
test "PdfSections opens an empty cached output for a PDF without an outline" {
if (!pdf_enabled or platform == .web) return;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const fixture = try pdf_impl.makeNoOutlineTestPdf(gpa);
defer gpa.free(fixture);
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain.pdf", .data = fixture });
var path_buf: [256]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/plain.pdf", .{tmp.sub_path});
const p = try Pardes.init(gpa, .{ .file = path });
defer p.deinit();
p.openPdfSections(0);
const pane = p.panes[0].?;
const output_id = pane.search_pane orelse return error.MissingEmptyPdfSections;
try std.testing.expectEqual(@as(usize, 0), p.panes[output_id].?.file.?.content.len);
try std.testing.expect(pane.pdf.?.outline_tried);
try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.outline.?.entries.len);
const serial = p.panes[output_id].?.serial;
p.openPdfSections(0);
try std.testing.expectEqual(output_id, pane.search_pane.?);
try std.testing.expectEqual(serial, p.panes[output_id].?.serial);
}
fn nextPipeEffect(p: *Pardes) ?u32 {
while (p.nextEffect()) |effect| switch (effect) {
.pipe => |request| return request.id,
else => {},
};
return null;
}
test "selection pipe prompt submits exact request and Escape cancels" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.hxOpenFileContent("one\ntwo\n");
pane.cur_row = 0;
pane.cur_col = 2;
pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
p.update(.{ .key = .{ .cp = '|' } });
try std.testing.expect(pane.tag_edit and pane.pipe_edit);
try std.testing.expect(std.mem.endsWith(u8, pane.tag_tail.items, config.pipe_marker));
try std.testing.expect(nextPipeEffect(p) == null);
p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(!pane.tag_edit and !pane.pipe_edit);
const id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
const request = p.pipeRequest(id) orelse return error.MissingPipeRequest;
try std.testing.expectEqualStrings("tr a-z A-Z", request.command);
try std.testing.expectEqualStrings("/", request.cwd);
try std.testing.expectEqual(@as(usize, 1), request.inputs.len);
try std.testing.expectEqualSlices(u8, "one", request.inputs[0].bytes);
const before = pane.file.?.content;
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(!pane.tag_edit and !pane.pipe_edit);
try std.testing.expectEqualSlices(u8, before, pane.file.?.content);
try std.testing.expect(nextPipeEffect(p) == null);
}
test "selection pipe replaces all ranges atomically and undo restores them" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.hxOpenFileContent("aa bb cc\n");
const pl = try p.paneCursorLines(pane);
const ranges = [_]modal.HxRange{
.{ .anchor = 0, .head = 2 },
.{ .anchor = 6, .head = 8 },
};
Pardes.setPaneRanges(pane, pl, pane.file.?.content, &ranges, &.{}, 0, true);
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
const request = p.pipeRequest(id) orelse return error.MissingPipeRequest;
try std.testing.expectEqual(@as(usize, 2), request.inputs.len);
try std.testing.expectEqualSlices(u8, "aa", request.inputs[0].bytes);
try std.testing.expectEqualSlices(u8, "cc", request.inputs[1].bytes);
const outputs: []const []const u8 = &.{ "AA\n", "" };
p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } });
try std.testing.expectEqualSlices(u8, "AA\n bb \n", pane.file.?.content);
try std.testing.expectEqual(@as(usize, 1), pane.file.?.undo.items.len);
try std.testing.expectEqual(@as(u8, 1), pane.nsel);
p.update(.{ .key = .{ .cp = 'u' } });
try std.testing.expectEqualSlices(u8, "aa bb cc\n", pane.file.?.content);
}
test "selection pipe failure and stale completion never mutate the file" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.hxOpenFileContent("abc\n");
pane.cur_col = 2;
pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const failed_id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
p.update(.{ .pipe_resp = .{ .id = failed_id, .success = false, .outputs = &.{} } });
try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content);
try std.testing.expectEqual(@as(usize, 0), pane.file.?.undo.items.len);
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const stale_id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
file_pane.setContent(p, &pane.file.?, try gpa.dupe(u8, "changed\n"));
p.update(.{ .pipe_resp = .{ .id = stale_id, .success = true, .outputs = &.{"ABC"} } });
try std.testing.expectEqualSlices(u8, "changed\n", pane.file.?.content);
try std.testing.expectEqual(@as(usize, 0), pane.file.?.undo.items.len);
}
test "selection pipe rejects a reused pane slot and a superseded request" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
var pane = try p.hxOpenFileContent("old\n");
pane.cur_col = 2;
pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const replaced_id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
pane = try p.hxOpenFileContent("new\n"); // same slot, different serial
p.update(.{ .pipe_resp = .{ .id = replaced_id, .success = true, .outputs = &.{"OLD"} } });
try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content);
try std.testing.expectEqual(@as(usize, 0), pane.file.?.undo.items.len);
pane.cur_col = 2;
pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "cat" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const first_id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
p.update(.{ .key = .{ .cp = '|' } });
p.update(.{ .key = .{ .cp = 'c', .text = "tr a-z A-Z" } });
p.update(.{ .key = .{ .cp = Key.enter } });
const latest_id = nextPipeEffect(p) orelse return error.MissingPipeEffect;
try std.testing.expect(first_id != latest_id);
p.update(.{ .pipe_resp = .{ .id = first_id, .success = true, .outputs = &.{"BAD"} } });
try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content);
p.update(.{ .pipe_resp = .{ .id = latest_id, .success = true, .outputs = &.{"NEW"} } });
try std.testing.expectEqualSlices(u8, "NEW\n", pane.file.?.content);
try std.testing.expectEqual(@as(usize, 1), pane.file.?.undo.items.len);
}
test "selection pipe binding is file-normal-only" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.hxOpenFileContent("x");
pane.file.?.output = .{ .from = .search };
p.update(.{ .key = .{ .cp = '|' } });
try std.testing.expect(!pane.pipe_edit);
pane.file.?.output = null;
pane.mode = .insert;
p.update(.{ .key = .{ .cp = '|', .text = "|" } });
try std.testing.expect(!pane.pipe_edit);
try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content);
}
test "startup config runs builtin lines in order and isolates bad lines" {
const p = try Pardes.init(std.testing.allocator, .{
.startup_config =
\\Theme dark
\\DefinitelyNotABuiltin
\\Kill trailing-garbage
\\Theme no-such-theme
\\Theme acme
,
});
defer p.deinit();
// The last valid command wins even after unknown, malformed, and
// well-formed-but-failing lines. `Kill trailing-garbage` must not be
// accepted as Kill, nor fall through to the shell from config.
try std.testing.expectEqualStrings("acme", p.theme().name);
try std.testing.expect(!p.themeAnimationActive());
try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*);
try std.testing.expect(!p.quit);
for (p.effects.items) |effect| switch (effect) {
.write => |w| {
try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "DefinitelyNotABuiltin") == null);
try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "Kill") == null);
},
else => {},
};
}
test "runtime theme changes animate chrome and retarget without a jump" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const first = p.chromeTheme().*;
try std.testing.expect(!p.themeAnimationActive());
const dark_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "dark")) break i;
} else return error.MissingDarkTheme;
const acme_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "acme")) break i;
} else return error.MissingAcmeTheme;
p.setThemeIndex(dark_index);
// Target semantics are immediate, while the displayed chrome begins at
// the exact previous frame.
try std.testing.expectEqualStrings("dark", p.theme().name);
try std.testing.expectEqual(first, p.chromeTheme().*);
try std.testing.expect(p.themeAnimationActive());
p.update(.tick);
p.update(.tick);
p.update(.tick);
const midflight = p.chromeTheme().*;
try std.testing.expect(!std.meta.eql(first, midflight));
p.setThemeIndex(acme_index);
try std.testing.expectEqualStrings("acme", p.theme().name);
try std.testing.expectEqual(midflight, p.chromeTheme().*);
try std.testing.expect(p.themeAnimationActive());
for (0..animation.transition_steps) |_| p.update(.tick);
try std.testing.expect(!p.themeAnimationActive());
try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*);
// Extra ticks are inert at the exact endpoint.
p.update(.tick);
try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*);
}
test "render uses target content colors while chrome is in flight" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
const source_chrome = p.chromeTheme().*;
const acme_index = for (themes, 0..) |th, i| {
if (std.mem.eql(u8, th.name, "acme")) break i;
} else return error.MissingAcmeTheme;
p.setThemeIndex(acme_index);
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const surface = try p.render(frame.allocator());
// The anchored topbar has not advanced from its source frame.
try std.testing.expectEqual(
Color{ .rgb = source_chrome.tag_bg },
surface.at(0, 0).style.bg,
);
// The document/terminal page does not ride the chrome animation: acme's
// target background is already present in the same render.
const r = p.rects[0];
const body = surface.at(r.x + r.w - 1, r.y + r.h - 1);
try std.testing.expectEqual(
Color{ .rgb = p.theme().bg.? },
body.style.bg,
);
try std.testing.expect(p.themeAnimationActive());
}
test "pane-tag Exec prefers New and argument builtins before shell fallback" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {} // initial shell spawn/geometry
const pane = p.panes[0].?;
try std.testing.expectEqualStrings(" New Del", Pardes.curTail(pane));
const tag_x = p.rects[0].x + config.GUTTER;
const tag_y = p.rects[0].y;
// A real middle-click on the canonical pane-tag word reaches Exec, which
// must consume New as a builtin before any write can reach the shell.
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } });
var saw_new = false;
while (p.nextEffect()) |effect| switch (effect) {
.new_file => |request| {
try std.testing.expectEqual(@as(u8, 0), request.pane);
try std.testing.expectEqual(pane.serial, request.serial);
saw_new = true;
},
.write => return error.NewFellThroughToPty,
else => {},
};
try std.testing.expect(saw_new);
// Argument-taking builtins use the same gesture path: a tag sweep is the
// complete command line, and Theme consumes its tail without a PTY write.
pane.tag_tail.clearRetainingCapacity();
try pane.tag_tail.appendSlice(gpa, " Theme dark");
pane.tag_init = true;
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .drag, .col = tag_x + 10, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 10, .row = tag_y } });
try std.testing.expectEqualStrings("dark", p.theme().name);
while (p.nextEffect()) |effect| switch (effect) {
.write => return error.ArgumentBuiltinFellThroughToPty,
else => {},
};
// Fixed-name builtins remain exact: a tail does not turn New or Kill into
// a match (especially important for the destructive one).
try std.testing.expect(!p.executeBuiltinLine(0, "New argument"));
try std.testing.expect(!p.executeBuiltinLine(0, "Kill trailing-garbage"));
try std.testing.expect(!p.quit);
// A word absent from the builtin vocabulary takes the fallback, including
// the terminating carriage return expected by the shell prompt.
pane.tag_tail.clearRetainingCapacity();
try pane.tag_tail.appendSlice(gpa, " DefinitelyNotABuiltin");
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } });
p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } });
var sent: std.ArrayList(u8) = .empty;
defer sent.deinit(gpa);
while (p.nextEffect()) |effect| switch (effect) {
.write => |w| {
try std.testing.expectEqual(@as(u8, 0), w.pane);
try sent.appendSlice(gpa, w.bytes.slice());
},
.new_file => return error.UnknownCommandRanNew,
else => {},
};
try std.testing.expectEqualStrings("DefinitelyNotABuiltin\r", sent.items);
}
test "legacy default tag tails upgrade while custom tails remain owned" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
const terminal = p.panes[0].?;
const terminal_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{
try p.tagPrefix(terminal),
legacy_pane_tail,
});
p.restoreTail(terminal, terminal_old);
try std.testing.expect(!terminal.tag_init);
try std.testing.expectEqualStrings(" New Del", Pardes.curTail(terminal));
const terminal_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Keep Del", .{
try p.tagPrefix(terminal),
});
p.restoreTail(terminal, terminal_custom);
try std.testing.expect(terminal.tag_init);
try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal));
// A savable file has a distinct old default. Save remains first after the
// migration so the tag's established `:w<Tab>` route is unchanged.
const file = try p.hxOpenFileContent("");
const file_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{
try p.tagPrefix(file),
legacy_file_pane_tail,
});
p.restoreTail(file, file_old);
try std.testing.expect(!file.tag_init);
try std.testing.expectEqualStrings(" Save New Del", Pardes.curTail(file));
const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{
try p.tagPrefix(file),
});
p.restoreTail(file, file_custom);
try std.testing.expect(file.tag_init);
try std.testing.expectEqualStrings(" Save Mine Del", Pardes.curTail(file));
}
test "unknown Exec from an image writes to a terminal in the image directory" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/pardes-image-dir");
const image_pane = try p.newDocPane(1);
image_pane.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-image-dir/pic.ppm") };
try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_pane));
try std.testing.expectEqual(@as(?usize, 0), p.execute(1, "echo image-fallback"));
var sent: std.ArrayList(u8) = .empty;
defer sent.deinit(gpa);
while (p.nextEffect()) |effect| switch (effect) {
.write => |w| {
try std.testing.expectEqual(@as(u8, 0), w.pane);
try sent.appendSlice(gpa, w.bytes.slice());
},
.spawn => return error.ImageExecSpawnedDespiteMatchingTerminal,
else => {},
};
try std.testing.expectEqualStrings("echo image-fallback\r", sent.items);
}
test "New completes as an empty watched file in the calling column and focuses it" {
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {} // initial shell spawns
const source: usize = 2; // the right column; active starts in the left
const source_col = p.layoutFindTerm(source).?.col;
try std.testing.expect(p.executeBuiltinLine(source, "New"));
var request: ?Effect = null;
while (p.nextEffect()) |effect| switch (effect) {
.new_file => request = effect,
else => {},
};
const new_effect = request orelse return error.MissingNewFileEffect;
const req = new_effect.new_file;
try std.testing.expectEqual(@as(u8, @intCast(source)), req.pane);
try std.testing.expectEqual(p.panes[source].?.serial, req.serial);
// Focus changes while the shell is doing IO. Placement must still use the
// effect's calling-pane token, never this later-active left column.
p.active = 0;
try std.testing.expect(p.openNewFile(req.pane, req.serial, "/tmp/pardes-test-new-a"));
const id = p.active;
try std.testing.expect(id != 0 and id != source);
try std.testing.expectEqual(source_col, p.layoutFindTerm(id).?.col);
const sf = p.layoutFindTerm(source).?;
try std.testing.expectEqual(id, p.col_terms[sf.col][sf.idx + 1]);
const file = p.panes[id].?.file orelse return error.NewIsNotAFile;
try std.testing.expectEqualStrings("/tmp/pardes-test-new-a", file.path);
try std.testing.expectEqual(@as(usize, 0), file.content.len);
try std.testing.expect(file.output == null);
try std.testing.expect(!p.panes[id].?.isTerminal());
var watched = false;
while (p.nextEffect()) |effect| switch (effect) {
.watch => |w| if (w.pane == id and w.on) {
watched = true;
},
else => {},
};
try std.testing.expect(watched);
// It is an ordinary file from here on: Save uses the normal file effect,
// and the dump contains its path and empty content.
try std.testing.expect(p.executeBuiltinLine(id, "Save"));
var saved = false;
while (p.nextEffect()) |effect| switch (effect) {
.save_file => |s| if (s.pane == id) {
saved = true;
},
else => {},
};
try std.testing.expect(saved);
try p.dumpState();
const state = try dump.readZon(std.testing.allocator, p.dump_out.?, "New-test");
defer dump.free(std.testing.allocator, state);
var dumped = false;
for (state.panes) |dp| if (dp.file) |df| {
if (std.mem.eql(u8, df.path, "/tmp/pardes-test-new-a")) {
try std.testing.expectEqual(@as(usize, 0), df.content.len);
dumped = true;
}
};
try std.testing.expect(dumped);
while (p.nextEffect()) |_| {} // write_dump
// Del closes and unwatches, but there is intentionally no unlink effect:
// adopted temporary documents preserve user data and dump restorability.
try std.testing.expect(p.executeBuiltinLine(id, "Del"));
try std.testing.expect(p.panes[id] == null);
var unwatched = false;
while (p.nextEffect()) |effect| switch (effect) {
.watch => |w| if (w.pane == id and !w.on) {
unwatched = true;
},
else => {},
};
try std.testing.expect(unwatched);
}
test "New requests repeat, stay anchored, and reject stale or full completions" {
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const source: usize = 2;
const source_col = p.layoutFindTerm(source).?.col;
try std.testing.expect(p.executeBuiltinLine(source, "New"));
try std.testing.expect(p.executeBuiltinLine(source, "New"));
var requests: [2]Effect = undefined;
var n: usize = 0;
while (p.nextEffect()) |effect| switch (effect) {
.new_file => if (n < requests.len) {
requests[n] = effect;
n += 1;
},
else => {},
};
try std.testing.expectEqual(requests.len, n);
p.active = 0;
try std.testing.expect(p.openNewFile(requests[0].new_file.pane, requests[0].new_file.serial, "/tmp/pardes-test-new-1"));
const first = p.active;
p.active = 1; // change focus again before the second completion
try std.testing.expect(p.openNewFile(requests[1].new_file.pane, requests[1].new_file.serial, "/tmp/pardes-test-new-2"));
const second = p.active;
try std.testing.expect(first != second);
try std.testing.expectEqual(source_col, p.layoutFindTerm(first).?.col);
try std.testing.expectEqual(source_col, p.layoutFindTerm(second).?.col);
try std.testing.expect(!std.mem.eql(u8, p.panes[first].?.file.?.path, p.panes[second].?.file.?.path));
while (p.nextEffect()) |_| {}
// A reused pane slot cannot answer an old request, and a malformed shell
// answer cannot manufacture a nameless file.
const old_serial = p.panes[source].?.serial;
p.panes[source].?.serial +%= 1;
try std.testing.expect(!p.openNewFile(@intCast(source), old_serial, "/tmp/pardes-test-stale"));
try std.testing.expect(!p.openNewFile(@intCast(source), p.panes[source].?.serial, ""));
// Exhaust every remaining slot after a request was issued: completion
// rejects it, which tells the shell to unlink the just-created candidate.
const live_serial = p.panes[source].?.serial;
for (0..MAX_PANES) |id| {
if (p.panes[id] == null) _ = try p.newDocPane(id);
}
try std.testing.expect(!p.openNewFile(@intCast(source), live_serial, "/tmp/pardes-test-full"));
try std.testing.expect(p.executeBuiltinLine(source, "New"));
var emitted_when_full = false;
while (p.nextEffect()) |effect| switch (effect) {
.new_file => emitted_when_full = true,
else => {},
};
try std.testing.expect(!emitted_when_full);
}
test "startup config overrides restored styling before initFromDump returns" {
const source = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme dark\n" });
defer source.deinit();
try std.testing.expectEqualStrings("dark", source.theme().name);
try source.dumpState();
const restored = try Pardes.initFromDump(
std.testing.allocator,
.{ .startup_config = "Theme acme\n" },
source.dump_out.?,
);
defer restored.deinit();
try std.testing.expectEqualStrings("acme", restored.theme().name);
try std.testing.expect(!source.themeAnimationActive());
try std.testing.expect(!restored.themeAnimationActive());
try std.testing.expectEqual(ChromeTheme.fromTheme(source.theme()), source.chromeTheme().*);
try std.testing.expectEqual(ChromeTheme.fromTheme(restored.theme()), restored.chromeTheme().*);
}
/// How a `Chord` is SPELLED in the index. The named keys come from Key's OWN
/// declarations rather than a table beside them — a new special key names
/// itself here, and a wrong name is impossible because there is only one. The
/// rest is the printable character; anything else is a compile error, because
/// a private-use codepoint cast to a byte would render as silent garbage in a
/// listing nobody diffs.
fn chordName(comptime c: config.Chord) []const u8 {
comptime {
const mods = (if (c.ctrl) "C-" else "") ++ (if (c.alt) "A-" else "") ++ (if (c.shift) "S-" else "");
for (@typeInfo(Key).@"struct".decls) |d| {
if (@TypeOf(@field(Key, d.name)) != u21) continue;
if (@field(Key, d.name) == c.cp) return mods ++ d.name;
}
if (c.cp < 0x20 or c.cp > 0x7e) @compileError("chord has no name for the index");
return mods ++ &[_]u8{@as(u8, @intCast(c.cp))};
}
}
/// Every way to run `b` that is NOT its leader path: the chords and buttons
/// config binds to it, plus the topbar if it has a word up there (row 0 is a
/// click target, and the only shortcut that works in tty mode where SPC
/// belongs to the shell). Walked from config's own tables — window_keys' and
/// jump_keys' `cmd` columns, look_cmd/exec_cmd, topbar_str — so retargeting a
/// binding there re-renders here with nothing to keep in step.
///
/// What is NOT here, and cannot be: a chord that reaches no builtin. Alt-n,
/// Alt-c, the tty toggle and the 1-2/1-3 cut/paste chords are inline handlers
/// with no word to index by. The day one of them becomes a builtin — a struct
/// in builtins.zig and a `cmd` column beside its binding — it appears here for
/// free, which is the upgrade path rather than a special case here.
fn shortcuts(comptime b: Builtin) []const u8 {
comptime {
@setEvalBranchQuota(20000);
var parts: []const []const u8 = &.{};
// both spellings of the four directional moves: the arrow is a real
// key someone presses, and the table carries it precisely so it is
// discoverable from the builtin as well as the other way round
for (config.window_keys) |wk| {
if (wk.cmd != b) continue;
// the prefix has one spelling and this is it
const pfx = chordName(config.window_prefix[0]) ++ " ";
parts = parts ++ &[_][]const u8{ pfx ++ chordName(wk.letter), pfx ++ chordName(wk.arrow) };
}
for (config.jump_keys) |jk| {
if (jk.cmd == b) parts = parts ++ &[_][]const u8{chordName(jk.chord)};
}
// the two acme verbs, a key and a mouse button each. Asked of the
// BINDING (look_cmd/exec_cmd point at a builtin) rather than of Look
// and Exec by name, so pointing look_cmd at Grep moves the row.
if (config.look_cmd == b) {
for (config.look_key) |k| parts = parts ++ &[_][]const u8{chordName(k)};
parts = parts ++ &[_][]const u8{@tagName(config.look_button) ++ "-click"};
}
if (config.exec_cmd == b) {
for (config.exec_key) |k| parts = parts ++ &[_][]const u8{chordName(k)};
parts = parts ++ &[_][]const u8{@tagName(config.exec_button) ++ "-click"};
}
var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' ');
while (it.next()) |w| {
if (std.mem.eql(u8, w, @tagName(b))) parts = parts ++ &[_][]const u8{"topbar"};
}
var out: []const u8 = "";
for (parts, 0..) |s, i| out = out ++ (if (i > 0) ", " else "") ++ s;
return out;
}
}
/// THE BUILTIN INDEX, flattened: one row per builtin — the leader path that
/// runs it (null: SPC does not reach it), every other way to run it, and the
/// Help line those are rendered into. SORTED BY PATH, so every prefix's
/// subtree is a contiguous run, which is all the two runtime readers need. The
/// matcher asks "exact hit? still a prefix of something?" and Help filters the
/// same rows by the same prefix. A node-and-pointer trie for forty
/// two-character paths would be ceremony.
///
/// A row per BUILTIN and no longer a row per leader PATH, which is what makes
/// Help the complete index instead of a second builtin listing a superset of
/// what Help lists. A path-less builtin (Look, Exec, Theme) is a row like any
/// other and its empty key column is the information: SPC does not reach this
/// one, the last column does — or nothing does, which is also worth knowing.
/// The mid-chord filter is the SAME array read with a non-empty prefix, and it
/// drops those rows by itself because an empty path starts with nothing.
const Row = struct { path: ?[]const u8, cmd: Builtin, line: []const u8 };
pub const builtin_rows: [std.enums.values(Builtin).len]Row = blk: {
// one pass per builtin per config table, and the insertion sort below is
// O(n²) comptime branches on top of it
@setEvalBranchQuota(200000);
var rows: [std.enums.values(Builtin).len]Row = undefined;
// the widest spaced-out path ("l D" = 3) and the widest name, so the three
// columns line up
var keyw: usize = 0;
var namew: usize = 0;
for (std.enums.values(Builtin)) |b| {
if (config.leader_path.get(b)) |p| keyw = @max(keyw, 2 * p.len - 1);
namew = @max(namew, @tagName(b).len);
}
for (std.enums.values(Builtin), 0..) |b, i| {
var keys: []const u8 = "";
if (config.leader_path.get(b)) |path| {
keys = "SPC ";
for (path, 0..) |c, k| {
if (k > 0) keys = keys ++ " ";
keys = keys ++ &[_]u8{c};
}
}
// the name column is only padded when something follows it: a row
// whose builtin has no other shortcut ends at the name, so the listing
// carries no trailing whitespace
const rest = shortcuts(b);
const named = @tagName(b) ++ (if (rest.len == 0) "" else (" " ** (namew - @tagName(b).len)) ++ " " ++ rest);
rows[i] = .{
.path = config.leader_path.get(b),
.cmd = b,
.line = keys ++ (" " ** (4 + keyw - keys.len)) ++ " " ++ named,
};
}
// insertion sort by path: a group sorts right before what extends it, and
// a path-less builtin sorts after every path — DEL is not a path because
// leaderKey only ever stores a printable key
const last = "\x7f";
for (1..rows.len) |i| {
var j = i;
while (j > 0 and std.mem.lessThan(u8, rows[j].path orelse last, rows[j - 1].path orelse last)) : (j -= 1) {
const t = rows[j];
rows[j] = rows[j - 1];
rows[j - 1] = t;
}
}
break :blk rows;
};
// config.topbar_str is a HAND-PICKED subset of the builtins in a fixed order,
// not a derivation — see it there for why each word is in or out. This is the
// check that a rename cannot silently rot it.
comptime {
@setEvalBranchQuota(20000); // the tokenizer walks the string one branch per byte, stringToEnum builds a map per name, and both sit behind the decl walk that folds Builtin
var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' ');
while (it.next()) |w| {
if (std.meta.stringToEnum(Builtin, w) == null) @compileError("topbar word is not a builtin: " ++ w);
}
}
/// the whitespace-delimited word covering `col` in `str` (topbar dispatch)
fn wordAtCol(str: []const u8, col: u16) []const u8 {
if (col >= str.len or str[col] == ' ') return "";
var lo: usize = col;
while (lo > 0 and str[lo - 1] != ' ') lo -= 1;
var hi: usize = col;
while (hi < str.len and str[hi] != ' ') hi += 1;
return str[lo..hi];
}
/// `a` IS `b` or lives under it — how Grep drops a pane's directory when
/// another pane's directory already covers it
fn pathUnder(a: []const u8, b: []const u8) bool {
const root = std.mem.trimEnd(u8, b, "/");
if (!std.mem.startsWith(u8, a, root)) return false;
return a.len == root.len or a[root.len] == '/';
}
const tutor_text = @embedFile("tutor.txt");
const rc_path = "/tmp/pardes-osc133.bash";
pub const bash_rc =
\\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc"
\\PS1='\[\e]133;A;cl=line\a\]'"$PS1"'\[\e]133;B\a\]'
\\PROMPT_COMMAND='printf "\e]133;D\a"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
\\trap 'printf "\e]133;C\a"' DEBUG
\\
;
// ---- theme ----
/// Halfway between two colors, channel by channel. Every selection tint pardes
/// paints is a mix of theme colors — the per-mouse-button ones pull the theme's
/// selection toward one of its own accents, a quarter of the way and so a mix
/// of a mix; the extra cursors' pulls it back toward the page — and renderPane
/// makes seven of those, which is six more than spelling the same three-channel
/// loop out at the call site is worth.
fn mix(a: [3]u8, b: [3]u8) [3]u8 {
var out: [3]u8 = undefined;
for (&out, a, b) |*c, x, y| c.* = @intCast((@as(u16, x) + y) / 2);
return out;
}
const UNDO_MAX = 256;
const EDIT_UNDO_MAX = 64; // terminal snapshots copy the edit buffer; cap tighter
/// Everything a theme repaints. `bg`/`fg` null = leave the host terminal's own
/// default cell showing (the native-dark shape); `palette` null = let a child's
/// ANSI indices reach the host untranslated. The gutter's move box lives here
/// too: it used to be a pair of module constants, but a theme that wants to be
/// restrained has to be able to turn the accent DOWN, and the box is the one
/// piece of loud chrome on screen. The overlay/drag greys that were also
/// hardcoded turned out to be the dark theme's own scroll_track/lineno/tag_fg
/// spelled a second time, so they read those fields now instead.
///
/// Selection is ONE pair, `sel_bg`/`sel_fg`, and the rest is arithmetic: the
/// three per-mouse-button tints and the dimmed extra cursors are mixed off it in
/// renderPane rather than named here. A theme author gets their selection colour
/// right and would get four more by accident — and every source gen_themes reads
/// names exactly one selection anyway.
pub const Theme = struct {
name: []const u8,
bg: ?[3]u8,
fg: ?[3]u8,
sel_bg: [3]u8,
sel_fg: [3]u8,
tag_bg: [3]u8,
tag_fg: [3]u8,
box: [3]u8, // move box, focused pane
box_dim: [3]u8, // move box, everything else
kw: [3]u8,
str: [3]u8,
num: [3]u8,
comment: [3]u8,
lineno: [3]u8,
scroll_track: [3]u8,
scroll_thumb: [3]u8,
palette: ?[16][3]u8,
};
/// The three themes pardes ships with, in RING ORDER, which is the one thing
/// the files themselves cannot say: `helix` is index 0 and so what boots, and
/// NextColor walks from here out into the generated ones. Written here rather
/// than in a fourth file because the order IS the information — and it is
/// load-bearing, since test/snapshots/theme.snap captures the first three
/// steps of the ring by their colors.
const curated = struct {
pub const helix = @import("themes/helix.zig");
pub const dark = @import("themes/dark.zig");
pub const acme = @import("themes/acme.zig");
};
/// A zig file IS a struct, so the FILES are the list: this walks a container's
/// declarations — each one an imported theme file — and copies its `theme`
/// value into a real Theme. FIELD BY FIELD rather than by plain coercion,
/// because a theme file deliberately imports nothing (it is data, not code) and
/// zig will not coerce a whole anonymous struct into a named one; assigning one
/// field at a time puts each value in a result location that knows the type,
/// which is also what makes a missing field a compile error naming it.
///
/// A FUNCTION and not a const for the same reason builtins.all is one: it is
/// only ever a signature to whoever walks it, never a value in its own way.
fn fold(comptime C: type) []const Theme {
comptime {
@setEvalBranchQuota(400000); // 228 themes x 15 fields, each field a @field lookup, and the array re-concatenated per theme
var out: []const Theme = &.{};
for (@typeInfo(C).@"struct".decls) |d| {
var t: Theme = undefined;
for (@typeInfo(Theme).@"struct".fields) |f| @field(t, f.name) = @field(@field(C, d.name).theme, f.name);
out = out ++ &[_]Theme{t};
}
return out;
}
}
/// The ring: ours, then every theme tools/gen_themes.zig exported out of the
/// helix and zed sources in vendor/themes (build.zig runs it and hands the
/// result over as a module). Adding one is dropping a file in there — there is
/// no list here to append to, which is the whole point of folding the files.
/// 228 of them: everything helix and zed ship, because "which of these is worth
/// having" is the user's call and not the build's. That length is why ThemeSel
/// exists — NextColor is a browse, not a way to arrive anywhere in particular.
pub const themes = fold(curated) ++ fold(@import("generated_themes"));
// Two themes answering to one name is a bug: `Theme <name>` resolves by name
// and would silently pick whichever came first, and ThemeSel would list the
// loser as a row that does nothing. The generated half cannot collide with
// ITSELF — one file per theme, all imported into one struct, so zig's own
// redeclaration error already catches that — which leaves exactly the cross
// pair to check here, three times 225 rather than 228 squared. This is the
// check that makes helix's `acme.toml` vendored as `acme_helix.toml`.
comptime {
@setEvalBranchQuota(20000);
const ours = fold(curated).len;
for (themes[0..ours]) |c| for (themes[ours..]) |g| if (std.mem.eql(u8, c.name, g.name))
@compileError("theme name \"" ++ c.name ++ "\" is both ours and generated; rename the vendored source");
}
/// The color roles attached to stable screen geometry. Document backgrounds,
/// syntax, terminal ANSI palettes, and PDF tint colors deliberately are not
/// here: those switch to `theme()` immediately while this small palette moves
/// between themes over a handful of display frames.
pub const ChromeTheme = struct {
tag_bg: [3]u8,
tag_fg: [3]u8,
box: [3]u8,
box_dim: [3]u8,
lineno: [3]u8,
scroll_track: [3]u8,
scroll_thumb: [3]u8,
pub fn fromTheme(th: *const Theme) ChromeTheme {
return .{
.tag_bg = th.tag_bg,
.tag_fg = th.tag_fg,
.box = th.box,
.box_dim = th.box_dim,
.lineno = th.lineno,
.scroll_track = th.scroll_track,
.scroll_thumb = th.scroll_thumb,
};
}
pub fn interpolate(from: ChromeTheme, to: ChromeTheme, step: u16, steps: u16) ChromeTheme {
var out: ChromeTheme = undefined;
inline for (@typeInfo(ChromeTheme).@"struct".fields) |field|
@field(out, field.name) = animation.interpolateRgb(@field(from, field.name), @field(to, field.name), step, steps);
return out;
}
};
const ChromeAnimation = animation.Transition(ChromeTheme);
const initial_chrome = ChromeTheme.fromTheme(&themes[0]);
// ---- the boundary types ----
pub const Color = union(enum) { default, index: u8, rgb: [3]u8 };
pub const CellStyle = struct {
fg: Color = .default,
bg: Color = .default,
bold: bool = false,
dim: bool = false,
italic: bool = false,
blink: bool = false,
reverse: bool = false,
invisible: bool = false,
strikethrough: bool = false,
ul: enum { off, single, double, curly, dotted, dashed } = .off,
};
/// One surface cell. `default = true` means "never painted this frame": the
/// shell renders it as the terminal's default cell (vaxis clear semantics).
pub const Cell = struct {
text: [7]u8 = @splat(' '),
len: u8 = 1,
style: CellStyle = .{},
default: bool = true,
pub fn grapheme(c: *const Cell) []const u8 {
return c.text[0..c.len];
}
};
/// One generation of a pixel attachment. `serial` identifies the pane for its
/// whole lifetime; `revision` identifies pixels rendered later by that same
/// pane (for example, a different PDF page or zoom level). Backends must use
/// both: pane slots are reused, while a live pane may replace its pixels.
pub const ImageCacheKey = if (pdf_enabled) struct {
serial: u32,
page: u32,
revision: u32,
pub fn eql(a: @This(), b: @This()) bool {
return a.serial == b.serial and a.page == b.page and
a.revision == b.revision;
}
} else struct {
serial: u32,
pub fn eql(a: @This(), b: @This()) bool {
return a.serial == b.serial;
}
};
/// Native PDF sizing is deliberately semantic rather than a backend knob.
/// Width mode is the document-reading view (the page may be panned vertically);
/// height mode keeps one whole page-height visible and may pan wide pages.
/// The type remains available to shared core code, while PdfView itself and
/// the builtin which mutates it are compiled away with `-Dmupdf=false`.
const PdfFitMode = if (pdf_enabled) enum { width, height } else void;
const PdfTintMode = if (pdf_enabled) pdf_impl.TintMode else void;
/// Every resident page records the PDF-only pixel state it was rendered for.
/// Disabled deliberately ignores colors: changing a theme must not replace an
/// untouched PDF raster. In tinted modes colors are part of the generation.
const PdfTintKey = if (pdf_enabled) struct {
mode: PdfTintMode,
colors: pdf_impl.TintColors,
fn eql(a: @This(), b: @This()) bool {
return a.mode == b.mode and
(a.mode == .disabled or std.meta.eql(a.colors, b.colors));
}
} else void;
/// Dynamic placement exists only for native PDF pages. Static image panes need
/// only their pane identity, so feature-off builds carry a zero-bit payload.
pub const NativePlacement = if (pdf_enabled) struct {
revision: u32 = 0,
page: u32 = 0,
fit: image.NativeFit = .contain,
pan_x: u16 = 0,
pan_y: u16 = 0,
/// Continuous-document pages supply their already-clipped geometry.
/// Static images and legacy callers leave this null and derive fit/pan.
geometry: ?image.NativeGeometry = null,
/// Subpixel vertical displacement retained from proportional SDL wheel dy.
pixel_offset_y: f32 = 0,
} else struct {};
/// A pixel image riding the surface: the shell transmits/places it over the
/// given cell rect (tty: Kitty graphics; SDL: alpha-blended GPU texture).
/// This is also the backend-neutral transport for rasterized PDF pages.
pub const ImagePlace = struct {
pane: u8,
/// Pane slots are reused. This identity makes a cached GPU texture or
/// kitty image unambiguously belong to the pane which supplied the bytes.
serial: u32,
native: NativePlacement = .{},
x: u16,
y: u16,
w: u16,
h: u16,
rgba: []const u8,
iw: usize,
ih: usize,
pub fn cacheKey(place: ImagePlace) ImageCacheKey {
if (comptime pdf_enabled)
return .{
.serial = place.serial,
.page = place.native.page,
.revision = place.native.revision,
};
return .{ .serial = place.serial };
}
};
test "pixel attachment cache key follows both pane lifetime and rendered revision" {
if (comptime pdf_enabled) {
const first = ImageCacheKey{ .serial = 41, .page = 7, .revision = 3 };
try std.testing.expect(first.eql(.{ .serial = 41, .page = 7, .revision = 3 }));
try std.testing.expect(!first.eql(.{ .serial = 41, .page = 8, .revision = 3 }));
try std.testing.expect(!first.eql(.{ .serial = 41, .page = 7, .revision = 4 }));
try std.testing.expect(!first.eql(.{ .serial = 42, .page = 7, .revision = 3 }));
} else {
const first = ImageCacheKey{ .serial = 41 };
try std.testing.expect(first.eql(.{ .serial = 41 }));
try std.testing.expect(!first.eql(.{ .serial = 42 }));
}
try std.testing.expectEqual(pdf_enabled, @hasField(ImageCacheKey, "revision"));
try std.testing.expectEqual(pdf_enabled, @hasField(NativePlacement, "fit"));
try std.testing.expectEqual(pdf_enabled, @hasField(CellPixels, "w"));
if (comptime !pdf_enabled) {
try std.testing.expectEqual(@as(usize, 4), @sizeOf(ImageCacheKey));
try std.testing.expectEqual(@as(usize, 0), @sizeOf(NativePlacement));
try std.testing.expectEqual(@as(usize, 0), @sizeOf(CellPixels));
try std.testing.expectEqual(@as(usize, 0), @sizeOf(PdfDrag));
}
}
test "pixel attachment fit and pan do not invalidate cached pixels" {
if (comptime !pdf_enabled) return;
var place = ImagePlace{
.pane = 0,
.serial = 41,
.native = .{ .revision = 3 },
.x = 0,
.y = 0,
.w = 1,
.h = 1,
.rgba = &.{ 0, 0, 0, 255 },
.iw = 1,
.ih = 1,
};
const key = place.cacheKey();
place.native.fit = .width;
place.native.pan_x = 1234;
place.native.pan_y = 65535;
try std.testing.expect(key.eql(place.cacheKey()));
}
/// The canonical interface: what a frame of pardes IS. The tty shell writes
/// these cells to vaxis one-to-one; the SDL shells rasterize them.
pub const Surface = struct {
cols: u16 = 0,
rows: u16 = 0,
cells: []Cell = &.{},
/// bar: draw an insert-style thin cursor instead of the block
cursor: ?struct { x: u16, y: u16, bar: bool = false } = null,
/// Pixel attachments are the exact visible set. PDFs can legally contain
/// arbitrarily short pages, so no fixed page-count array can represent a
/// viewport without occasionally dropping an intersecting page.
images: []?ImagePlace = &.{},
nimages: usize = 0,
pub fn at(s: *Surface, x: u16, y: u16) *Cell {
std.debug.assert(x < s.cols and y < s.rows);
return &s.cells[@as(usize, y) * s.cols + x];
}
fn set(s: *Surface, x: u16, y: u16, text: []const u8, style: CellStyle) void {
const c = s.at(x, y);
std.debug.assert(text.len <= c.text.len);
@memcpy(c.text[0..text.len], text);
c.len = @intCast(text.len);
c.style = style;
c.default = false;
}
/// Print UTF-8 text into a row, no wrap, clipped to [x, x+w). Returns the
/// column after the last written cell. Wide glyphs take two cells.
///
/// The text is NOT trusted to be valid UTF-8 — a file pane holds whatever
/// bytes are on disk (latin-1 source, an ELF opened by mistake), a path can
/// be any bytes at all, and a search row splices both. std's unchecked
/// iterator panics on a bad start byte, so decode by hand and paint one
/// U+FFFD per undecodable byte (what a terminal does).
fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 {
var col = x;
const end = x + w;
var i: usize = 0;
while (i < text.len) {
if (col >= end) break;
// n == 0: not a start byte at all. A short tail or a bad
// continuation decodes to null the same way — one U+FFFD, one byte.
const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0;
const decoded: ?u21 = if (n > 0 and i + n <= text.len)
(std.unicode.utf8Decode(text[i .. i + n]) catch null)
else
null;
const cp_slice = if (decoded == null) "\u{FFFD}" else text[i .. i + n];
i += if (decoded == null) 1 else n;
const cp = decoded orelse 0xFFFD;
if (cp == '\r') continue;
const width: u16 = if (cp < 0x80) 1 else uucode.get(.width, cp);
if (width == 0) continue;
s.set(col, y, cp_slice, style);
if (width == 2 and col + 1 < end) {
// spacer: empty cell under the wide glyph's tail
s.set(col + 1, y, "", style);
}
col += width;
}
return col;
}
fn fill(s: *Surface, x: u16, y: u16, w: u16, h: u16, style: CellStyle) void {
var yy = y;
while (yy < y + h) : (yy += 1) {
var xx = x;
while (xx < x + w) : (xx += 1) s.set(xx, yy, " ", style);
}
}
fn clearRect(s: *Surface, x: u16, y: u16, w: u16, h: u16) void {
var yy = y;
while (yy < y + h) : (yy += 1) {
var xx = x;
while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{};
}
}
/// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint
fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void {
const c = s.at(x, y);
@memcpy(c.text[0..glyph.len], glyph);
c.len = @intCast(glyph.len);
c.default = false;
}
};
pub const Mouse = struct {
// sel indexing relies on left/middle/right being 0/1/2
pub const Button = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right, none };
pub const Kind = enum { press, release, motion, drag };
button: Button,
kind: Kind,
col: u16,
row: u16,
/// Ctrl held during the click. Only the left press reads it (ctrl-click =
/// goto-definition, the one chord every editor with an LSP has); every
/// other button ignores it, because acme's button semantics are already
/// the vocabulary here and modifiers are not part of it.
ctrl: bool = false,
};
pub const Key = struct {
cp: u21, // codepoint or one of the specials below
text: []const u8 = "",
ctrl: bool = false,
alt: bool = false,
/// Only consulted for keys whose codepoint does NOT already carry the
/// shift (Escape and friends) — `A` is `A`, not shift-`a`, so `hit()`
/// ignores this field unless a binding explicitly asks for it.
shift: bool = false,
pub const enter: u21 = 0x0D;
pub const escape: u21 = 0x1B;
pub const tab: u21 = 0x09;
pub const backspace: u21 = 0x7F;
// private-use plane for non-text keys, matching no real codepoint
pub const up: u21 = 0xF0001;
pub const down: u21 = 0xF0002;
pub const left: u21 = 0xF0003;
pub const right: u21 = 0xF0004;
pub const home: u21 = 0xF0005;
pub const end: u21 = 0xF0006;
pub const page_up: u21 = 0xF0007;
pub const page_down: u21 = 0xF0008;
pub const delete: u21 = 0xF0009;
};
/// Does this press match a binding? Every keymap test in the core goes through
/// here, so the modifier rules are written once instead of once per modifier
/// (the three is/isC/isA predicates this replaces each spelled out the same
/// comparison with a different pair of negations).
///
/// A binding is a LIST: most have two spellings that must reach the same arm —
/// `h` and Left, `Ctrl-f` and PageDown — and the `or` chain that used to do
/// that at every call site is now one loop here.
fn hit(key: Key, binding: []const config.Chord) bool {
for (binding) |c| {
if (key.cp != c.cp or key.ctrl != c.ctrl or key.alt != c.alt) continue;
// shift is carried in the codepoint for anything printable (`A` is
// `A`, not shift-`a`), so it is consulted ONLY when a binding asks for
// it — otherwise every letter binding would newly demand shift be up
if (c.shift and !key.shift) continue;
return true;
}
return false;
}
/// `Pane.sel` is indexed by @intFromEnum(button), so this is the SELECT
/// button's slot: where a sweep lands and where the left half of every acme
/// chord reads its selection from. Named rather than the bare 0 it used to be
/// so that config.select_button is genuinely the only place the choice is
/// made.
const sel_slot = @intFromEnum(config.select_button);
/// The same test for a MODAL PREFIX (`g`, `z`, `m`, `mi`, `]`...). config
/// spells those as bare codepoints rather than Chords because pardes stores
/// the codepoint itself in pane.pending until the next key completes the
/// sequence — so this is the one place the two shapes meet, and it is the same
/// comparison the stored byte gets a few lines later.
fn isPrefix(key: Key, cp: u21) bool {
return key.cp == cp and !key.ctrl and !key.alt;
}
/// The single physical-key -> BODY-NORMAL vocabulary seam. A key may carry
/// several roles (`h` is both move-left and `gh`'s line-start); the pure
/// normal_input parser chooses among them from its explicit prefix state.
/// Both text panes and PDF panes call this exact function before adapting the
/// resulting semantic Action.
fn normalInput(key: Key) normal_input.Input {
var out: normal_input.Input = .{
.cp = key.cp,
.ctrl = key.ctrl,
.alt = key.alt,
};
const roles = &out.roles;
if (hit(key, config.escape)) roles.insert(.escape);
if (isPrefix(key, config.goto_prefix)) roles.insert(.prefix_goto);
if (isPrefix(key, config.view_prefix)) roles.insert(.prefix_view);
if (isPrefix(key, config.match_prefix)) roles.insert(.prefix_match);
if (isPrefix(key, config.find_char_fwd)) roles.insert(.prefix_find_fwd);
if (isPrefix(key, config.find_char_back)) roles.insert(.prefix_find_back);
if (isPrefix(key, config.till_char_fwd)) roles.insert(.prefix_till_fwd);
if (isPrefix(key, config.till_char_back)) roles.insert(.prefix_till_back);
if (isPrefix(key, config.replace_prefix)) roles.insert(.prefix_replace);
if (isPrefix(key, config.next_prefix)) roles.insert(.prefix_next);
if (isPrefix(key, config.prev_prefix)) roles.insert(.prefix_prev);
if (hit(key, config.goto_file_start)) roles.insert(.goto_file_start);
if (hit(key, config.goto_last_line)) roles.insert(.goto_last_line);
if (hit(key, config.goto_line_start)) roles.insert(.goto_line_start);
if (hit(key, config.goto_line_end)) roles.insert(.goto_line_end);
if (hit(key, config.goto_first_nonws)) roles.insert(.goto_first_nonws);
if (hit(key, config.goto_line_down)) roles.insert(.goto_line_down);
if (hit(key, config.goto_line_up)) roles.insert(.goto_line_up);
if (hit(key, config.goto_column)) roles.insert(.goto_column);
if (hit(key, config.goto_view_top)) roles.insert(.goto_view_top);
if (hit(key, config.goto_view_center)) roles.insert(.goto_view_center);
if (hit(key, config.goto_view_bottom)) roles.insert(.goto_view_bottom);
if (hit(key, config.goto_definition)) roles.insert(.goto_definition);
if (hit(key, config.goto_declaration)) roles.insert(.goto_declaration);
if (hit(key, config.goto_type_definition)) roles.insert(.goto_type_definition);
if (hit(key, config.goto_implementation)) roles.insert(.goto_implementation);
if (hit(key, config.goto_references)) roles.insert(.goto_references);
if (hit(key, config.view_top)) roles.insert(.view_top);
if (hit(key, config.view_center)) roles.insert(.view_center);
if (hit(key, config.view_bottom)) roles.insert(.view_bottom);
if (hit(key, config.view_scroll_down)) roles.insert(.view_scroll_down);
if (hit(key, config.view_scroll_up)) roles.insert(.view_scroll_up);
if (isPrefix(key, config.match_inside)) roles.insert(.match_inside);
if (isPrefix(key, config.match_around)) roles.insert(.match_around);
if (isPrefix(key, config.surround_add)) roles.insert(.surround_add);
if (isPrefix(key, config.surround_replace)) roles.insert(.surround_replace);
if (isPrefix(key, config.surround_delete)) roles.insert(.surround_delete);
if (hit(key, config.goto_paragraph)) roles.insert(.goto_paragraph);
if (hit(key, config.add_newline)) roles.insert(.add_newline);
if (hit(key, config.goto_diagnostic)) roles.insert(.goto_diagnostic);
if (hit(key, config.goto_diagnostic_end)) roles.insert(.goto_diagnostic_end);
if (hit(key, config.move_left)) roles.insert(.move_left);
if (hit(key, config.move_right)) roles.insert(.move_right);
if (hit(key, config.move_down)) roles.insert(.move_down);
if (hit(key, config.move_up)) roles.insert(.move_up);
if (hit(key, config.next_word_start)) roles.insert(.next_word_start);
if (hit(key, config.prev_word_start)) roles.insert(.prev_word_start);
if (hit(key, config.next_word_end)) roles.insert(.next_word_end);
if (hit(key, config.next_long_word_start)) roles.insert(.next_long_word_start);
if (hit(key, config.prev_long_word_start)) roles.insert(.prev_long_word_start);
if (hit(key, config.next_long_word_end)) roles.insert(.next_long_word_end);
if (hit(key, config.repeat_find)) roles.insert(.repeat_find);
if (hit(key, config.line_start)) roles.insert(.line_start);
if (hit(key, config.line_end)) roles.insert(.line_end);
if (hit(key, config.line_first_nonws)) roles.insert(.line_first_nonws);
if (hit(key, config.goto_line)) roles.insert(.goto_line);
if (hit(key, config.half_page_down)) roles.insert(.half_page_down);
if (hit(key, config.half_page_up)) roles.insert(.half_page_up);
if (hit(key, config.page_down)) roles.insert(.page_down);
if (hit(key, config.page_up)) roles.insert(.page_up);
if (hit(key, config.insert)) roles.insert(.insert);
if (hit(key, config.append)) roles.insert(.append);
if (hit(key, config.insert_line_start)) roles.insert(.insert_line_start);
if (hit(key, config.insert_line_end)) roles.insert(.insert_line_end);
if (hit(key, config.open_below)) roles.insert(.open_below);
if (hit(key, config.open_above)) roles.insert(.open_above);
if (hit(key, config.select_mode)) roles.insert(.select_mode);
if (hit(key, config.select_line)) roles.insert(.select_line);
if (hit(key, config.select_line_bounds)) roles.insert(.select_line_bounds);
if (hit(key, config.shrink_to_line_bounds)) roles.insert(.shrink_to_line_bounds);
if (hit(key, config.collapse_selection)) roles.insert(.collapse_selection);
if (hit(key, config.flip_selection)) roles.insert(.flip_selection);
if (hit(key, config.select_all)) roles.insert(.select_all);
if (hit(key, config.copy_sel_below)) roles.insert(.copy_sel_below);
if (hit(key, config.copy_sel_above)) roles.insert(.copy_sel_above);
if (hit(key, config.keep_primary_sel)) roles.insert(.keep_primary_sel);
if (hit(key, config.remove_primary_sel)) roles.insert(.remove_primary_sel);
if (hit(key, config.rotate_sel_fwd)) roles.insert(.rotate_sel_fwd);
if (hit(key, config.rotate_sel_back)) roles.insert(.rotate_sel_back);
if (hit(key, config.split_sel_newline)) roles.insert(.split_sel_newline);
if (hit(key, config.merge_sels)) roles.insert(.merge_sels);
if (hit(key, config.merge_consecutive_sels)) roles.insert(.merge_consecutive_sels);
if (hit(key, config.trim_sels)) roles.insert(.trim_sels);
if (hit(key, config.select_regex)) roles.insert(.select_regex);
if (hit(key, config.split_regex)) roles.insert(.split_regex);
if (hit(key, config.delete)) roles.insert(.delete);
if (hit(key, config.delete_noyank)) roles.insert(.delete_noyank);
if (hit(key, config.change)) roles.insert(.change);
if (hit(key, config.yank)) roles.insert(.yank);
if (hit(key, config.replace_with_yank)) roles.insert(.replace_with_yank);
if (hit(key, config.paste_after)) roles.insert(.paste_after);
if (hit(key, config.paste_before)) roles.insert(.paste_before);
if (hit(key, config.switch_case)) roles.insert(.switch_case);
if (hit(key, config.to_lowercase)) roles.insert(.to_lowercase);
if (hit(key, config.to_uppercase)) roles.insert(.to_uppercase);
if (hit(key, config.join_lines)) roles.insert(.join_lines);
if (hit(key, config.indent)) roles.insert(.indent);
if (hit(key, config.unindent)) roles.insert(.unindent);
if (hit(key, config.format)) roles.insert(.format);
if (hit(key, config.increment)) roles.insert(.increment);
if (hit(key, config.decrement)) roles.insert(.decrement);
if (hit(key, config.comment_toggle)) roles.insert(.comment_toggle);
if (hit(key, config.undo)) roles.insert(.undo);
if (hit(key, config.redo)) roles.insert(.redo);
if (hit(key, config.leader)) roles.insert(.leader);
if (hit(key, config.command_line)) roles.insert(.command_line);
if (hit(key, config.pipe_selection)) roles.insert(.pipe_selection);
if (hit(key, config.search)) roles.insert(.search);
if (hit(key, config.search_next)) roles.insert(.search_next);
if (hit(key, config.search_prev)) roles.insert(.search_prev);
return out;
}
/// Pixel dimensions are meaningful only to the native PDF placement path.
/// Keep resize events layout-only when that path is not part of the build.
pub const CellPixels = if (pdf_enabled) struct {
w: u16 = 8,
h: u16 = 16,
} else struct {};
pub const Event = union(enum) {
key: Key,
mouse: Mouse,
resize: struct {
cols: u16,
rows: u16,
/// Physical pixels in one grid cell, present only when native PDF
/// placement is compiled in. Defaults keep headless/core callers
/// useful and give terminals which cannot report pixels the
/// conventional 1:2 cell aspect.
cell_pixels: CellPixels = .{},
},
output: struct { pane: u8, bytes: []const u8 },
eof: struct { pane: u8 },
/// a language query the shell ran on a worker has finished. `rows` is
/// `+Search`-format text (see lsp.zig) and is borrowed for this call only,
/// exactly like `output` bytes. An id the core no longer recognises is a
/// stale answer (the pane was closed, or a newer query superseded it) and
/// is dropped.
lsp_resp: struct { id: u32, rows: []const u8 },
/// A selection-pipe worker finished. Every output is borrowed for this
/// update only; success is atomic, so a failed/nonzero invocation carries
/// no usable outputs and changes nothing.
pipe_resp: struct { id: u32, success: bool, outputs: []const []const u8 },
/// a file the shell was asked to watch changed on disk; `bytes` are its
/// new contents, borrowed for this call exactly like `output`. A shell
/// with no filesystem (the browser) or no watcher simply never sends one —
/// nothing in the core waits for it.
file_changed: struct { pane: u8, bytes: []const u8 },
paste: []const u8,
/// Native shells may preserve sub-cell wheel distance in physical pixels.
/// TTY button events still enter through the ordinary mouse path.
pdf_scroll: struct { pane: u8, delta_pixels: f32 },
pinch: f32,
touch_scroll: f32,
tick,
};
/// IO the core wants done. Payloads are inline (fixed buffers): effects are
/// queued values with no lifetime ties back into the core.
pub const Effect = union(enum) {
spawn: struct { pane: u8, cwd: Buf(256) },
write: struct { pane: u8, bytes: Buf(64) },
resize_pty: struct { pane: u8, cols: u16, rows: u16 },
open_link: Buf(256),
/// write this pane's file content to its path; the shell reads both off
/// the core (content is unbounded, effects are fixed-size values)
save_file: struct { pane: u8 },
/// Create an empty, uniquely-named temporary file. `pane` + `serial`
/// identify the pane/column that issued New even if focus moves before the
/// shell completes the IO. The shell calls openNewFile with the path and
/// unlinks it itself when that completion rejects the request.
new_file: struct { pane: u8, serial: u32 },
/// a serialized state dump is ready in core.dump_out; write it to the
/// path dump.outPath resolves (acme-style: another instance loads it
/// with -l, or the Restore builtin loads it into this one)
write_dump,
/// the yank register changed; the shell reads it off the core (OSC 52 out)
set_clipboard,
/// answer a language query OFF the event loop and post the rows back as an
/// `lsp_resp` Event. The shell reads the file's path and content off the
/// core (like save_file) and must SNAPSHOT them before the worker starts —
/// the core keeps editing while this is in flight.
lsp: struct { id: u32, kind: lsp.Kind, pane: u8, offset: u32, arg: Buf(128) },
/// Snapshot the matching request with pipeRequest(id), then run it away
/// from the UI/event loop and answer with pipe_resp.
pipe: struct { id: u32 },
/// start (`on`) or stop watching this pane's file on disk. Starting, the
/// shell reads the path off the core exactly like save_file does; stopping
/// carries nothing, because by the time an `off` is drained the pane is
/// already freed — the shell remembers what it watches per pane id.
/// Only real files ask for this: an output buffer has no file behind it.
watch: struct { pane: u8, on: bool },
quit,
fn Buf(comptime n: usize) type {
return struct {
data: [n]u8 = undefined,
len: u16 = 0,
pub fn slice(b: *const @This()) []const u8 {
return b.data[0..b.len];
}
fn from(text: []const u8) @This() {
var b: @This() = .{};
std.debug.assert(text.len <= n);
@memcpy(b.data[0..text.len], text);
b.len = @intCast(text.len);
return b;
}
};
}
};
pub const Mode = enum { normal, insert, tty };
/// A terminal's edit buffer: real gpa-owned text standing in for the `rows`
/// shell rows starting at ABSOLUTE body row `row`. It is edited by exactly
/// the machinery File.content is — that is the whole point, a terminal in
/// insert mode has to behave like a text file — and it rides the scrollback
/// the way the char-mode insertion runs it replaced did. The vt grid itself
/// is never written, so output keeps streaming underneath.
///
/// Seeded from the rows it stands in for the first time you type, and grown
/// whenever an edit reaches past either end (absorbing the shell rows it
/// swallows). When it ends up holding MORE lines than the rows it covers —
/// which is what pressing Enter does — the surface below simply slides down
/// by the difference: see Pane.surfRow.
pub const Ovl = struct {
row: i32 = 0,
rows: i32 = 1,
text: []u8 = &.{},
};
/// One mouse selection (block-shaped), per button. c/r are text-area relative;
/// r counts from the tag row (body starts at BOX_H).
pub const Sel = struct {
state: enum { none, dragging, done } = .none,
c0: i32 = 0,
c1: i32 = 0,
r0: i32 = 0,
r1: i32 = 0,
};
/// A modal line selection (helix `x`): whole rows [r0, r1], absolute.
pub const LineSel = struct {
active: bool = false,
r0: i32 = 0,
r1: i32 = 0,
};
/// A modal char-range selection: the anchor lives here, the head is the pane
/// cursor. Since the helix motion model landed, EVERY motion leaves one of
/// these — `explicit` separates user-intent selections (v / x / X / terminal
/// n/N / file-search n/N) from bare motion residue: the acme Enter/Tab chords
/// only act on explicit ones. Mutually exclusive with LineSel.
pub const CharSel = struct {
active: bool = false,
row: i32 = 0,
col: i32 = 0,
explicit: bool = false,
};
/// ponytail: at most this many cursors at once. helix's `Selection.ranges` is
/// an unbounded Vec; a fixed array keeps a Pane trivially copyable (the undo
/// snapshots memcpy it) and costs nothing at one cursor. The ceiling only
/// bites on `C`/`Alt-s` over a very long selection, where the extra ranges are
/// simply not created — raise the number, or swap in an ArrayList, if that
/// ever matters.
pub const MAX_SELS = 64;
/// One selection range in PANE coordinates: the block-cursor cell and the
/// anchor cell. Deliberately the same pair `cur_row`/`cur_col` + `vsel`
/// already are, so a range moves in and out of the primary slot without a
/// conversion.
pub const SelRange = struct {
row: i32,
col: i32,
arow: i32,
acol: i32,
/// this range's own j/k goal column (helix Range::old_visual_position);
/// the PRIMARY's copy is Pane.sticky_col
sticky: i32 = -1,
};
/// Undo snapshot of a terminal pane's edit buffer (whole-state, dumb on
/// purpose). `ovl` is null for a pane nothing has been typed into yet, and
/// owns its text exactly like FileSnap does.
pub const EditSnap = struct {
ovl: ?Ovl,
cur_row: i32,
cur_col: i32,
vsel: CharSel,
};
/// Undo snapshot of a file pane: content + the selection at commit time —
/// helix undo restores the selection along with the text.
/// ponytail: the PRIMARY selection only. With multiple cursors an undo puts
/// the primary back and leaves the others where they are — which is right
/// whenever the undone edit is the one they made (the common case, and what
/// the msel-undo differential case pins), and merely misplaced otherwise.
/// Storing the whole list would put MAX_SELS ranges in every one of the 256
/// snapshots a pane keeps, for a case nobody has complained about.
pub const FileSnap = struct {
content: []u8,
cur_row: i32,
cur_col: i32,
vsel: CharSel,
};
/// A file pane's backing: content is gpa-owned; undo/redo are whole snapshots.
pub const File = struct {
path: []u8,
content: []u8,
/// Monotonic content identity for asynchronous edits. Every content swap
/// goes through file_pane.setContent, which bumps this; a pipe completion
/// accepted against another revision would overwrite intervening work.
revision: u32 = 0,
/// set = this is an OUTPUT buffer (acme's +Errors): a file pane with no
/// file behind it, showing text the core produced itself. It records the
/// COMMAND that opened it, and output_pane.zig's one table turns that into
/// every way it differs from a file — ask it, never this field's shape.
/// `path` still names it (and gives its directory) so looks inside it
/// resolve like anywhere else.
output: ?output_pane.Output = null,
scroll: usize = 0,
/// THE LINE INDEX: `line_starts[i]` is the byte offset where line i begins,
/// and `line_starts.len` IS the line count. Empty means "not built yet" —
/// a real index always holds at least one entry, because a file always has
/// at least one line. Built and read only through file_pane.lineIndex /
/// nlines / lineStart; see the invalidation contract on lineIndex.
line_starts: []usize = &.{},
/// one syntax.Syn byte per content byte in the highlighted window
highlights: []u8 = &.{},
highlight_start: usize = 0,
syntax_dirty: bool = true,
undo: std.ArrayList(FileSnap) = .empty,
redo: std.ArrayList(FileSnap) = .empty,
};
/// An image pane's backing: the decoded+downscaled RGBA (kept so the petscii
/// grid can re-render on resize/toggle) and the cached glyph grid.
pub const Image = struct {
path: []u8,
petscii: bool = false,
pmode: image.PaletteMode = .commodore,
ascii: bool = true,
tried: bool = false, // decode attempted — exactly once
rgba: []u8 = &.{},
iw: usize = 0,
ih: usize = 0,
/// dump-loaded image bytes (gpa-owned), decoded lazily like a file read
raw: []u8 = &.{},
grid: []image.petscii.Cell = &.{},
gw: usize = 0,
gh: usize = 0,
grid_w: u16 = 0,
grid_h: u16 = 0,
grid_mode: image.PaletteMode = .commodore,
grid_ascii: bool = true,
};
const PdfPoint = if (pdf_enabled) pdf_impl.Point else void;
const PdfHighlight = if (pdf_enabled) pdf_impl.Highlight else void;
const PdfRaster = if (pdf_enabled) struct {
valid: bool = false,
page: usize = 0,
rgba: []u8 = &.{},
iw: usize = 0,
ih: usize = 0,
request: pdf_impl.RenderRequest = .{},
request_valid: bool = false,
tried: bool = false,
decorated: bool = false,
tint_key: ?PdfTintKey = null,
revision: u32 = 0,
} else void;
const PdfSectionsOutput = if (pdf_enabled) struct {
pane: usize,
serial: u32,
/// The generated revision. A mismatch means the user edited the output;
/// reopening must not overwrite it, so a fresh output is opened instead.
revision: u32,
} else void;
/// A PDF pane is compiled out as a zero-bit `void` field when MuPDF is off.
/// With it enabled, the pane owns one live document, one lazy current-page
/// raster for SDL/Kitty, and one lazy text projection for non-pixel hosts and
/// normal Pardes search semantics.
const PdfView = if (pdf_enabled) struct {
path: []u8,
document: pdf_impl.Document,
page: usize = 0,
page_count: usize,
page_sizes: []pdf_impl.PageSize,
/// Pixel-space layout is recomputed only when fit or physical viewport
/// changes. These tiny arrays replace any all-document raster.
page_starts: []u64,
page_heights: []u32,
document_height: u64 = 0,
layout_viewport_w: u32 = 0,
layout_viewport_h: u32 = 0,
layout_fit: PdfFitMode = .width,
layout_valid: bool = false,
/// Top of the viewport in document display pixels. f64 preserves SDL's
/// fractional wheel distance while page starts/heights remain integral.
document_scroll_y: f64 = 0,
scroll_to_page_pending: bool = true,
/// Exactly the visible pages. Entries are removed (and RGBA freed) the
/// frame a page leaves the viewport, so pixel memory is viewport-bounded
/// even for documents with pathological page dimensions.
rasters: std.ArrayList(PdfRaster) = .empty,
/// A physical viewport change rebuilds page heights. Preserve the same
/// page-relative reading position instead of reinterpreting old pixels or
/// snapping to the active page's top.
layout_anchor_pending: bool = false,
layout_anchor_page: usize = 0,
layout_anchor_fraction: f64 = 0,
next_raster_revision: u32 = 0,
fit: PdfFitMode = .width,
tint: PdfTintMode = .filtered,
/// Normalized 0..65535 pan positions. NativeGeometry maps the extrema
/// exactly onto the source overflow, independent of page or cell size.
pan_x: u16 = 0,
pan_y: u16 = 0,
rgba: []u8 = &.{},
/// Search/selection geometry changed without changing fit or pan. The next
/// draw transactionally regenerates this one RGBA buffer with MuPDF's baked
/// highlights; a second full-page buffer is never retained after the swap.
highlights_dirty: bool = false,
search_reveal_pending: bool = false,
search_results: ?pdf_impl.SearchResults = null,
selection: ?pdf_impl.Selection = null,
selection_text: []u8 = &.{},
selection_anchor: ?pdf_impl.Point = null,
selection_head: ?pdf_impl.Point = null,
drag_anchor: ?pdf_impl.Point = null,
drag_head: ?pdf_impl.Point = null,
iw: usize = 0,
ih: usize = 0,
render_tried: bool = false,
/// Last quality request attempted, successful or not. A viewport change
/// gets one transactional retry; a capped/failed request does not spin on
/// every frame. Fit and pan are intentionally absent from this key.
render_request: pdf_impl.RenderRequest = .{},
render_request_valid: bool = false,
render_revision: u32 = 0,
text: []u8 = &.{},
text_tried: bool = false,
text_scroll: usize = 0,
/// Full, untruncated PDF query. +Search records only a display/Look copy;
/// this survives page navigation while page-local quads are rebuilt.
search_query: []u8 = &.{},
/// Zero-based logical MuPDF hit on the current page. Result rows encode
/// this as Spot.col + 1, letting same-page occurrences reveal distinctly.
search_hit: usize = 0,
/// Last viewport for which search_hit was revealed. Comparing this at
/// draw time covers layout/border changes without treating every frame
/// (or a manual pan) as a reason to snap back to the hit.
reveal_viewport_w: u32 = 0,
reveal_viewport_h: u32 = 0,
reveal_fit: PdfFitMode = .width,
reveal_viewport_valid: bool = false,
/// Loaded once on first PdfSections. An empty outline is still a loaded
/// outline; `outline_tried` distinguishes it from the lazy initial state
/// and makes backend failures repeatably inert instead of retrying every
/// command invocation.
outline: ?pdf_impl.Outline = null,
outline_tried: bool = false,
sections_output: ?PdfSectionsOutput = null,
/// Page-space outline coordinates survive a pane split/layout rebuild.
/// ensurePdfLayout consumes them without invalidating any page pixels.
outline_reveal_pending: ?pdf_impl.OutlineInternalDestination = null,
} else void;
/// Pure outline-to-row policy. Keeping destination resolution and title
/// sanitisation together makes the ordinal written into a row exactly the
/// ordinal Look later resolves; neither path invents a second flattened tree.
pub const PdfSectionRows = if (pdf_enabled) struct {
pub fn usableDestination(destination: pdf_impl.OutlineDestination) ?pdf_impl.OutlineDestination {
return switch (destination) {
.internal => destination,
.external => |uri| if (safeHttpUri(uri)) destination else null,
.none => null,
};
}
fn safeHttpUri(uri: []const u8) bool {
// Effect.open_link is inline and cannot carry a larger URL. Omitting
// it here is preferable to rendering a row which can never act.
if (uri.len > 256) return false;
var has_scheme = false;
for (config.url_schemes) |scheme| {
if (std.mem.startsWith(u8, uri, scheme)) {
has_scheme = true;
break;
}
}
if (!has_scheme) return false;
for (uri) |byte| if (byte <= 0x20 or byte == 0x7f) return false;
return true;
}
/// A structural node goes to the first later DFS entry still below it
/// which carries a usable destination. Nodes with their own unusable URI
/// are not structural: omit them instead of silently changing their link.
pub fn resolve(entries: []const pdf_impl.OutlineEntry, ordinal: usize) ?pdf_impl.OutlineDestination {
if (ordinal >= entries.len) return null;
const entry = entries[ordinal];
if (entry.destination != .none) return usableDestination(entry.destination);
var i = ordinal + 1;
while (i < entries.len and entries[i].depth > entry.depth) : (i += 1)
if (usableDestination(entries[i].destination)) |destination| return destination;
return null;
}
/// Resolve every rendered row in one DFS pass. `resolve` above stays the
/// public single-ordinal policy used by Look; bulk materialisation avoids
/// rescanning the same descendant chain for every structural ancestor.
/// The one-usize-per-entry table is transient (64 KiB at MuPDF's 8192
/// outline-item limit) and stores source ordinals, so URI slices continue
/// to borrow from the document-owned outline instead of being copied.
fn resolveOrdinals(
gpa: std.mem.Allocator,
entries: []const pdf_impl.OutlineEntry,
) ![]usize {
const unresolved = std.math.maxInt(usize);
const ordinals = try gpa.alloc(usize, entries.len);
@memset(ordinals, unresolved);
const Pending = struct { depth: u8, ordinal: usize };
// OutlineEntry.depth is u8. A valid DFS path therefore cannot hold
// more than 256 simultaneously unresolved ancestors, independent of
// the tighter limit enforced by the MuPDF bridge.
var pending: [256]Pending = undefined;
var pending_len: usize = 0;
for (entries, 0..) |entry, ordinal| {
while (pending_len > 0 and pending[pending_len - 1].depth >= entry.depth)
pending_len -= 1;
if (usableDestination(entry.destination) != null) {
ordinals[ordinal] = ordinal;
for (pending[0..pending_len]) |ancestor|
ordinals[ancestor.ordinal] = ordinal;
pending_len = 0;
} else if (entry.destination == .none) {
pending[pending_len] = .{ .depth = entry.depth, .ordinal = ordinal };
pending_len += 1;
}
}
return ordinals;
}
fn appendTitle(
out: *std.ArrayList(u8),
gpa: std.mem.Allocator,
title: ?[]const u8,
) !void {
const raw = title orelse {
try out.appendSlice(gpa, "[untitled]");
return;
};
var i: usize = 0;
var wrote = false;
var pending_space = false;
while (i < raw.len) {
const n: usize = std.unicode.utf8ByteSequenceLength(raw[i]) catch {
pending_space = wrote;
i += 1;
continue;
};
if (i + n > raw.len) {
pending_space = wrote;
break;
}
const cp = std.unicode.utf8Decode(raw[i .. i + n]) catch {
pending_space = wrote;
i += n;
continue;
};
const whitespace_or_control = cp <= 0x20 or cp == 0x7f or
(cp >= 0x80 and cp <= 0x9f) or cp == 0x2028 or cp == 0x2029;
if (whitespace_or_control) {
pending_space = wrote;
} else {
if (pending_space) try out.append(gpa, ' ');
try out.appendSlice(gpa, raw[i .. i + n]);
wrote = true;
pending_space = false;
}
i += n;
}
if (!wrote) try out.appendSlice(gpa, "[empty title]");
}
pub fn render(
gpa: std.mem.Allocator,
path: []const u8,
entries: []const pdf_impl.OutlineEntry,
) ![]u8 {
// The output pane's directory is the PDF's directory, so a basename
// resolves to the same document while leaving room for the actual
// chapter title. An absolute prefix can consume the entire picker.
const target = std.fs.path.basename(path);
const ordinals = try resolveOrdinals(gpa, entries);
defer gpa.free(ordinals);
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
for (entries, 0..) |entry, ordinal| {
const resolved = ordinals[ordinal];
if (resolved == std.math.maxInt(usize)) continue;
const destination = usableDestination(entries[resolved].destination) orelse unreachable;
switch (destination) {
.internal => |internal| try out.print(gpa, "{s}:{d}:{d} ", .{
target,
internal.page + 1,
ordinal + 1,
}),
.external => |uri| try out.print(gpa, "{s} ", .{uri}),
.none => unreachable,
}
try out.appendNTimes(gpa, ' ', @as(usize, entry.depth) * 2);
try appendTitle(&out, gpa, entry.title);
try out.append(gpa, '\n');
}
return out.toOwnedSlice(gpa);
}
} else struct {};
const PdfSlot = if (pdf_enabled) ?PdfView else void;
fn hasPdf(pane: *const Pane) bool {
return if (comptime pdf_enabled) pane.pdf != null else false;
}
fn hasPdfSelection(pane: *const Pane) bool {
return if (comptime pdf_enabled)
if (pane.pdf) |pv| pv.selection != null and pv.selection_text.len > 0 else false
else
false;
}
test "feature-off PDF pane state is zero-sized" {
if (!pdf_enabled) try std.testing.expectEqual(@as(usize, 0), @sizeOf(PdfSlot));
}
pub const Pane = struct {
vt: ghostty_vt.Terminal,
stream: ghostty_vt.TerminalStream,
/// The same allocator Pardes holds. A pane already owns heap (its content,
/// its emulator, its undo stacks) and Pardes frees all of it; this is here
/// so the pane methods that need the file's LINE INDEX — scrollBy,
/// ensureCursorVisible, lastNavRow — can build it. The alternative was
/// threading an allocator through ensureCursorVisible's 33 call sites.
gpa: std.mem.Allocator,
/// WHICH pane this is, for anything that outlives the pane: slots are
/// REUSED (freeSlot hands back the lowest free one), so a remembered id
/// alone can silently come to mean an unrelated pane. Handed out by
/// Pardes.next_serial and never reused. The one reader is the jump stack.
serial: u32 = 0,
mode: Mode = .normal,
vweight: f32 = 1,
cols: u16,
rows: u16,
greet: bool = false,
file: ?File = null,
image: ?Image = null,
pdf: PdfSlot = if (pdf_enabled) null else {},
msel: LineSel = .{},
vsel: CharSel = .{},
/// MULTIPLE CURSORS. helix's Selection is a list of ranges plus a primary
/// index; pardes keeps the PRIMARY exactly where it has always been —
/// cur_row/cur_col + vsel — and the other ranges here, document-ordered
/// and disjoint (helix's Selection::normalize). That split is the whole
/// design: every motion, operator, renderer and mouse path in this file
/// still reads one selection, so with `nsel == 0` not a byte of behaviour
/// moves, and the 800 differential cases and 66 snapshots keep proving it.
/// The extra ranges are driven by replaying the single-selection key
/// handler once per range (see replaySels).
sels: [MAX_SELS - 1]SelRange = undefined,
nsel: u8 = 0,
/// helix select/extend mode (`v`): motions extend the selection from its
/// fixed anchor instead of replacing it. Reported as mode "select";
/// pane.mode stays .normal (insert/tty transitions drop it).
select: bool = false,
/// sticky goal column for j/k runs (helix old_visual_position): any
/// non-vertical range write resets it to -1.
sticky_col: i32 = -1,
/// an `a` append session's original block-cursor cell: Esc backs the
/// cursor up one grapheme and rebuilds the appended-over selection from
/// here (helix doc.restore_cursor). Null outside `a` sessions.
append_at: ?struct { row: i32, col: i32 } = null,
/// Compact storage for normal_input.State's match sub-prefix.
pending2: u21 = 0,
/// Compact storage for normal_input.State's `mr<from><to>` held char.
pending_ch: u21 = 0,
/// Compact storage for normal_input.State's count (0 = none).
count: u32 = 0,
/// last f/F/t/T motion, for Alt-. repeat
find_op: u8 = 0,
find_ch: u21 = 0,
/// Compact storage for normal_input.State's typed prefix.
pending: u21 = 0,
/// `/` search and the Find builtin: the pattern is typed into the tag tail
/// (no popup); search_at is the tail length before the marker was appended
/// (submit/cancel restore it, and the marker itself says WHICH search this
/// is). Enter fills the output buffer in pane search_pane with one result
/// per row; n/N walk it, search_row being the row they last landed on
/// (null = fresh results, nothing stepped to yet). WHICH command filled
/// that buffer is the BUFFER's own record, never a second field here —
/// output_pane.resultsFrom is how `]d` asks.
search_edit: bool = false,
search_at: u16 = 0,
/// `|` reuses the visible tag-tail input but submits a shell-filter
/// request rather than a search. pipe_at is a tail byte offset exactly
/// like search_at; Enter/Esc restore the tail to it.
pipe_edit: bool = false,
pipe_at: u16 = 0,
search_pane: ?usize = null,
search_row: ?usize = null,
/// The selection an `s`/`S` input was armed on, as gap offsets over the
/// motion surface. Every keystroke re-derives the preview FROM here rather
/// than from the previous preview — which is what helix's regex_prompt
/// does (it reverts to its snapshot before each update), what makes typing
/// a pattern one character at a time land on the same answer as pasting it
/// whole, and what makes Esc a plain restore with nothing else to undo.
/// `nsel_snap == 0` means no such input is armed; exitTagEdit, the one
/// place search_edit is ever cleared, clears it too.
sel_snap: [MAX_SELS]modal.HxRange = undefined,
nsel_snap: u8 = 0,
sel_snap_pri: u8 = 0,
/// ...including whether it was a user-intent selection: a preview IS one
/// (you picked those matches), but restoring must not silently promote
/// motion residue into something the acme chords will act on
sel_snap_expl: bool = false,
/// the editable tag tail: seeded with the default builtins on first touch;
/// edited in place by a modal one-line editor sharing the pane's mode
tag_tail: std.ArrayList(u8) = .empty,
tag_init: bool = false,
tag_edit: bool = false,
tag_sel: bool = false,
/// the body mode a tag edit hijacked (tags are always insert); terminals
/// restore it on exit so clicking the tag never changes the pane's mode
tag_mode: Mode = .normal,
/// THE tag coordinate space: byte columns into the WHOLE rendered tag,
/// prefix ++ tail (tagText). One space, no conversions — the renderer, the
/// mouse and every motion speak it directly. The prefix is live chrome, so
/// it is selectable/yankable/executable but READ-ONLY: every edit op
/// measures from `edit0` (= tagPrefix().len, the first editable column) and
/// does nothing left of it.
tag_col: u16 = 0,
tag_anchor: u16 = 0,
ed_undo: std.ArrayList(EditSnap) = .empty,
ed_redo: std.ArrayList(EditSnap) = .empty,
/// live working directory, shell-reported (setCwd); shown in the tag and
/// the base for look-resolution of relative paths.
cwd: [1024]u8 = undefined,
cwd_len: u16 = 0,
/// modal cursor, at ABSOLUTE body rows of the pane's SURFACE (file lines,
/// or the terminal's shell rows with its edit buffer standing in). Tracks
/// the shell cursor until pinned by a click or a key.
cur_pinned: bool = false,
cur_row: i32 = 0,
cur_col: i32 = 0,
/// horizontal scroll, file panes only (terminals wrap at pty width, they
/// never have wider lines): content columns hidden left of the gutter.
/// No scrollbar — the wheel and cursor movement (with scrolloff) drive it,
/// the goal is just being able to read long lines. Byte columns, like the
/// rest of the file-pane code.
hscroll: i32 = 0,
/// THE WRAP MAP, and the whole of what soft line breaks are: for every body
/// row of the LAST frame, the document line it showed and the byte column
/// of that line the row started at. `wrap_n == 0` says the body was NOT
/// wrapped, i.e. the rows are the lines from `scroll()` down one each —
/// which is exactly what wrapAt/wrapRow below fall back to, so with the
/// toggle off not one reader computes anything it did not compute before.
///
/// INVALIDATION, the part that rots if nobody says it out loud: written in
/// EXACTLY ONE PLACE, file_pane.bodyText, on every build of a file pane's
/// body. So it is at worst one frame old — which is what a mouse click
/// wants (you click the character you can SEE), and it is fresh for the
/// render passes, every one of which runs after bodyText inside the same
/// renderPane call. Nothing else may write it; a second writer is a second
/// truth, and the first click on a stale row is how you find out.
///
/// ponytail: a fixed 256 rows. A pane taller than that does not wrap at
/// all — bodyText leaves wrap_n at 0 and clips the way it always did —
/// rather than half-recording a mapping every site here would then have to
/// distrust. Grow the arrays the day a 256-row window turns up.
wrap_line: [256]i32 = undefined,
wrap_col: [256]i32 = undefined,
wrap_n: u16 = 0,
sel: [3]Sel = @splat(.{}),
/// terminals only: the typed-text buffer standing in for shell rows
ovl: ?Ovl = null,
/// every raw pty byte, in order — the dump/replay record.
tty_stream: std.ArrayList(u8) = .empty,
/// query replies ghostty computed (DSR, DA, kitty); the stream handler has
/// no path to the effect queue, so they land here and sync() drains them
/// into write effects. Bounded: replies are tiny escape sequences.
reply: [256]u8 = undefined,
reply_len: u16 = 0,
/// THE TRANSIENT MESSAGE: what just happened to this pane, drawn on its
/// LAST row until the next key or mouse event wipes it (see update). Fixed
/// and inline like `reply` above — a message is one short line, so a pane
/// that never sees one still costs nothing to carry it, and there is no
/// allocation to fail at the moment something is trying to be reported.
/// Written in exactly one place, Pardes.setMessage, by a SHELL.
msg: [256]u8 = undefined,
msg_len: u16 = 0,
pub fn cwdSlice(p: *const Pane) []const u8 {
return p.cwd[0..p.cwd_len];
}
pub fn isTerminal(pane: *const Pane) bool {
return pane.file == null and pane.image == null and !hasPdf(pane);
}
pub fn pdfPath(pane: *const Pane) ?[]const u8 {
if (comptime pdf_enabled) if (pane.pdf) |pv| return pv.path;
return null;
}
pub fn pdfPage(pane: *const Pane) ?usize {
if (comptime pdf_enabled) if (pane.pdf) |pv| return pv.page;
return null;
}
/// Surface row of shell row `g`. The edit buffer's lines stand in for the
/// `rows` shell rows it covers, so everything below it slides by the
/// difference — the identity on files and on terminals nobody has typed
/// a newline into, which is why the rest of the row math can stay naive.
pub fn surfRow(pane: *const Pane, g: i32) i32 {
const o = pane.ovl orelse return g;
if (g <= o.row) return g;
const lines: i32 = @intCast(modal.lineCount(o.text));
if (g >= o.row + o.rows) return g + lines - o.rows;
return @min(g, o.row + lines - 1); // inside the buffer: its own rows
}
/// the inverse; every surface row inside the edit buffer maps to its anchor
pub fn gridRow(pane: *const Pane, s: i32) i32 {
const o = pane.ovl orelse return s;
if (s <= o.row) return s;
const lines: i32 = @intCast(modal.lineCount(o.text));
if (s < o.row + lines) return o.row;
return s - lines + o.rows;
}
/// current scroll offset: file top line, or the scrollback offset
pub fn scroll(pane: *Pane) i32 {
if (pane.file) |f| return @intCast(f.scroll);
if (comptime pdf_enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll);
return pane.surfRow(@intCast(pane.vt.screens.active.pages.scrollbar().offset));
}
/// The document position a BODY ROW begins at — `vr` 0 is the first row
/// under the tag. The screen->document half of the wrap map, and the half
/// the mouse asks: a click lands on the character the user can see, which
/// is last frame's arrangement, which is what the map holds.
pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } {
if (pane.wrap_n > 0 and vr >= 0 and vr < @as(i32, pane.wrap_n))
return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)] };
// unwrapped: rows ARE lines, and the byte column a row starts at is the
// horizontal scroll (always 0 on a terminal, which never has one)
return .{ .line = pane.scroll() + vr, .at = pane.hscroll };
}
/// ...and back: the body row `line`:`col` renders on, plus the byte column
/// that row starts at — subtract it from a document column to get a screen
/// one. `row` is -1 when the position is not on screen, which only a
/// wrapped body ever says: unwrapped the arithmetic answers for any line at
/// all and the callers' own bounds checks do the rejecting, as before.
pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32 } {
if (pane.wrap_n == 0) return .{ .row = line - pane.scroll(), .at = pane.hscroll };
var i: u16 = 0;
while (i < pane.wrap_n) : (i += 1) {
if (pane.wrap_line[i] != line) continue;
// the LAST row of a line owns every column past its start, so a
// cursor parked on the trailing newline still has somewhere to draw
if (i + 1 < pane.wrap_n and pane.wrap_line[i + 1] == line and col >= pane.wrap_col[i + 1]) continue;
return .{ .row = @intCast(i), .at = pane.wrap_col[i] };
}
return .{ .row = -1, .at = 0 };
}
/// ponytail: `delta` is LOGICAL LINES, wrapped or not — one `j` past the
/// bottom scrolls a whole line even when that line is five screen rows, and
/// a wheel tick or a Ctrl-d page counts lines rather than rows. So a body
/// full of long lines scrolls in jumps, and the view can never sit at the
/// MIDDLE of a wrapped line. That is the ceiling the whole feature buys its
/// smallness with: wrap is render + hit-test and nothing else in the editor
/// knows about it. The upgrade is to make f.scroll a (line, row-within-line)
/// pair, which every reader of it — this, the scrollbar, the syntax window,
/// bodyText, ensureCursorVisible, the gutter click — would then have to
/// learn; do that when scrolling long lines actually annoys someone.
fn scrollBy(pane: *Pane, delta: i32) void {
if (pane.file) |*f| {
const max: i64 = @intCast(file_pane.nlines(pane.gpa, f) -| 1);
const n = std.math.clamp(@as(i64, @intCast(f.scroll)) + delta, 0, max);
const next: usize = @intCast(n);
if (next != f.scroll) {
f.scroll = next;
f.syntax_dirty = true;
}
} else if (hasPdf(pane)) {
if (comptime pdf_enabled) {
const pv = &pane.pdf.?;
const max: i64 = @intCast(modal.lineCount(pv.text) -| 1);
pv.text_scroll = @intCast(std.math.clamp(
@as(i64, @intCast(pv.text_scroll)) + delta,
0,
max,
));
}
} else {
// the vt scrolls in SHELL rows; convert through the edit buffer
const off: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
pane.vt.screens.active.scroll(.{ .delta_row = pane.gridRow(pane.surfRow(off) + delta) - off });
}
}
pub fn ensureCursorVisible(pane: *Pane) void {
// scrolloff margin, shrunk on short panes so the band stays non-empty
var margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2));
const off = pane.scroll();
// A WRAPPED body shows fewer LINES than it has rows, and scrolling is
// still by line — so the bottom of the view is the last line the map
// recorded, not off+rows-1, or every long line would scroll the file
// out from under itself. Clamped to the file's own last line because
// the rows past EOF go on counting, and the margin shrinks with it for
// the same reason the short-pane clamp above exists: a band wider than
// the view has no stable position and the two branches below then take
// turns moving it, one keystroke each, for ever.
var last = off + @as(i32, pane.rows) - 1;
if (pane.wrap_n > 0) if (pane.file) |*f| {
const eof: i32 = @intCast(file_pane.nlines(pane.gpa, f) -| 1);
last = @min(pane.wrap_line[pane.wrap_n - 1], eof);
margin = @min(margin, @divTrunc(@max(0, last - off), 2));
};
if (pane.cur_row < off + margin) {
pane.scrollBy(pane.cur_row - margin - off); // scrollBy clamps at line 0
} else if (pane.cur_row > last - margin) {
// don't scroll a file past EOF-at-bottom-row (vim's bottom clamp);
// terminals overshoot harmlessly — the vt clamps at the live bottom
var to = pane.cur_row + margin;
if (pane.file) |*f| to = @min(to, @as(i32, @intCast(file_pane.nlines(pane.gpa, f) -| 1)));
if (comptime pdf_enabled) {
if (pane.pdf) |pv|
to = @min(to, @as(i32, @intCast(modal.lineCount(pv.text) -| 1)));
}
pane.scrollBy(@max(0, to - last));
}
// the horizontal mirror, files only: keep scroll_off columns of
// context around the cursor (wheel-driven hscroll is exempt — it
// never moves the cursor, and a cursor move pulls the view back).
// A wrapped body has nothing to scroll sideways, and its hscroll is
// left ALONE rather than zeroed: turn the wrap back off and the view
// you had is still there.
if (pane.file != null and pane.wrap_n == 0) {
const w: i32 = @max(1, @as(i32, pane.cols) - @as(i32, config.PREFIX_W));
const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2));
if (pane.cur_col < pane.hscroll + hmargin)
pane.hscroll = @max(0, pane.cur_col - hmargin)
else if (pane.cur_col > pane.hscroll + w - 1 - hmargin)
pane.hscroll = pane.cur_col - (w - 1 - hmargin);
}
}
/// the last navigable row: file -> last content line; terminal -> viewport bottom
fn lastNavRow(pane: *Pane) i32 {
if (pane.file) |*f| return @intCast(file_pane.nlines(pane.gpa, f) -| 1);
if (hasPdf(pane)) return @intCast(modal.lineCount(if (comptime pdf_enabled) pane.pdf.?.text else "") -| 1);
return pane.scroll() + @as(i32, pane.rows) - 1;
}
fn pinCursor(pane: *Pane) void {
if (pane.cur_pinned) return;
if (pane.file != null or hasPdf(pane)) {
pane.cur_row = pane.scroll();
pane.cur_col = 0;
} else {
const goff: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
pane.cur_row = pane.surfRow(@as(i32, @intCast(pane.vt.screens.active.cursor.y)) + goff);
pane.cur_col = @intCast(pane.vt.screens.active.cursor.x);
}
pane.cur_pinned = true;
}
};
const PdfDrag = if (pdf_enabled) struct {
native: bool = false,
/// Drag updates keep selection geometry/text live, but their expensive
/// baked raster highlight is committed once on release.
selection_changed: bool = false,
} else struct {};
const Drag = union(enum) {
none,
/// `corner_idx` is what makes this a CORNER grab: the press landed on a
/// cell that is both this v-border and one of left_col's own h-borders,
/// and then the one drag moves both boundaries — cur_x the column pair,
/// cur_y left_col's pane pair at index corner_idx. null is a plain edge
/// drag and cur_y is only carried along for the preview.
///
/// It is the LEFT column's h-splits a corner honours, and only those. The
/// v handle IS left_col's last cell, so left_col's horizontal hint is
/// drawn straight THROUGH it while the right column's spans start one cell
/// further right — the corners this finds are exactly the cells where the
/// user can see the two lines cross. Honouring the right column too would
/// scatter corners across rows with no visible crossing.
///
/// ponytail: so a corner moves exactly TWO boundaries, never three — a
/// right-column h-split that happens to sit at the same row is left alone,
/// even though the eye may read the whole row as one line. Add a second
/// optional index (the right column's k) here and a second applyRowSplit
/// call if that ever reads as a bug rather than as restraint.
border_v: struct { left_col: usize, cur_x: u16, corner_idx: ?usize = null, cur_y: u16 = 0 },
border_h: struct { col: usize, top_idx: usize, cur_y: u16 },
move: struct { id: usize, cur_x: u16, cur_y: u16 },
/// a left sweep along a pane's TAG row: it drives the tag's own cursor and
/// selection (rendered-tag columns) rather than the body's block selection,
/// which is what makes a one-line tag select like a line of text
tag: struct { id: usize },
/// chorded: a 1-2/1-3 cut/paste chord fired during this left drag —
/// the drag's own release is then inert
select: struct {
id: usize,
button: Mouse.Button,
chorded: bool = false,
ctrl: bool = false,
/// This gesture began over a usable native PDF raster. The payload is
/// zero-bit when PDF support is absent.
pdf: PdfDrag = .{},
},
};
// The two border clamps, pulled out as plain arithmetic on plain numbers for
// one reason: a CORNER drag runs both of them off the same mouse position, and
// the thing that has to hold is that each one only ever looks at its own axis.
// A clamp that consulted the other axis — or a single "is this point legal"
// test over the pair — would freeze the whole gesture the moment either edge
// hit its stop, when what the hand expects is the free axis to keep tracking
// and the pinned one to sit at the wall. Being pure, they are also the piece
// worth a test; see below.
/// Where a vertical border drag settles: `mcol` clamped so neither column of
/// the pair falls under MINW. `lx`/`lw` are the left column's x and width,
/// `rw` the right column's. Degenerate pairs (a window too narrow to hold two
/// minimums at all) pass the mouse through rather than snapping to a lie.
fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 {
const lo = lx + config.MINW;
const hi = lx +| lw +| rw -| config.MINW;
return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol;
}
/// Where a horizontal border drag settles: `mrow` clamped so either pane may
/// shrink to just its tag row (BOX_H) but no further. `ay`/`ah` are the upper
/// pane's y and height, `bh` the lower pane's.
fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 {
const lo = ay + BOX_H - 1;
const hi = ay +| ah +| bh -| (BOX_H + 1);
return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow;
}
test "a corner drag's two axes clamp independently" {
// a 100-wide window split 50/50, and a 30-row column split 15/14 under the
// topbar: the shape windowops.snap drives
const lx: u16 = 0;
const lw: u16 = 50;
const rw: u16 = 50;
const ay: u16 = TOPBAR_H;
const ah: u16 = 15;
const bh: u16 = 14;
// the walls, spelled out: the handle is the upper pane's LAST row, so the
// upper pane bottoms out with its tag row alone at ay, and the lower pane
// does the same one row above the pair's end
const row_lo: u16 = ay + BOX_H - 1;
const row_hi: u16 = ay + ah + bh - (BOX_H + 1);
// each axis alone, at both walls
try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0));
try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999));
try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0));
try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999));
// THE corner property: drag off the right edge while staying mid-height —
// x sits at its wall, y still tracks the mouse row exactly
try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999));
try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12));
// and the mirror: pinned at the bottom, x still free
try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999));
try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40));
// both pinned at once is just both walls, not a stuck gesture
try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0));
try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999));
// degenerate pairs pass through untouched, each on its own terms: a pane
// pair with no room stays draggable even when the column pair has room
try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7));
try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40));
try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9));
}
pub const Rect = struct { x: u16, y: u16, w: u16, h: u16 };
pub const Options = struct {
tty_only: bool = false,
/// initial shell panes: 1 (default) or 3 for the classic two-column boot.
/// A `file` outranks this — see there.
shells: u8 = 1,
/// argv FILE (resolved absolute): boot with it as the ONLY pane, focused
/// and filling the window. It names the whole boot layout, so `shells` is
/// not consulted at all (it never was — the file arm always won).
file: ?[]const u8 = null,
file_line: usize = 0,
tty_toggle: u21 = config.tty_toggle_default,
/// load a dump of another instance instead of spawning shells (acme -l)
load_path: ?[]const u8 = null,
/// Native main fills this with the contents of the per-user config file.
/// Keeping discovery out of the core makes constructors and web builds
/// deterministic; when present, each line is dispatched as a builtin
/// before init returns and therefore before any frontend can render.
startup_config: ?[]const u8 = null,
/// Initial grid. Shell contract: for LIVE sessions leave these at the
/// defaults and deliver the real size as the first resize EVENT — the core
/// defers each shell's greeting until after a resize (so `ls` wraps to the
/// real pane width); pre-sizing here means that resize never fires and the
/// greeting never runs. Pre-size only for dump loads (nothing greets, and
/// it avoids reflowing replayed content twice).
cols: u16 = 80,
rows: u16 = 24,
};
const PendingPipe = struct {
id: u32,
pane: usize,
serial: u32,
revision: u32,
command: []u8,
cwd: []u8,
inputs: []selection_pipe.Input,
ranges: [MAX_SELS]modal.HxRange,
primary: u8,
explicit: bool,
fn deinit(wait: *PendingPipe, gpa: std.mem.Allocator) void {
gpa.free(wait.command);
gpa.free(wait.cwd);
for (wait.inputs) |input| gpa.free(@constCast(input.bytes));
gpa.free(wait.inputs);
wait.* = undefined;
}
fn request(wait: *const PendingPipe) selection_pipe.Request {
return .{
.id = wait.id,
.command = wait.command,
.cwd = wait.cwd,
.inputs = wait.inputs,
};
}
};
pub const Pardes = struct {
gpa: std.mem.Allocator,
opts: Options,
screen_w: u16,
screen_h: u16,
cell_pixels: CellPixels = .{},
resize_count: usize = 0,
panes: [MAX_PANES]?*Pane = @splat(null),
// layout: columns own x by weight; panes own y by vweight within a column.
ncol: usize = 0,
col_weight: [MAX_COLS]f32 = @splat(1),
col_terms: [MAX_COLS][MAX_PANES]usize = undefined,
col_n: [MAX_COLS]usize = @splat(0),
// derived each sync
rects: [MAX_PANES]Rect = undefined,
col_x: [MAX_COLS]u16 = undefined,
col_w: [MAX_COLS]u16 = undefined,
active: usize = 0,
/// THE focus history: where the keyboard has BEEN, oldest first, and `jcur`
/// is the entry it is at NOW (so `jumps[jcur]` is always the live spot and
/// the entries past it are the ones Ctrl-i walks forward into). Maintained
/// in exactly one place — sync() — and read by everything that asks "where
/// was I": Back/Forward, Last, the Jumplist buffer, prevFocus when a pane
/// closes, Toggleterm, and the directory order a look resolves in.
///
/// One list, not two. A jumplist kept beside a focus history is two things
/// to keep agreeing, and they would disagree the first time one of them
/// forgot a pane the other still names.
jumps: [MAX_JUMPS]Loc = undefined,
njumps: usize = 0,
jcur: usize = 0,
/// hands out Pane.serial; monotonic, never reused
next_serial: u32 = 0,
theme_idx: usize = 0,
chrome_animation: ChromeAnimation = ChromeAnimation.init(initial_chrome),
/// False only while startup configuration or a dump restore is selecting
/// its first theme. No frame is rendered in that interval.
animate_theme_changes: bool = false,
colors_on: bool = true,
/// soft line breaks in file panes (the Wrap builtin). Off by default: with
/// it off every row math in here is the one-row-per-line arithmetic it has
/// always been, and nothing on screen moves by a cell.
wrap_on: bool = false,
show_debug: bool = false,
/// the Crt builtin's CRT post-process, rendered by the gui shell only
/// (the tty and web shells never read it)
crt_on: bool = false,
/// Native pixel attachments supported by the shell (Kitty graphics in a
/// terminal, GPU textures in SDL). Image panes dynamically fall back to
/// the PETSCII matcher without it.
native_images: bool = false,
quit: bool = false,
drag: Drag = .none,
hover_col: u16 = 0,
hover_row: u16 = 0,
/// touchpad drift guard, counted down in horizontal wheel ticks — see
/// config.wheelTick, which owns the whole rule. Global, and clock-free on
/// purpose: the core has no clock, so "recently scrolled vertically" can
/// only mean "in the last few wheel events", which is all the heuristic
/// needs.
/// ponytail: it therefore never times out — only a horizontal tick spends
/// it, so a sideways swipe an hour after a scroll still pays the toll. If
/// that ever bites, clear it on any non-wheel event: a keypress or a click
/// is proof the gesture ended, and still needs no clock.
wheel_guard: u8 = 0,
ctrl_w_pending: bool = false,
/// A key is being REPLAYED over several selections (replaySels). The one
/// thing the replay cannot do is let a per-pass action that is really a
/// per-KEYSTROKE action fire once per range: the undo snapshot must be
/// taken once, the yank register accumulates instead of being overwritten,
/// and anything that opens, closes or focuses a pane (runBuiltin) or asks
/// the language backend (lspRequest) happens on the first pass and stops
/// the replay dead — see multiOnce.
multi_on: bool = false,
multi_first: bool = false,
multi_stop: bool = false,
/// SPC leader in flight, holding the key path typed so far (empty = just
/// SPC). Global like ctrl_w_pending — there is one leader and it acts on
/// the active pane, whose tag shows the pending path while it waits.
leader_on: bool = false,
leader_keys: [4]u8 = undefined,
leader_n: u8 = 0,
/// the TOPBAR holds the keyboard, parked at this column of the rendered
/// row-0 line. Global like leader_on for the same reason: row 0 is not a
/// pane and never will be, so its one piece of focus state cannot live on
/// one. `null` = the panes have the keyboard, which is every other frame.
topbar_col: ?u16 = null,
ov_pinch_scale: f32 = 1.0,
ov_touch_scroll_delta: f32 = 0.0,
/// middle+left chord argument: a kept left selection captured by a left
/// press during an active middle select-drag; consumed on middle release
chord_arg: ?[]u8 = null,
/// how many `execute` calls are on the stack — see max_exec_depth
exec_depth: u8 = 0,
/// The one language query in flight. ONE, deliberately: every one of these
/// is a keystroke the user is waiting on, so a second press means "I meant
/// this one" — the id bump makes the older answer stale and lspResponse
/// drops it. A queue would only buy the right to render an answer nobody
/// is waiting for any more.
/// `arg` rides along only so the buffer the answer opens can record what
/// was asked (a rename's new name, a symbol query) — the query itself has
/// it in the effect already.
lsp_seq: u32 = 0,
lsp_wait: ?struct { id: u32, kind: lsp.Kind, pane: usize, arg: Effect.Buf(128) } = null,
/// One current shell-filter request. A newer submit frees and supersedes
/// it; old worker answers then fail the id check. The request itself owns
/// every byte a shell snapshots while draining the id-only effect.
pipe_seq: u32 = 0,
pipe_wait: ?PendingPipe = null,
/// pending effects, drained by the shell after each update. Growable: one
/// update can emit unbounded writes (a big selection executed is chunked
/// into 64-byte write effects) — a fixed ring overflows and panics.
effects: std.ArrayList(Effect) = .empty,
effects_head: usize = 0,
/// modal yank register (gpa-owned); a yank also mirrors out to the system
/// clipboard via the set_clipboard effect.
yank: ?[]u8 = null,
/// the last serialized dump (gpa-owned), read by the write_dump effect
dump_out: ?[]u8 = null,
/// where the shell wrote the last dump (shell reports back after
/// write_dump); shown in the topbar as `Restore <path>`
last_dump: ?[]const u8 = null,
/// a Restore builtin wants this dump loaded into the live session; the
/// shell consumes it via takeRestore each frame (core stays sans-IO)
restore_req: ?[]const u8 = null,
restore_buf: [1024]u8 = undefined,
surface: Surface = .{},
/// per-update scratch (paneCursorLines, selection text); reset each update
scratch: std.heap.ArenaAllocator,
pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes {
const p = try gpa.create(Pardes);
p.* = .{ .gpa = gpa, .opts = opts, .screen_w = opts.cols, .screen_h = opts.rows, .scratch = .init(gpa) };
if (opts.file) |path| {
// FILE argv boot: the doc alone, filling the window. Naming a file
// is asking to READ it, not to be handed a shell you did not ask
// for and have to close — and the launch directory is one Newcol
// away when it is wanted. Doc, PDF and image all boot the same way.
_ = initial_doc: {
if (comptime pdf_enabled) if (look.isPdfPath(path))
break :initial_doc try p.openPdfView(0, path, opts.file_line);
if (look.isImagePath(path))
break :initial_doc try p.openImageView(0, path);
break :initial_doc try file_pane.open(p, 0, path, opts.file_line);
};
p.ncol = 1;
p.col_n[0] = 1;
p.col_terms[0][0] = 0;
} else if (opts.tty_only) {
_ = try p.newPane(0);
p.panes[0].?.mode = .tty;
p.ncol = 1;
p.col_n[0] = 1;
p.col_terms[0][0] = 0;
} else if (opts.shells >= 3) {
// classic layout: two columns, the left one split in two.
_ = try p.newPane(0);
_ = try p.newPane(1);
_ = try p.newPane(2);
for (p.panes[0..3]) |slot| slot.?.greet = true;
p.ncol = 2;
p.col_n[0] = 2;
p.col_terms[0][0] = 0;
p.col_terms[0][1] = 1;
p.col_n[1] = 1;
p.col_terms[1][0] = 2;
} else {
// ponytail: 1 and 3 are the only boot layouts; anything else acts as 1
_ = try p.newPane(0);
p.panes[0].?.greet = true;
p.ncol = 1;
p.col_n[0] = 1;
p.col_terms[0][0] = 0;
}
p.sync();
p.applyStartupConfig();
p.finishThemeInitialization();
p.sync();
return p;
}
pub fn deinit(p: *Pardes) void {
for (&p.panes) |*slot| if (slot.*) |pane| {
p.deinitPane(pane);
slot.* = null;
};
const gpa = p.gpa;
if (p.yank) |y| gpa.free(y);
if (p.dump_out) |d| gpa.free(d);
if (p.last_dump) |d| gpa.free(d);
if (p.chord_arg) |a| gpa.free(a);
if (p.pipe_wait) |*wait| wait.deinit(gpa);
p.effects.deinit(gpa);
p.scratch.deinit();
gpa.free(p.surface.cells);
if (p.surface.images.len > 0) gpa.free(p.surface.images);
gpa.destroy(p);
}
/// shell feedback after write_dump: remember where the dump landed (the
/// topbar grows a `Restore <path>` word pointing at it)
pub fn setLastDump(p: *Pardes, path: []const u8) void {
const copy = p.gpa.dupe(u8, path) catch return;
if (p.last_dump) |old| p.gpa.free(old);
p.last_dump = copy;
}
/// the shell polls this each frame: a pending Restore's dump path, or null
pub fn takeRestore(p: *Pardes) ?[]const u8 {
const r = p.restore_req;
p.restore_req = null;
return r;
}
/// the topbar line: the fixed builtins, plus `Restore <path>` once a dump
/// exists — render and click dispatch must agree on this exact string
fn topbar(p: *Pardes, buf: []u8) []const u8 {
if (p.last_dump) |d|
return std.fmt.bufPrint(buf, config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str;
return config.topbar_str;
}
pub fn deinitPane(p: *Pardes, pane: *Pane) void {
if (pane.image) |*iv| {
p.gpa.free(iv.path);
if (iv.rgba.len > 0) p.gpa.free(iv.rgba);
if (iv.raw.len > 0) p.gpa.free(iv.raw);
if (iv.grid.len > 0) p.gpa.free(iv.grid);
}
if (comptime pdf_enabled) {
if (pane.pdf) |*pv| {
p.gpa.free(pv.path);
for (pv.rasters.items) |raster| if (raster.rgba.len > 0)
p.gpa.free(raster.rgba);
pv.rasters.deinit(p.gpa);
p.gpa.free(pv.page_sizes);
p.gpa.free(pv.page_starts);
p.gpa.free(pv.page_heights);
// `rgba` aliases the active raster for legacy geometry state;
// its owner was released above.
if (pv.text.len > 0) p.gpa.free(pv.text);
if (pv.search_query.len > 0) p.gpa.free(pv.search_query);
if (pv.search_results) |*results| results.deinit(p.gpa);
if (pv.selection) |*selection| selection.deinit(p.gpa);
if (pv.selection_text.len > 0) p.gpa.free(pv.selection_text);
if (pv.outline) |*outline| outline.deinit(p.gpa);
pv.document.deinit();
}
}
if (pane.file) |*f| {
// a watched file is going away: tell the shell to drop it. The id
// comes from the slot, which every caller still has pointing at
// `pane` (they null it right after) — deinitPane has never needed
// one before and threading it through seven call sites for this is
// worse than the scan.
if (f.output == null) for (p.panes, 0..) |slot, i| {
if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(i), .on = false } });
};
p.gpa.free(f.path);
p.gpa.free(f.content);
if (f.line_starts.len > 0) p.gpa.free(f.line_starts);
if (f.highlights.len > 0) p.gpa.free(f.highlights);
for (f.undo.items) |s| p.gpa.free(s.content);
f.undo.deinit(p.gpa);
for (f.redo.items) |s| p.gpa.free(s.content);
f.redo.deinit(p.gpa);
}
if (pane.ovl) |o| p.gpa.free(o.text);
pane.tag_tail.deinit(p.gpa);
for (pane.ed_undo.items) |sn| if (sn.ovl) |o| p.gpa.free(o.text);
pane.ed_undo.deinit(p.gpa);
for (pane.ed_redo.items) |sn| if (sn.ovl) |o| p.gpa.free(o.text);
pane.ed_redo.deinit(p.gpa);
pane.stream.deinit();
pane.vt.deinit(p.gpa);
pane.tty_stream.deinit(p.gpa);
p.gpa.destroy(pane);
}
/// Allocate a pane slot with a live terminal emulator and queue the spawn
/// effect (optionally in a directory); the shell answers by forking a pty
/// and wiring reads back as Event.output for this pane id.
pub fn newPane(p: *Pardes, id: usize) !*Pane {
return p.newShell(id, "");
}
pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane {
std.debug.assert(p.panes[id] == null);
if (cwd.len > 256) return error.PathTooLong; // spawn effect cwd is a Buf(256)
const pane = try p.gpa.create(Pane);
pane.* = .{
.vt = try ghostty_vt.Terminal.init(p.gpa, .{
.cols = p.screen_w,
.rows = p.screen_h,
.max_scrollback = 16 * 1024 * 1024,
}),
.stream = undefined,
.gpa = p.gpa,
.cols = p.screen_w,
.rows = p.screen_h,
};
pane.stream = pane.vt.vtStream();
// answer terminal queries (DSR/DA/kitty) back into the pty, else
// crossterm apps (nushell, helix, fzf) block on the reply forever.
pane.stream.handler.effects.write_pty = term_pane.ptyReport;
pane.stream.handler.effects.device_attributes = term_pane.ptyDeviceAttrs;
p.next_serial += 1;
pane.serial = p.next_serial;
p.panes[id] = pane;
p.emit(.{ .spawn = .{ .pane = @intCast(id), .cwd = .from(cwd) } });
return pane;
}
/// a doc pane (file/image): no pty, no spawn; a stub 1x1 emulator only
/// because the shared machinery touches its allocator-owned bits.
pub fn newDocPane(p: *Pardes, id: usize) !*Pane {
std.debug.assert(p.panes[id] == null);
const pane = try p.gpa.create(Pane);
pane.* = .{
.vt = try ghostty_vt.Terminal.init(p.gpa, .{ .cols = 1, .rows = 1 }),
.stream = undefined,
.gpa = p.gpa,
.cols = p.screen_w,
.rows = p.screen_h,
};
pane.stream = pane.vt.vtStream();
p.next_serial += 1;
pane.serial = p.next_serial;
p.panes[id] = pane;
return pane;
}
pub fn freeSlot(p: *Pardes) ?usize {
return for (p.panes, 0..) |slot, i| {
if (slot == null) break i;
} else null;
}
/// chunk arbitrary-length bytes into fixed-size write effects (order kept)
pub fn emitWrite(p: *Pardes, id: usize, bytes: []const u8) void {
var off: usize = 0;
while (off < bytes.len) {
const n = @min(bytes.len - off, 64);
p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(bytes[off .. off + n]) } });
off += n;
}
}
/// The shell reports the spawned pane's working directory (and later cwd
/// changes it observes, e.g. via /proc/<pid>/cwd before each frame).
pub fn setCwd(p: *Pardes, id: usize, cwd: []const u8) void {
const pane = p.panes[id] orelse return;
const n = @min(cwd.len, pane.cwd.len);
@memcpy(pane.cwd[0..n], cwd[0..n]);
pane.cwd_len = @intCast(n);
}
/// Complete a `new_file` effect without doing IO in the core. The shell
/// has already created `path` as an empty file; we model those known empty
/// bytes directly, insert immediately below the still-live calling pane in
/// ITS column (never whichever column became active), focus it, and start
/// the same watch every ordinary file pane has. False leaves ownership
/// with the shell, which closes and unlinks the unadopted file.
pub fn openNewFile(p: *Pardes, source: u8, serial: u32, path: []const u8) bool {
if (path.len == 0 or source >= MAX_PANES) return false;
const src = p.panes[source] orelse return false;
if (src.serial != serial) return false;
const sf = p.layoutFindTerm(source) orelse return false;
const free = p.freeSlot() orelse return false;
const path_copy = p.gpa.dupe(u8, path) catch return false;
const content = p.gpa.dupe(u8, "") catch {
p.gpa.free(path_copy);
return false;
};
const pane = p.newDocPane(free) catch {
p.gpa.free(content);
p.gpa.free(path_copy);
return false;
};
pane.file = .{ .path = path_copy, .content = content };
pane.cur_pinned = true;
// sf was captured from SOURCE, not active. Nothing above this point
// mutates layout, so it is still the exact calling column/index.
p.layoutInsert(sf.col, sf.idx + 1, free);
p.splitBelow(source, pane);
p.active = free;
p.emit(.{ .watch = .{ .pane = @intCast(free), .on = true } });
p.sync();
return true;
}
/// Post the transient message on `id`'s last row. Called by a SHELL once
/// the IO it narrates has actually happened, exactly as openNewFile above
/// completes a `new_file` effect: the core neither writes files nor owns a
/// clock, so both the outcome and the wall time in `text` come from there
/// (message.zig spells it, once, for both native shells).
///
/// Nothing here decides WHEN it goes away — update does, on the next key or
/// mouse event — and nothing here knows whether the row is free: an armed
/// prompt simply outranks a message at render time, so a message posted
/// under one is stored and invisible rather than refused.
pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void {
if (id >= MAX_PANES) return;
const pane = p.panes[id] orelse return;
pane.msg_len = @intCast(@min(text.len, pane.msg.len));
@memcpy(pane.msg[0..pane.msg_len], text[0..pane.msg_len]);
}
pub fn emit(p: *Pardes, e: Effect) void {
p.effects.append(p.gpa, e) catch {};
}
pub fn nextEffect(p: *Pardes) ?Effect {
if (p.effects_head == p.effects.items.len) {
p.effects.clearRetainingCapacity();
p.effects_head = 0;
return null;
}
const e = p.effects.items[p.effects_head];
p.effects_head += 1;
return e;
}
pub fn update(p: *Pardes, ev: Event) void {
// A transient message is exactly as old as your last input: touch the
// keyboard or the mouse and it is gone, on every pane, because a
// message is a report and you have just proved you are back. Only
// INPUT counts — a resize, pty output, a watch or an answering worker
// all repaint without you, and a message that a background shell could
// wipe would be one you never got to read.
//
// An ARMED PROMPT is a different occupant of the same row and is not
// touched here: it lives in tag_tail, it is what the keystroke is being
// typed INTO, and it ends at Enter or Esc. So clearing here can never
// fight one — at worst it clears something the prompt was already
// hiding.
switch (ev) {
.key, .mouse => for (p.panes) |slot| {
if (slot) |pane| pane.msg_len = 0;
},
else => {},
}
switch (ev) {
.resize => |sz| {
if (comptime pdf_enabled) {
var before: [MAX_PANES]?PdfViewport = @splat(null);
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
if (pane.pdf != null) before[id] = p.pdfViewport(pane);
}
p.screen_w = sz.cols;
p.screen_h = sz.rows;
p.cell_pixels.w = @max(1, sz.cell_pixels.w);
p.cell_pixels.h = @max(1, sz.cell_pixels.h);
// Compare the effective per-pane pixel viewport, not the
// resize event itself: duplicate SIGWINCH notifications
// must not undo a reader's manual pan.
p.computeGeom();
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
if (pane.pdf) |*pv| {
if (!std.meta.eql(before[id], p.pdfViewport(pane))) {
capturePdfLayoutAnchor(pv);
pv.layout_valid = false;
pv.search_reveal_pending = pv.search_query.len > 0;
}
}
}
} else {
p.screen_w = sz.cols;
p.screen_h = sz.rows;
}
p.resize_count += 1;
},
.output => |o| {
const pane = p.panes[o.pane] orelse return;
pane.tty_stream.appendSlice(p.gpa, o.bytes) catch {};
pane.stream.nextSlice(o.bytes);
// follow new output to the bottom only in tty mode; in
// normal/insert the user is reading scrollback and the view
// holds still while output streams in. Tag edits hijack
// pane.mode to insert — the body mode sits in tag_mode.
const bmode = if (pane.tag_edit) pane.tag_mode else pane.mode;
if (bmode == .tty)
pane.vt.screens.active.scroll(.active);
},
.eof => |e| p.removePane(e.pane),
.lsp_resp => |r| p.lspResponse(r.id, r.rows),
.pipe_resp => |r| p.pipeResponse(r.id, r.success, r.outputs),
.file_changed => |fc| p.fileChanged(fc.pane, fc.bytes),
.key => |key| p.handleKey(key),
.mouse => |m| p.handleMouse(m),
.pdf_scroll => |scroll| {
if (comptime pdf_enabled) {
if (scroll.pane < MAX_PANES) {
if (p.panes[scroll.pane]) |pane| {
if (hasPdf(pane) and p.native_images)
_ = p.scrollPdfDocument(pane, @floatCast(scroll.delta_pixels));
}
}
}
},
.paste => |bytes| {
// a shell-level paste (bracketed/SDL): load the register, paste
p.setYank(bytes);
if (p.panes[p.active]) |pane| p.normalPaste(pane, false);
},
.pinch => |scale| p.ov_pinch_scale = scale,
.touch_scroll => |delta| p.ov_touch_scroll_delta = delta,
.tick => p.chrome_animation.advance(),
}
_ = p.scratch.reset(.retain_capacity);
p.sync();
}
fn setYank(p: *Pardes, text: []const u8) void {
// Inside a multi-selection replay the register collects EVERY range's
// text, in document order — the passes run last-range-first, so each
// new piece goes in front of what is already there.
// ponytail: helix keeps one register VALUE per range and pastes
// value[i] back at range[i]; pardes has a single register, so N
// cursors yank one newline-joined blob and a paste puts that whole
// blob at every cursor. Written down as a differential waiver rather
// than faked — a per-range register is its own feature.
if (p.multi_on and !p.multi_first) {
const old = p.yank orelse "";
const sep: []const u8 = if (text.len > 0 and text[text.len - 1] == '\n') "" else "\n";
const joined = std.fmt.allocPrint(p.gpa, "{s}{s}{s}", .{ text, sep, old }) catch return;
if (p.yank) |y| p.gpa.free(y);
p.yank = joined;
return;
}
if (p.yank) |y| p.gpa.free(y);
p.yank = p.gpa.dupe(u8, text) catch null;
p.emit(.{ .set_clipboard = {} });
}
/// A per-KEYSTROKE action reached from inside a per-SELECTION replay —
/// one that opens, closes or focuses a pane, or asks the language backend.
/// It must happen once rather than once per cursor, and once it has, the
/// remaining passes are meaningless (the pane they would edit may be gone),
/// so the replay stops. True = this pass may go ahead.
fn multiOnce(p: *Pardes) bool {
if (!p.multi_on) return true;
p.multi_stop = true;
return p.multi_first;
}
// ---- tag + selection text (chord sources) ----
/// the live tag prefix: the pane's cwd/path, and nothing else (an image
/// still names its kind — the renderer toggles it used to spell out are
/// builtins now, under SPC t). The mode used to lead this as a word; it is
/// the one character in the layout box now (renderPane), so every tagline
/// starts four columns further left and spends them on the path instead.
///
/// Arena-allocated like everything the renderer is handed — the tag is
/// retained through the frame and a cwd can be rewritten under us by the
/// next shell report, so this owns its bytes rather than lending the
/// pane's.
fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 {
const arena = p.scratch.allocator();
if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fmt.allocPrint(
arena,
"pdf {d}/{d} {s} PdfFit {s} PdfTint PdfSections {s}",
.{ pv.page + 1, pv.page_count, @tagName(pv.fit), @tagName(pv.tint), pv.path },
);
if (pane.image) |iv| return std.fmt.allocPrint(arena, config.tag_image ++ " {s}", .{iv.path});
if (pane.file) |f| return arena.dupe(u8, f.path);
return arena.dupe(u8, pane.cwdSlice());
}
/// the editable tail: the user's edited buffer once touched, else defaults
/// (a buffer with nothing to Save gets the plain tail — the table decides)
fn curTail(pane: *Pane) []const u8 {
if (pane.tag_init) return pane.tag_tail.items;
if (pane.file) |f| if (output_pane.fileTraits(f.output).saves) return file_pane_tail;
return pane_tail;
}
/// the tag exactly as it is rendered: prefix ++ tail. THE text tag_col and
/// tag_anchor index, so the renderer, the mouse, the motions and the chord
/// all read the same bytes at the same columns.
fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 {
return std.fmt.allocPrint(arena, "{s}{s}", .{ try p.tagPrefix(pane), curTail(pane) });
}
/// focus the tag for editing, seeding the tail on first touch and parking
/// the cursor at `col` — a column of the RENDERED tag (see tag_col).
/// NEGATIVE means the first EDITABLE column, which is where `:` and a
/// tagline hop land: a place no click can name, so it needs no sentinel of
/// its own and the callers need no prefix length.
fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void {
const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len);
if (!pane.tag_init) {
pane.tag_tail.appendSlice(p.gpa, curTail(pane)) catch return;
pane.tag_init = true;
}
if (!pane.tag_edit) pane.tag_mode = pane.mode;
pane.tag_edit = true;
pane.tag_sel = false;
// a one-line tag has no use for normal mode: always insert
pane.mode = .insert;
pane.pending = 0;
const end = edit0 + @as(i32, @intCast(pane.tag_tail.items.len));
pane.tag_col = @intCast(if (col < 0) edit0 else std.math.clamp(col, 0, end));
}
fn exitTagEdit(pane: *Pane) void {
// tags are always insert; leaving one restores the body mode: files
// back to normal, terminals to whatever they had — a click (this runs
// on every body press) must never change a shell pane's mode
if (pane.isTerminal()) {
if (pane.tag_edit) pane.mode = pane.tag_mode;
} else pane.mode = .normal;
pane.tag_edit = false;
pane.tag_sel = false;
pane.search_edit = false; // an abandoned search input stays as tag text
pane.pipe_edit = false;
pane.nsel_snap = 0; // ...and its s/S preview keeps whatever it previewed
}
fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } {
const a: usize = pane.tag_anchor;
const c: usize = pane.tag_col;
return .{ .lo = @min(a, c), .hi = @max(a, c) };
}
/// the text a tag Enter/Tab chord (and `y`) acts on: the char selection,
/// else the file-ish word under the cursor. Over the WHOLE rendered tag, so
/// the path is a word like any other — Enter on it looks it.
fn tagChordText(p: *Pardes, pane: *Pane) ?[]const u8 {
const text = p.tagText(p.scratch.allocator(), pane) catch return null;
if (pane.tag_sel) {
const b = tagSelBounds(pane);
const hi = @min(b.hi + 1, text.len);
return if (hi > b.lo) text[b.lo..hi] else null;
}
const b = config.wordBounds(text, @min(@as(usize, pane.tag_col), text.len));
return if (b.hi > b.lo) text[b.lo..b.hi] else null;
}
/// tag-edit key dispatch: a modal one-line editor over the rendered tag,
/// sharing the pane's mode — the cursor moves over all of it, edits reach
/// only the tail. Newlines are always dropped.
fn tagInsertKey(p: *Pardes, pane: *Pane, key: Key) void {
if (hit(key, config.escape)) {
exitTagEdit(pane); // the tag is ALWAYS insert; Esc leaves it
return;
}
// the acme chords on the selection or the word at the cursor
if (hit(key, config.look_key) or hit(key, config.exec_key)) {
if (p.tagChordText(pane)) |txt| {
pane.tag_sel = false;
p.runBuiltin(if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", txt);
}
return;
}
// the prefix is live chrome, not text you own: the cursor may sit in it
// (that is how the path selects), but every edit below is measured from
// the first EDITABLE column and simply does nothing to the left of it.
const edit0: u16 = @intCast((p.tagPrefix(pane) catch return).len);
const end: u16 = edit0 + @as(u16, @intCast(pane.tag_tail.items.len));
if (key.text.len > 0) {
if (pane.tag_col < edit0) return; // typing inside the path: inert
for (key.text) |ch| {
if (ch == '\n' or ch == '\r') continue; // one-line tag
pane.tag_tail.insert(p.gpa, pane.tag_col - edit0, ch) catch return;
pane.tag_col += 1;
}
return;
}
switch (key.cp) {
Key.backspace => if (pane.tag_col > edit0) {
_ = pane.tag_tail.orderedRemove(pane.tag_col - edit0 - 1);
pane.tag_col -= 1;
},
Key.left => if (pane.tag_col > 0) {
pane.tag_col -= 1;
},
Key.right => if (pane.tag_col < end) {
pane.tag_col += 1;
},
Key.home => pane.tag_col = 0,
Key.end => pane.tag_col = end,
else => {},
}
}
/// write a helix range back onto the tag cursor + selection: the rendered
/// tag's one-line mirror of setPaneRange.
fn setTagRange(pane: *Pane, text: []const u8, r: modal.HxRange) void {
const lo = @min(r.anchor, r.head);
const hi = @max(r.anchor, r.head);
pane.tag_col = @intCast(modal.hxCursor(text, r));
pane.tag_sel = hi > lo + 1; // a 1-wide range IS the block cursor
if (pane.tag_sel) pane.tag_anchor = @intCast(if (r.head > r.anchor) lo else hi - 1);
}
/// normal mode ON the tag — where `:` lands. The body's own helix motions
/// with the WHOLE rendered tag as a one-line document (so the path selects
/// like any other text, and Enter on it looks it), plus insert entry and
/// the acme chords; editing keys stay in insert (`i` then type, like the
/// mouse path) and never reach left of `edit0`.
fn tagNormalKey(p: *Pardes, pane: *Pane, key: Key) void {
const text = p.tagText(p.scratch.allocator(), pane) catch return;
const cur: usize = @min(@as(usize, pane.tag_col), text.len);
// Esc abandons the command line: back to the body, tail kept as text
if (hit(key, config.escape)) return exitTagEdit(pane);
// the chord: run the selection (or the word under the cursor) and drop
// back into the body — the whole point of `:`. The same two bindings as
// everywhere else (config.look_key / exec_key), so the command line is
// `:w<Tab>` by default.
// Nothing under the cursor means nothing ran: the tag keeps focus.
if (hit(key, config.look_key) or hit(key, config.exec_key)) {
const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd;
const txt = p.tagChordText(pane) orelse return;
const id = p.active;
exitTagEdit(pane); // leave the tag FIRST: Del frees the pane
p.runBuiltin(cmd, id, "", txt);
return;
}
// y — yank what the chord would run: the selection, else the word under
// the cursor. The path is selectable, so this is how you copy it out.
if (hit(key, config.tag_yank)) {
if (p.tagChordText(pane)) |txt| p.setYank(txt);
return;
}
// insert entry (one line, so I/A are the tail's ends). The prefix is
// read-only, so entering insert inside it parks at the first editable
// column instead — you can never be typing into the path.
if (hit(key, config.insert) or hit(key, config.append) or
hit(key, config.insert_line_start) or hit(key, config.insert_line_end))
{
const edit0: usize = (p.tagPrefix(pane) catch return).len;
pane.tag_col = @intCast(@max(edit0, if (hit(key, config.append))
modal.nextGrapheme(text, cur)
else if (hit(key, config.insert_line_start))
0
else if (hit(key, config.insert_line_end))
text.len
else
cur));
pane.tag_sel = false;
pane.mode = .insert;
return;
}
// h/j/k/l — a tagline is a place in the LAYOUT, so the four letters walk
// it: focus the neighbour and land on ITS tagline, still in normal mode,
// so tag-to-tag navigation never drops through a body. Runs the SAME
// Left/Down/Up/Right builtins `SPC w h/j/k/l` and `Ctrl-w` run, off the
// SAME table (config.window_keys) — one focusDir, one binding. Only the
// LETTER column: the arrows keep the in-tag grapheme motion below, so
// the letters cost nothing. Nothing in that direction = stay put, tag
// and all: focusDir left `active` alone, so there is nothing to undo —
// EXCEPT upwards, where "nothing" is still something (see below).
const dir: ?Builtin = for (config.window_keys) |wk| {
if (hit(key, &.{wk.letter})) break wk.cmd;
} else null;
if (dir) |d| {
const from = p.active;
p.runBuiltin(d, from, "", null);
if (p.active == from) {
// above the topmost tagline is the TOPBAR — row 0, the global
// one. It is not a pane, so focusDir can never reach it; this
// one fallback is what makes `k` walk off the top of the
// layout instead of dying there. Only from a tagline: a body's
// `SPC w k`/`Ctrl-w k` keeps its pane-to-pane meaning.
if (d == .Up) {
exitTagEdit(pane);
p.topbar_col = 0;
}
return;
}
const dest = p.panes[p.active] orelse return;
exitTagEdit(pane); // the pane we left is fully out of its tag...
p.enterTagEdit(dest, -1); // ...and the tail's start is the new park
if (dest.tag_edit) dest.mode = .normal;
return;
}
if (lineMotion(text, cur, key)) |r| setTagRange(pane, text, r);
}
/// the one-line normal-mode motion vocabulary as a helix range over `text`,
/// or null when `key` is not one of them: arrows by grapheme, `0`/`$`/`^`
/// (Home/End) to the ends, and the word motions, which select the span they
/// traverse exactly like the body's. A pane's tag and the TOPBAR are the
/// same one-line normal mode over different bytes, so the keys are read in
/// one place; only `h`/`l` differ — a tagline spends them on the layout,
/// the topbar has no layout — and each caller answers those itself.
fn lineMotion(text: []const u8, cur: usize, key: Key) ?modal.HxRange {
const target: ?usize = if (hit(key, config.line_move_left))
modal.prevGrapheme(text, cur)
else if (hit(key, config.line_move_right))
modal.nextGrapheme(text, cur)
else if (hit(key, config.line_start))
0
else if (hit(key, config.line_end))
modal.prevGrapheme(text, text.len)
else if (hit(key, config.line_first_nonws))
modal.firstNonWs(text)
else
null;
if (target) |t| return .{ .anchor = t, .head = t };
const wt: ?modal.WordTarget = if (hit(key, config.next_word_start))
.next_word_start
else if (hit(key, config.prev_word_start))
.prev_word_start
else if (hit(key, config.next_word_end))
.next_word_end
else if (hit(key, config.next_long_word_start))
.next_long_word_start
else if (hit(key, config.prev_long_word_start))
.prev_long_word_start
else if (hit(key, config.next_long_word_end))
.next_long_word_end
else
null;
const t = wt orelse return null;
return modal.hxWordMove(text, .{ .anchor = cur, .head = modal.nextGrapheme(text, cur) }, 1, t);
}
/// normal mode ON the topbar — row 0, where `k` off a top-row tagline
/// lands. The same one-line vocabulary a tag has (lineMotion), plus `h`/`l`
/// as plain grapheme motion: up here they have no neighbouring window to
/// walk to, so they cost nothing. Enter/Tab runs the word under the cursor
/// through the very dispatch a middle click on it uses, and `j` drops back
/// onto a tagline. The bar is chrome with no tail of its own, so there is
/// deliberately no insert mode and no selection: focus, move, run, leave.
fn topbarKey(p: *Pardes, key: Key) void {
var tb_buf: [1200]u8 = undefined;
const bar = p.topbar(&tb_buf);
// the line GROWS a `Restore <path>` word the moment a dump lands, so
// the column is clamped against the live line on every use
const cur: usize = @min(@as(usize, p.topbar_col orelse return), bar.len);
if (hit(key, config.escape)) {
p.topbar_col = null; // the active pane still has its body focus
return;
}
// the chord: run the word under the cursor, exactly as a middle click
// on it does. Leave the bar FIRST — `Kill` lives up here and tears the
// session down, the same hazard the pane-tag chord has with `Del`.
if (hit(key, config.look_key) or hit(key, config.exec_key)) {
const word = wordAtCol(bar, @intCast(cur));
p.topbar_col = null;
if (word.len > 0) _ = p.execute(p.active, word);
return;
}
// j — back down onto a tagline, the mirror of the k that got you here:
// the pane you came from if it still holds the top row, else the
// leftmost pane that does. Recomputed, never remembered, so a pane
// deleted while the bar had focus strands nobody.
if (hit(key, config.topbar_down)) {
var dest: ?usize = null;
for (p.panes, 0..) |slot, i| {
if (slot == null or p.rects[i].y != TOPBAR_H) continue;
if (i == p.active) {
dest = i;
break;
}
if (dest == null or p.rects[i].x < p.rects[dest.?].x) dest = i;
}
const d = dest orelse return;
const pane = p.panes[d].?;
p.topbar_col = null;
p.active = d;
p.enterTagEdit(pane, -1);
if (pane.tag_edit) pane.mode = .normal;
return;
}
const col: ?usize = if (hit(key, config.topbar_left))
modal.prevGrapheme(bar, cur)
else if (hit(key, config.topbar_right))
modal.nextGrapheme(bar, cur)
else if (lineMotion(bar, cur, key)) |r|
modal.hxCursor(bar, r)
else
null;
// never past the last cell: there is nothing to append up here, so the
// block cursor stays ON a character (which is where `$` already lands)
if (col) |c| p.topbar_col = @intCast(@min(c, modal.prevGrapheme(bar, bar.len)));
}
/// tag + '\n' + body: the full selectable pane text (row 0 = the tag)
fn paneText(p: *Pardes, pane: *Pane) ![]u8 {
const arena = p.scratch.allocator();
return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try p.bodyText(arena, pane) });
}
/// block-selected text, newline-joined per row; reads the rendered screen
/// so typed text and shell output select identically. Scratch-owned.
fn selectionText(p: *Pardes, pane: *Pane, sl: Sel) ![]const u8 {
const arena = p.scratch.allocator();
const r0 = @min(sl.r0, sl.r1);
const r1 = @max(sl.r0, sl.r1);
const c0: usize = @intCast(@max(0, @min(sl.c0, sl.c1)));
const c1: usize = @intCast(@max(0, @max(sl.c0, sl.c1)));
const text = try p.paneText(pane);
var out: std.ArrayList(u8) = .empty;
var it = std.mem.splitAny(u8, text, "\n");
var v: i32 = 0;
var first = true;
while (it.next()) |line| : (v += 1) {
if (v < r0 or v > r1) continue;
if (!first) try out.append(arena, '\n');
first = false;
const b0 = @min(c0, line.len);
const b1 = @min(c1 + 1, line.len);
try out.appendSlice(arena, line[b0..b1]);
}
return out.items;
}
/// Is (r,c) inside the span (ar,ac)..(br,bc), in reading order? Either end
/// may be given first — a selection swept upwards has its anchor after its
/// head — and the coordinate SYSTEM is the caller's: screen cells for a
/// mouse selection, absolute rows for a modal one.
fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool {
const fwd = ar < br or (ar == br and ac <= bc);
const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc };
const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac };
return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec));
}
/// acme: a no-drag middle/right click expands to the word under it —
/// file-ish, or a whole `` @`...` `` run (config.wordBounds is the spelling)
fn expandSel(p: *Pardes, pane: *Pane, sl: *Sel) void {
if (sl.c0 != sl.c1 or sl.r0 != sl.r1) return;
const text = p.paneText(pane) catch return;
var it = std.mem.splitAny(u8, text, "\n");
var v: i32 = 0;
while (it.next()) |line| : (v += 1) {
if (v != sl.r0) continue;
const col: usize = @intCast(@max(0, sl.c0));
if (col > line.len) return;
const b = config.wordBounds(line, col);
if (b.hi > b.lo) {
sl.c0 = @intCast(b.lo);
sl.c1 = @intCast(b.hi - 1);
}
return;
}
}
/// the word under the modal cursor as a pane-local selection (paneText
/// coords: row 0 is the tag; file panes carry the line-number prefix)
fn cursorWordSel(pane: *Pane) Sel {
const w = pane.wrapRow(pane.cur_row, pane.cur_col);
const vrow = w.row + @as(i32, BOX_H);
const vcol = if (pane.file != null) pane.cur_col - w.at + @as(i32, config.PREFIX_W) else pane.cur_col;
return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow };
}
/// the active modal selection as text (v range or x lines), if any
fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 {
if (comptime pdf_enabled) if (p.native_images) if (pane.pdf) |pv|
if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text;
if (pane.vsel.active) return p.vselText(pane);
if (!pane.msel.active) return null;
return p.yankRows(pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1));
}
/// What an execute takes as its ARGUMENT: text selected ANYWHERE (acme —
/// the chord argument is whatever is selected, in any window), searched
/// `first` (the pane the execute happened in), then the active pane (making
/// a selection focuses its pane, so it holds the most recent one), then
/// slot order. Per pane a kept left selection wins, else an explicit modal
/// (v/x, n/N) one. Scratch-owned: dead at the next arena reset, so a caller
/// that keeps it (the 2-1 chord) copies.
fn heldSelection(p: *Pardes, first: usize) ?[]const u8 {
var k: usize = 0;
while (k < p.panes.len + 2) : (k += 1) {
const i = switch (k) {
0 => first,
1 => p.active,
else => k - 2,
};
if (k > 0 and (i == first or (k > 1 and i == p.active))) continue;
const t = p.panes[i] orelse continue;
if (comptime pdf_enabled) if (p.native_images) if (t.pdf) |pv| {
if (pv.selection != null and pv.selection_text.len > 0)
return pv.selection_text;
};
if (t.sel[sel_slot].state == .done) {
if (p.selectionText(t, t.sel[sel_slot]) catch null) |tx| return tx;
} else if ((t.vsel.active and t.vsel.explicit) or t.msel.active) {
if (p.currentSelText(t)) |tx| return tx;
}
}
return null;
}
/// Splice a chord argument onto what the gesture pointed at. acme's 2-1
/// chord means "run this WITH that", and that is a command LINE: `Grep`
/// plus a held `foo` is the same string `Grep foo` you could have typed,
/// so it goes down the one path that already knows how to split a name
/// from its tail. The alternative — a second argument threaded past the
/// dispatcher — is what used to be here, and it could not survive Exec
/// becoming an ordinary builtin with one argument slot like every other.
/// Scratch-owned; `txt` itself when there is nothing to splice.
fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 {
const a = std.mem.trim(u8, arg orelse return txt, " \t\r\n");
if (a.len == 0) return txt;
const t = std.mem.trim(u8, txt, " \t\r\n");
return std.fmt.allocPrint(p.scratch.allocator(), "{s} {s}", .{ t, a }) catch txt;
}
fn handleKey(p: *Pardes, key: Key) void {
// the topbar holds the keyboard (`k` off the topmost tagline): row 0 is
// its own one-line normal mode and owns every key until Esc or a chord.
// Before the pane lookup because it needs no pane — that is the point.
if (p.topbar_col != null) return p.topbarKey(key);
const pane = p.panes[p.active] orelse return;
// a SPC leader in flight swallows the next key, whatever it is —
// before Ctrl-w, so a modified key abandons the sequence instead of
// arming a second prefix on top of it
if (p.leader_on) return p.leaderKey(key);
// Ctrl-w prefix: helix-style directional pane focus (h/j/k/l or the
// arrows), running the SAME builtins `SPC w h/j/k/l` runs off the SAME
// table a tagline's own h/j/k/l reads. It stays despite the leader
// covering it because it reaches one place the leader cannot: a pane
// in raw tty mode never sees SPC (the shell owns every printable key),
// so this is the only keyboard way out of one.
if (p.ctrl_w_pending) {
p.ctrl_w_pending = false;
for (config.window_keys) |wk| {
if (hit(key, &.{ wk.letter, wk.arrow })) return p.runBuiltin(wk.cmd, p.active, "", null);
}
return;
}
// insert mode owns Ctrl-w (delete word backward, helix); the focus
// prefix keeps normal/tty
if (hit(key, config.window_prefix) and pane.mode != .insert) {
p.ctrl_w_pending = true;
return;
}
// global window ops (any mode): Alt-n new terminal below, Alt-c move
// the active terminal into a fresh column
if (hit(key, config.new_shell_below)) {
const free = p.freeSlot() orelse return;
const nt = p.newShell(free, "") catch return;
nt.greet = true;
const src = p.splitParent(p.active);
const f = p.layoutFindTerm(src).?;
p.layoutInsert(f.col, f.idx + 1, free);
p.splitBelow(src, nt);
p.active = free;
return;
}
// the jump chords, global for the same reason: Ctrl-o has to get you
// out of wherever you are, including a pane in raw tty mode. Above the
// acme chords below, which is what makes Ctrl-i reachable at all — on
// a kitty-protocol host it arrives as its own key, and where it does
// not it IS Tab (0x09) and falls through to Exec, see config.jump_keys.
for (config.jump_keys) |jk| {
if (hit(key, &.{jk.chord})) return p.runBuiltin(jk.cmd, p.active, "", null);
}
if (hit(key, config.pane_to_new_column)) {
const f = p.layoutFindTerm(p.active).?;
if (p.ncol < MAX_COLS and p.col_n[f.col] > 1) {
p.absorbVWeight(p.active);
p.layoutRemove(p.active);
p.layoutAppendColumn(p.active);
}
return;
}
// the configured Ctrl-key, or Shift-Esc, toggles raw tty mode in and
// out (terminals only); tty is deliberately off the normal editing
// path. Shift-Esc needs a host that reports modifiers on Escape (the
// kitty keyboard protocol); where it doesn't it arrives as a plain
// Escape and still means what Escape always means.
const tty_toggle = (key.ctrl and key.cp == p.opts.tty_toggle) or
hit(key, config.tty_toggle_alt);
if (pane.isTerminal() and tty_toggle) {
if (pane.mode == .tty) {
pane.mode = .normal;
pane.pending = 0;
} else p.enterTty(p.active);
return;
}
// `|` owns the same visible one-line tag input as search, but Enter
// snapshots an asynchronous shell filter. Escape is a pure cancel:
// restore the old tail and never emit a request.
if (pane.pipe_edit and (hit(key, config.search_submit) or hit(key, config.escape))) {
if (hit(key, config.search_submit)) p.submitPipe(p.active);
pane.tag_tail.shrinkRetainingCapacity(@min(pane.pipe_at, pane.tag_tail.items.len));
exitTagEdit(pane);
pane.mode = .normal;
pane.pending = 0;
return;
}
// a search input in flight (`/` or Find): Enter searches, Esc abandons;
// both restore the tag tail and hand focus back to the body.
if (pane.search_edit and (hit(key, config.search_submit) or hit(key, config.escape))) {
if (hit(key, config.search_submit))
p.submitSearch(p.active)
else if (selRegexArmed(pane)) |_|
// Esc on an `s`/`S` preview: back to the selection it opened
// on. The empty pattern applies nothing, so this IS the
// snapshot — one path, not a second restore.
p.applySelRegex(pane, "", false);
pane.tag_tail.shrinkRetainingCapacity(@min(pane.search_at, pane.tag_tail.items.len));
exitTagEdit(pane);
pane.mode = .normal;
pane.pending = 0;
return;
}
// tag editing intercepts every other key: a modal one-line editor over
// the tail, sharing the pane's mode. Above the body chords — a focused
// tag owns Enter/Tab too (that IS the `:` command line).
if (pane.tag_edit) {
if (pane.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key);
// an armed `s`/`S` re-runs its pattern after EVERY keystroke: that
// live preview is what makes it interactive. Through the slot, not
// `pane` — a tag chord above can run a builtin that closed it.
const pn = p.panes[p.active] orelse return;
if (selRegexArmed(pn)) |a| p.applySelRegex(pn, a.pat, a.split);
return;
}
// the acme chords in the body — look at / execute (config.look_key and
// exec_key, Enter and Tab by default) the EXPLICIT modal selection
// (v/x/X, terminal n/N, search n/N); implicit motion residue falls back
// to the file-ish word under the cursor.
if (pane.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) {
const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd;
pane.pinCursor();
const explicit = (p.native_images and hasPdfSelection(pane)) or
(pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
if (explicit) {
if (p.currentSelText(pane)) |txt| {
pane.vsel.active = false;
pane.msel.active = false;
pane.select = false;
p.runBuiltin(cmd, p.active, "", txt);
return;
}
}
var sel = cursorWordSel(pane);
p.expandSel(pane, &sel);
const word = p.selectionText(pane, sel) catch return;
p.runBuiltin(cmd, p.active, "", word);
return;
}
// PDFs share BODY-NORMAL recognition with text, then deliberately
// adapt only navigation and the cross-pane command/search actions.
// Returning here keeps unsupported edits away from placeholder cells.
if (pane.mode == .normal and hasPdf(pane)) return p.handlePdfNormal(pane, key);
switch (pane.mode) {
.normal => {
p.handleNormal(pane, key);
},
.insert => {
if (hit(key, config.escape)) {
pane.mode = .normal;
pane.msel.active = false;
pane.pending = 0;
// leaving an `a` append session: the cursor backs up one
// grapheme and the appended-over span becomes the
// implicit selection (helix doc.restore_cursor)
if (pane.append_at) |aa| {
pane.append_at = null;
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
const gap = modal.hxOff(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) });
const a_off = modal.hxOff(text, .{ .row = @intCast(@max(0, aa.row)), .col = @intCast(@max(0, aa.col)) });
// helix restore_cursor is Range::new(from, prev(to)) on
// the GAP range, so it can never walk back past the
// append origin — a session whose edits ate everything
// typed collapses ONTO it. Without the clamp the cursor
// lands one cell before where the append began (`la`,
// Backspace, Esc).
const back = @max(a_off, modal.prevGrapheme(text, gap));
const bc = modal.hxPos(text, back);
pane.cur_row = @intCast(bc.row);
pane.cur_col = @intCast(bc.col);
pane.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false };
pane.cur_pinned = true;
pane.ensureCursorVisible();
// The other cursors move the same way the primary did —
// every one of them was handed the same keys, so every
// session shrank by the same grapheme — but they
// COLLAPSE rather than span: only the primary remembers
// where its append began (append_at is one field).
// ponytail: helix restores every range's appended-over
// span; store an origin per SelRange if that matters.
for (pane.sels[0..pane.nsel]) |*s| {
const sgap = modal.hxOff(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) });
const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap);
const bp = modal.hxPos(text, b2);
s.row = @intCast(bp.row);
s.col = @intCast(bp.col);
s.arow = s.row;
s.acol = s.col;
}
}
return;
}
p.handleInsert(pane, key);
},
.tty => p.forwardKey(p.active, key),
}
}
/// A key after SPC: walk the leader tree (leader_rows, the comptime table).
/// `?` at any depth opens Help scoped to the path typed so far; an exact
/// path runs its builtin with no arguments; a key that only extends a
/// group keeps waiting. ANYTHING else abandons the sequence — a typo must
/// not leave the next keystroke armed at a builtin that closes panes, and
/// the indicator vanishing is the receipt (vim and helix drop unmapped
/// leader keys the same way). Esc lands here as one of those.
fn leaderKey(p: *Pardes, key: Key) void {
p.leader_on = false; // only "still a prefix" below re-arms it
if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) return;
const c: u8 = @intCast(key.cp);
if (c == config.leader_help) return output_pane.openHelp(p, p.active, p.leader_keys[0..p.leader_n]);
if (p.leader_n >= p.leader_keys.len) return;
p.leader_keys[p.leader_n] = c;
p.leader_n += 1;
const pfx = p.leader_keys[0..p.leader_n];
// a path-less builtin is a row here too (it is the same index Help
// reads), and SPC cannot reach one — so both scans skip it
for (builtin_rows) |row| {
if (std.mem.eql(u8, row.path orelse continue, pfx)) return p.runBuiltin(row.cmd, p.active, "", null);
}
for (builtin_rows) |row| {
if (std.mem.startsWith(u8, row.path orelse continue, pfx)) {
p.leader_on = true;
return;
}
}
}
/// Enter raw tty. If the shell is at a prompt and the modal cursor sits on
/// the input line, move the shell's REAL cursor there via ghostty's
/// promptClickMove (arrow keys the shell understands) — dropping into tty
/// lands where you navigated. Requires OSC 133 cl=line (our bash rc).
fn enterTty(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const screen = pane.vt.screens.active;
if (pane.vt.cursorIsAtPrompt()) {
// the pin is a GRID position: convert the modal cursor's surface
// row back through the edit buffer
const goff: i32 = @intCast(screen.pages.scrollbar().offset);
const vp_row: i32 = pane.gridRow(pane.cur_row) - goff;
if (vp_row >= 0) {
if (screen.pages.pin(.{ .viewport = .{ .x = @intCast(@max(0, pane.cur_col)), .y = @intCast(vp_row) } })) |click_pin| {
const cursor_pin = screen.cursor.page_pin.*;
var pit = cursor_pin.promptIterator(.left_up, null);
if (pit.next()) |prompt_pin| {
if (!click_pin.before(prompt_pin)) {
const m = screen.promptClickMove(click_pin);
var i: usize = 0;
while (i < m.left) : (i += 1) p.emitWrite(id, "\x1b[D");
i = 0;
while (i < m.right) : (i += 1) p.emitWrite(id, "\x1b[C");
}
}
}
}
}
pane.mode = .tty;
pane.msel.active = false;
pane.vsel.active = false;
pane.nsel = 0; // raw tty: the program owns the pane, and its cursor is the shell's
pane.select = false;
pane.append_at = null;
pane.sticky_col = -1;
pane.pending = 0;
}
/// move focus to the nearest pane in `dir` of `from` (overlap-aware
/// nearest edge). `from` is the pane the builtin ran on, which is the
/// active one for a key but the CLICKED one for a name executed in a tag.
pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) void {
const a = p.rects[from];
var best: ?usize = null;
var best_d: i32 = 0;
for (p.panes, 0..) |slot, i| {
if (slot == null or i == from) continue;
const r = p.rects[i];
const vov = a.y < r.y + r.h and r.y < a.y + a.h;
const hov = a.x < r.x + r.w and r.x < a.x + a.w;
const ok = switch (dir) {
.left => r.x + r.w <= a.x and vov,
.right => r.x >= a.x + a.w and vov,
.up => r.y + r.h <= a.y and hov,
.down => r.y >= a.y + a.h and hov,
};
if (!ok) continue;
const d: i32 = switch (dir) {
.left => @as(i32, a.x) - @as(i32, r.x + r.w),
.right => @as(i32, r.x) - @as(i32, a.x + a.w),
.up => @as(i32, a.y) - @as(i32, r.y + r.h),
.down => @as(i32, r.y) - @as(i32, a.y + a.h),
};
if (best == null or d < best_d) {
best = i;
best_d = d;
}
}
if (best) |b| {
p.active = b;
// a count typed before the hop was meant for the pane you left
p.panes[b].?.pending = 0;
}
}
// ---- move-drag placement ----
const MovePlacement = struct {
preview_col: usize,
above_id: usize,
row: u16,
above_y: u16,
above_h: u16,
};
fn targetColumn(p: *Pardes, cur_x: u16) usize {
var tc: usize = if (p.ncol > 0) p.ncol - 1 else 0;
for (0..p.ncol) |c| {
if (cur_x >= p.col_x[c] and cur_x < p.col_x[c] + p.col_w[c]) {
tc = c;
break;
}
}
return tc;
}
fn splitRowForExtent(y: u16, h: u16, cur_y: u16) ?u16 {
if (h < 2) return null;
const min_each: u16 = if (h >= config.MINH * 2) config.MINH else 1;
const lo = y +| min_each;
const hi = y + h - min_each;
if (lo > hi) return y + h / 2;
return std.math.clamp(cur_y, lo, hi);
}
fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlacement {
const src = p.layoutFindTerm(id) orelse return null;
const tc = p.targetColumn(cur_x);
if (tc == src.col and p.col_n[src.col] == 1) return null;
if (tc == src.col) {
const sr = p.rects[id];
if (cur_y >= sr.y and cur_y < sr.y + sr.h) return null;
}
var heights: [MAX_PANES]u16 = @splat(0);
for (0..p.ncol) |c| {
for (0..p.col_n[c]) |k| {
const pid = p.col_terms[c][k];
heights[pid] = p.rects[pid].h;
}
}
if (p.col_n[src.col] > 1) {
const sib = if (src.idx > 0) p.col_terms[src.col][src.idx - 1] else p.col_terms[src.col][src.idx + 1];
heights[sib] +|= p.rects[id].h;
}
var y: u16 = TOPBAR_H;
var last: ?MovePlacement = null;
for (0..p.col_n[tc]) |k| {
const pid = p.col_terms[tc][k];
if (pid == id) continue;
const h = heights[pid];
const row = splitRowForExtent(y, h, cur_y) orelse {
y +|= h;
continue;
};
const placement: MovePlacement = .{
.preview_col = tc,
.above_id = pid,
.row = row,
.above_y = y,
.above_h = h,
};
last = placement;
if (cur_y < y + h) return placement;
y +|= h;
}
return last;
}
/// drop pane `id` below the pane under the cursor, converting on-screen
/// heights to weights so ONLY the split pane changes size
fn moveTerm(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void {
const placement = p.movePlacement(id, cur_x, cur_y) orelse return;
const src = p.layoutFindTerm(id) orelse return;
const source_multi = p.col_n[src.col] > 1;
var heights: [MAX_PANES]u16 = @splat(0);
for (0..p.ncol) |c| {
for (0..p.col_n[c]) |k| {
const pid = p.col_terms[c][k];
heights[pid] = p.rects[pid].h;
}
}
p.layoutRemove(id);
if (source_multi and src.col < p.ncol and p.col_n[src.col] > 0) {
const sib = if (src.idx > 0) p.col_terms[src.col][src.idx - 1] else p.col_terms[src.col][src.idx];
heights[sib] +|= p.rects[id].h;
}
const af = p.layoutFindTerm(placement.above_id) orelse return;
const upper_h = @max(1, placement.row -| placement.above_y);
const lower_h = @max(1, placement.above_h -| upper_h);
heights[placement.above_id] = upper_h;
heights[id] = lower_h;
p.layoutInsert(af.col, af.idx + 1, id);
p.setColumnWeights(af.col, &heights);
if (source_multi and src.col < p.ncol and src.col != af.col) p.setColumnWeights(src.col, &heights);
}
fn setColumnWeights(p: *Pardes, col: usize, heights: *const [MAX_PANES]u16) void {
if (col >= p.ncol) return;
for (0..p.col_n[col]) |k| {
const pid = p.col_terms[col][k];
if (p.panes[pid]) |pane| pane.vweight = @floatFromInt(@max(1, heights[pid]));
}
}
// ---- helix-modal normal mode ----
const PaneLines = struct {
lines: []const []const u8,
row0: i32, // absolute row of lines[0]
};
fn ensurePdfText(p: *Pardes, pane: *Pane) ![]const u8 {
if (comptime !pdf_enabled) return error.PdfDisabled;
const pv = &(pane.pdf orelse return error.NotPdf);
if (!pv.text_tried) {
pv.text_tried = true;
pv.text = pv.document.pageText(p.gpa, pv.page) catch &.{};
}
return pv.text;
}
/// The lines the cursor moves over, absolute rows. File: all content lines.
/// Terminal: the whole history+active grid with the edit buffer's lines
/// standing in for the rows it covers, so motions ride the scrollback and
/// the typed text alike. Scratch-arena backed.
/// (pub only for test/hxdiff.zig — the helix differential harness dumps
/// this surface as a tty case's final text.)
pub fn paneCursorLines(p: *Pardes, pane: *Pane) !PaneLines {
const arena = p.scratch.allocator();
if (pane.file) |*f| {
// straight off the line index: exact size (no ArrayList regrowth
// copying a 300k-entry table forward) and no second scan for the
// newlines the index already found. Identical to splitting the
// content — a file's line count is its newline count plus one.
const idx = try file_pane.lineIndex(pane.gpa, f);
const ls = try arena.alloc([]const u8, idx.len);
for (idx, 0..) |s, i| {
const e = if (i + 1 < idx.len) idx[i + 1] - 1 else f.content.len;
ls[i] = f.content[s..e];
}
return .{ .lines = ls, .row0 = 0 };
}
if (hasPdf(pane)) {
const text = try p.ensurePdfText(pane);
var ls: std.ArrayList([]const u8) = .empty;
var it = std.mem.splitScalar(u8, text, '\n');
while (it.next()) |line| try ls.append(arena, line);
return .{ .lines = ls.items, .row0 = 0 };
}
const rows = try term_pane.shellRows(p, pane);
// the buffer may sit below the dump's last row (the grid's trailing
// blanks are trimmed off), so run the loop to whichever ends later
var last = rows.len;
if (pane.ovl) |o| last = @max(last, @as(usize, @intCast(@max(0, o.row + o.rows))));
var ls: std.ArrayList([]const u8) = .empty;
var g: usize = 0;
while (g < last) : (g += 1) {
if (pane.ovl) |o| if (o.row >= 0 and g == @as(usize, @intCast(o.row))) {
var bit = std.mem.splitScalar(u8, o.text, '\n');
while (bit.next()) |ln| try ls.append(arena, ln);
g += @intCast(o.rows - 1);
continue;
};
try ls.append(arena, if (g < rows.len) rows[g] else "");
}
return .{ .lines = ls.items, .row0 = 0 };
}
fn toModalCursor(pane: *Pane, pl: PaneLines) modal.Cursor {
const r: i32 = pane.cur_row - pl.row0;
return .{ .row = @intCast(@max(0, r)), .col = @intCast(@max(0, pane.cur_col)) };
}
fn fromModalCursor(pane: *Pane, pl: PaneLines, c: modal.Cursor) void {
pane.cur_row = @as(i32, @intCast(c.row)) + pl.row0;
pane.cur_col = @intCast(c.col);
pane.cur_pinned = true;
}
// ---- helix range plumbing (see modal.zig "helix range engine") ----
// The pane's cursor + vsel cells render ONE helix gap range over the flat
// motion surface. Every motion builds the current range, transforms it the
// way the helix command would, and writes it back: normal mode REPLACES
// the selection with the motion's range, select mode (v) extends it via
// put_cursor. The differential suite (zig build hxdiff) pins all of this
// against a real helix, key for key.
/// the flat motion surface: file content as-is; terminals join the
/// cursor-lines dump (scratch-arena backed, same lifetime as pl)
fn flatSurface(p: *Pardes, pane: *Pane, pl: PaneLines) ![]const u8 {
if (pane.file) |f| return f.content;
if (hasPdf(pane)) return p.ensurePdfText(pane);
const arena = p.scratch.allocator();
var buf: std.ArrayList(u8) = .empty;
for (pl.lines, 0..) |ln, i| {
if (i > 0) try buf.append(arena, '\n');
try buf.appendSlice(arena, ln);
}
return buf.items;
}
/// modal.hxOff and modal.hxPos, answered from the file's LINE INDEX when
/// `text` is that file's content — which is exactly what flatSurface hands
/// back for a file pane, and so what every motion in a document goes
/// through. The modal pair has to scan the buffer for the same two numbers
/// (a newline count and a walk to the line start), and on a multi-MB file
/// those scans were the bulk of a keystroke.
///
/// The identity check is the whole safety argument: anything that is NOT
/// this file's content — a terminal's joined motion surface, an edit
/// buffer, a search haystack — falls through to the scan, where it is O(a
/// screenful) anyway. The two branches must agree exactly or the 481
/// differential and 561 parity cases say so; the arithmetic below is
/// hxOff/hxPos transcribed, with line i's terminator read off idx[i+1]-1
/// instead of searched for.
fn indexOf(pane: *Pane, text: []const u8) ?[]const usize {
const f = if (pane.file) |*ff| ff else return null;
if (text.ptr != f.content.ptr or text.len != f.content.len) return null;
return file_pane.lineIndex(pane.gpa, f) catch null;
}
fn paneOff(pane: *Pane, text: []const u8, c: modal.Cursor) usize {
const idx = indexOf(pane, text) orelse return modal.hxOff(text, c);
const row = @min(c.row, idx.len - 1);
const s = idx[row];
const e = if (row + 1 < idx.len) idx[row + 1] - 1 else text.len;
return @min(s + c.col, e);
}
/// modal.lineStartOffset, same contract (row past the end -> text.len)
fn paneLineStart(pane: *Pane, text: []const u8, row: usize) usize {
const idx = indexOf(pane, text) orelse return modal.lineStartOffset(text, row);
return if (row >= idx.len) text.len else idx[row];
}
fn panePos(pane: *Pane, text: []const u8, off: usize) modal.Cursor {
const idx = indexOf(pane, text) orelse return modal.hxPos(text, off);
const o = @min(off, text.len);
// the last line start at or before `o`; idx is sorted and idx[0] == 0,
// so upperBound never returns 0
const row = std.sort.upperBound(usize, idx, o, struct {
fn cmp(key: usize, item: usize) std.math.Order {
return std.math.order(key, item);
}
}.cmp) - 1;
return .{ .row = row, .col = o - idx[row] };
}
/// the current selection as a helix gap range over `text`, whose first
/// line is absolute row `row0` (0 for the motion surface and for file
/// content; a terminal's edit buffer starts wherever it was anchored)
fn paneRange(pane: *Pane, text: []const u8, row0: i32) modal.HxRange {
const c = paneOff(pane, text, .{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) });
if (pane.msel.active) {
// legacy line selection (file-search results highlight): linewise
const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0));
const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0));
const s = modal.lineStartOffset(text, r0);
const e = if (r1 + 1 >= modal.hxLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1);
return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) };
}
if (pane.vsel.active) return cellRange(text, pane.vsel.row - row0, pane.vsel.col, pane.cur_row - row0, pane.cur_col);
return .{ .anchor = c, .head = modal.nextGrapheme(text, c) };
}
/// a gap range from its two block-cursor CELLS — the arithmetic paneRange
/// does for cur/vsel, shared with the extra selections, which are stored
/// in exactly the same shape
fn cellRange(text: []const u8, arow: i32, acol: i32, hrow: i32, hcol: i32) modal.HxRange {
const a = modal.hxOff(text, .{ .row = @intCast(@max(0, arow)), .col = @intCast(@max(0, acol)) });
const c = modal.hxOff(text, .{ .row = @intCast(@max(0, hrow)), .col = @intCast(@max(0, hcol)) });
return cellOffRange(text, a, c);
}
/// the same, from the two cells' gap offsets
fn cellOffRange(text: []const u8, a: usize, c: usize) modal.HxRange {
if (a <= c) return .{ .anchor = a, .head = modal.nextGrapheme(text, c) };
return .{ .anchor = modal.nextGrapheme(text, a), .head = c };
}
/// the inverse: a gap range's cursor and anchor CELLS (equal for a bare
/// 1-wide cursor). setPaneRange's own conversion, factored out so the
/// extra selections write back through the same three lines.
fn rangeCells(text: []const u8, r: modal.HxRange) struct { cur: usize, anc: usize } {
if (r.head > r.anchor) return .{ .cur = modal.prevGrapheme(text, r.head), .anc = r.anchor };
if (r.head < r.anchor) return .{ .cur = r.head, .anc = modal.prevGrapheme(text, r.anchor) };
return .{ .cur = r.head, .anc = r.head };
}
/// write a helix range back into pane state. `explicit` marks user-intent
/// selections (v/x/X, terminal n/N, file-search n/N) — the acme chords
/// act only on those; motion residue stays implicit.
fn setPaneRange(pane: *Pane, pl: PaneLines, text: []const u8, r0: modal.HxRange, explicit: bool) void {
var r = r0;
if (r.anchor == r.head) r.head = modal.nextGrapheme(text, r.head); // min_width_1
const off = rangeCells(text, r);
const cc = panePos(pane, text, off.cur);
// a bare block cursor has both cells on the same offset — the common
// case by far — and this conversion is not free even indexed
const ac = if (off.anc == off.cur) cc else panePos(pane, text, off.anc);
pane.cur_row = @as(i32, @intCast(cc.row)) + pl.row0;
pane.cur_col = @intCast(cc.col);
pane.vsel = .{
.active = off.anc != off.cur or pane.select,
.row = @as(i32, @intCast(ac.row)) + pl.row0,
.col = @intCast(ac.col),
.explicit = explicit or pane.select,
};
pane.msel.active = false;
pane.nsel = 0; // writing ONE range means the selection IS that range
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.pending = 0;
pane.ensureCursorVisible();
}
// ---- the OTHER selections (helix Selection.ranges / primary_index) ----
// Two functions read and write the whole list; everything else in this
// file still speaks the single primary range, and replaySels below is what
// makes an ordinary key act at every cursor.
/// The whole selection as helix gap ranges over `text`, DOCUMENT ORDER
/// (pane.sels is kept that way, so this only has to slot the primary in).
/// Returns how many were written and which index is the primary.
fn paneRanges(pane: *Pane, text: []const u8, row0: i32, out: *[MAX_SELS]modal.HxRange) struct { n: usize, pri: usize } {
const pr = paneRange(pane, text, row0);
var n: usize = 0;
var pri: usize = 0;
var placed = false;
for (pane.sels[0..pane.nsel]) |s| {
const r = cellRange(text, s.arow - row0, s.acol, s.row - row0, s.col);
if (!placed and @min(pr.anchor, pr.head) <= @min(r.anchor, r.head)) {
pri = n;
out[n] = pr;
n += 1;
placed = true;
}
out[n] = r;
n += 1;
}
if (!placed) {
pri = n;
out[n] = pr;
n += 1;
}
return .{ .n = n, .pri = pri };
}
/// Write a whole selection back — helix's `Selection::new`: min-width-1,
/// sorted by start, overlapping ranges merged (the primary following its
/// range through a merge). `ranges[pri]` lands in the primary slot through
/// setPaneRange, so nothing downstream can tell it apart from a lone
/// cursor; the rest become pane.sels. `sticky` carries each range's own
/// j/k goal column, -1 for the ones that have none.
fn setPaneRanges(pane: *Pane, pl: PaneLines, text: []const u8, in: []const modal.HxRange, sticky: []const i32, pri0: usize, explicit: bool) void {
if (in.len == 0) return; // helix asserts non-empty; here it just means "no change"
var r: [MAX_SELS]modal.HxRange = undefined;
var st: [MAX_SELS]i32 = undefined;
var n: usize = @min(in.len, MAX_SELS);
var pri: usize = @min(pri0, n - 1);
for (in[0..n], 0..) |x, i| {
r[i] = x;
if (r[i].anchor == r[i].head) r[i].head = modal.nextGrapheme(text, r[i].head);
st[i] = if (i < sticky.len) sticky[i] else -1;
}
// insertion sort by start — n is tiny and usually already ordered
var i: usize = 1;
while (i < n) : (i += 1) {
var j = i;
while (j > 0 and @min(r[j].anchor, r[j].head) < @min(r[j - 1].anchor, r[j - 1].head)) : (j -= 1) {
std.mem.swap(modal.HxRange, &r[j], &r[j - 1]);
std.mem.swap(i32, &st[j], &st[j - 1]);
if (pri == j) pri = j - 1 else if (pri == j - 1) pri = j;
}
}
// merge overlaps (helix Range::overlaps + Range::merge, kept forward:
// a merged range takes the union and loses its direction only when the
// two disagree, which is what helix's else-branch does)
var k: usize = 0;
i = 1;
while (i < n) : (i += 1) {
const a = r[k];
const b = r[i];
const af = @min(a.anchor, a.head);
const at = @max(a.anchor, a.head);
const bf = @min(b.anchor, b.head);
const bt = @max(b.anchor, b.head);
if (af == bf or (at > bf and bt > af)) {
r[k] = if (a.anchor > a.head and b.anchor > b.head)
.{ .anchor = @max(a.anchor, b.anchor), .head = @min(a.head, b.head) }
else
.{ .anchor = @min(af, bf), .head = @max(at, bt) };
if (pri == i) pri = k;
if (st[k] < 0) st[k] = st[i];
continue;
}
k += 1;
r[k] = b;
st[k] = st[i];
if (pri == i) pri = k;
}
n = k + 1;
setPaneRange(pane, pl, text, r[pri], explicit);
pane.sticky_col = st[pri];
var w: usize = 0;
for (r[0..n], 0..) |x, idx| {
if (idx == pri) continue;
const c = rangeCells(text, x);
const cc = modal.hxPos(text, c.cur);
const ac = modal.hxPos(text, c.anc);
pane.sels[w] = .{
.row = @as(i32, @intCast(cc.row)) + pl.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + pl.row0,
.acol = @intCast(ac.col),
.sticky = st[idx],
};
w += 1;
}
pane.nsel = @intCast(w);
}
/// The helix keys that act on the selection LIST rather than on the text.
/// Each reads the whole list and writes a whole list back; none is a
/// motion, which is why Action.scope marks them exempt from per-range
/// replay. The goal columns are dropped on the way through — every
/// one of these is a fresh intent about WHERE the cursors are, the same
/// reason setPaneRange resets sticky_col.
fn multiSelAction(pane: *Pane, pl: PaneLines, text: []const u8, kind: normal_input.Multi, cnt: usize) void {
var rs: [MAX_SELS]modal.HxRange = undefined;
const got = paneRanges(pane, text, pl.row0, &rs);
const n = got.n;
const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
if (kind == .remove_primary) {
if (n < 2) return; // helix: "no selections remaining"
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
for (rs[0..n], 0..) |r, i| {
if (i == got.pri) continue;
out[m] = r;
m += 1;
}
// helix Selection::remove: the NEXT range takes over, or the
// previous one when the primary was last
return setPaneRanges(pane, pl, text, out[0..m], &.{}, @min(got.pri, m - 1), expl);
}
if (kind == .rotate_forward or kind == .rotate_backward) {
const step = cnt % n;
const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n;
return setPaneRanges(pane, pl, text, rs[0..n], &.{}, pri, expl);
}
if (kind == .merge) {
// helix merge_selections: first.merge(last) — the ranges are
// sorted, so that is simply the whole span
const lo = @min(rs[0].anchor, rs[0].head);
const hi = @max(rs[n - 1].anchor, rs[n - 1].head);
const rev = rs[0].anchor > rs[0].head and rs[n - 1].anchor > rs[n - 1].head;
const one: modal.HxRange = if (rev) .{ .anchor = hi, .head = lo } else .{ .anchor = lo, .head = hi };
return setPaneRanges(pane, pl, text, &.{one}, &.{}, 0, expl);
}
if (kind == .merge_consecutive) {
// ranges that TOUCH become one; setPaneRanges already merges the
// ones that overlap, so widening each by a grapheme says exactly
// "consecutive counts as overlapping" and nothing else
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
var pri: usize = 0;
for (rs[0..n], 0..) |r, i| {
if (m > 0 and @min(r.anchor, r.head) == @max(out[m - 1].anchor, out[m - 1].head)) {
const lo = @min(@min(out[m - 1].anchor, out[m - 1].head), @min(r.anchor, r.head));
const hi = @max(@max(out[m - 1].anchor, out[m - 1].head), @max(r.anchor, r.head));
out[m - 1] = .{ .anchor = lo, .head = hi };
if (i == got.pri) pri = m - 1;
continue;
}
if (i == got.pri) pri = m;
out[m] = r;
m += 1;
}
return setPaneRanges(pane, pl, text, out[0..m], &.{}, pri, expl);
}
if (kind == .split_newline) {
// helix selection::split_on_newline — one range per line the
// selection covers, the newlines themselves left out
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
for (rs[0..n]) |r| {
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
if (from == to) {
if (m < MAX_SELS) {
out[m] = r;
m += 1;
}
continue;
}
var start = from;
while (start < to and m < MAX_SELS) {
const eol = modal.hxLineEndIdx(text, modal.hxLineOf(text, start));
if (eol >= to) {
out[m] = .{ .anchor = start, .head = to };
m += 1;
break;
}
out[m] = .{ .anchor = start, .head = eol };
m += 1;
start = eol + 1;
}
}
if (m == 0) return;
return setPaneRanges(pane, pl, text, out[0..m], &.{}, 0, true); // helix keeps primary 0
}
if (kind == .trim) {
// helix trim_selections: whitespace off both ends; ranges that are
// empty or all whitespace are dropped entirely
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
for (rs[0..n]) |r| {
var from = @min(r.anchor, r.head);
var to = @max(r.anchor, r.head);
while (from < to and std.ascii.isWhitespace(text[from])) from += 1;
while (to > from and std.ascii.isWhitespace(text[to - 1])) to -= 1;
if (from >= to) continue;
out[m] = if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to };
m += 1;
}
if (m == 0) { // helix: collapse_selection + keep_primary_selection
const c = modal.hxCursor(text, rs[got.pri]);
return setPaneRange(pane, pl, text, .{ .anchor = c, .head = c }, false);
}
// helix: the first survivor that OVERLAPS the old primary, else the last
const pf = @min(rs[got.pri].anchor, rs[got.pri].head);
const pt = @max(rs[got.pri].anchor, rs[got.pri].head);
var pri = m - 1;
for (out[0..m], 0..) |r, i| {
const f = @min(r.anchor, r.head);
const t = @max(r.anchor, r.head);
if (f == pf or (t > pf and pt > f)) {
pri = i;
break;
}
}
return setPaneRanges(pane, pl, text, out[0..m], &.{}, pri, expl);
}
// C / Alt-C — helix copy_selection_on_line, a copy of each range on the
// next/previous line that is long enough to hold its columns.
// ponytail: BYTE columns, not helix's visual ones, so a TAB counts as
// one column here. Everything else in this file measures the same way
// (hscroll, the mouse, the renderer's gutter), and fixing it means
// teaching all of them tab stops at once.
const below = kind == .copy_below;
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
var pri: usize = 0;
const nlines = modal.hxLineCount(text);
for (rs[0..n], 0..) |r, ri| {
const is_pri = ri == got.pri;
// head-exclusive: back the leading end off onto its own cell
const hp = modal.hxPos(text, if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head);
const ap = modal.hxPos(text, if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor));
const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1;
if (m >= MAX_SELS) break;
if (is_pri) pri = m;
out[m] = r;
m += 1;
var made: usize = 0;
var k: usize = 0;
while (made < cnt and m < MAX_SELS) : (k += 1) {
const d = (k + 1) * height;
const arow = if (below) ap.row + d else ap.row -| d;
const hrow = if (below) hp.row + d else hp.row -| d;
if (arow >= nlines or hrow >= nlines) break;
const a2 = modal.hxOff(text, .{ .row = arow, .col = ap.col });
const h2 = modal.hxOff(text, .{ .row = hrow, .col = hp.col });
// a line too short to reach the column is skipped, not clamped
if (modal.hxPos(text, a2).col == ap.col and modal.hxPos(text, h2).col == hp.col) {
if (is_pri) pri = m;
out[m] = modal.hxPutCursor(text, .{ .anchor = a2, .head = a2 }, h2, true);
m += 1;
made += 1;
}
if (arow == 0 and hrow == 0) break;
}
}
setPaneRanges(pane, pl, text, out[0..m], &.{}, pri, expl);
}
// ---- `s` / `S`: the selection LIST from a regex ----
// The other two list-making keys, and the only ones that need a pattern
// typed first. They reuse the `/` input wholesale (startSearch — the tag
// tail IS the prompt) and differ from it in one thing: the pattern is
// re-applied on every keystroke, so the selection is the preview.
/// helix `s` / `S`: arm the tag input for a regex, remembering the
/// selection it is about to rewrite. Nothing moves yet — every keystroke
/// below re-derives the preview from this snapshot, and Enter simply stops
/// while Esc puts the snapshot back.
fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void {
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
const got = paneRanges(pane, text, pl.row0, &pane.sel_snap);
pane.nsel_snap = @intCast(got.n);
pane.sel_snap_pri = @intCast(got.pri);
pane.sel_snap_expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
p.startSearch(pane, if (split) config.split_marker else config.select_marker);
}
/// The pattern an armed `s`/`S` input holds right now, and which of the two
/// it is — read back off the MARKER, exactly the way submitSearch decides
/// which search is running. Null for `/`, Find, Grep and Rename.
fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } {
if (!pane.search_edit or pane.nsel_snap == 0) return null;
const tail = pane.tag_tail.items;
const armed = tail[@min(pane.search_at, tail.len)..];
const split = std.mem.startsWith(u8, armed, config.split_marker);
if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null;
const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null;
return .{ .pat = armed[slash + 1 ..], .split = split };
}
/// Put the selection back the way `s`/`S` found it and then, if `pat`
/// compiles and hits, rewrite it: helix's select_on_matches (every match
/// INSIDE each range becomes a range) and split_on_matches (each range
/// becomes the pieces BETWEEN its matches).
///
/// Anything that yields nothing — an empty pattern, one that will not
/// compile, one that does not match — leaves the snapshot standing, which
/// is helix's "nothing selected" and also what makes typing a pattern one
/// character at a time bearable: every prefix of it is one of those.
///
/// ponytail: MAX_SELS ranges, and matches past that are dropped rather
/// than growing the list — the ceiling the whole selection model has.
/// ponytail: mvzr searches from each match's end, so `^` and `$` assert
/// against THAT position rather than against a line the way helix's
/// multi_line regex does, and `.` matches a newline like any other byte.
/// Both are waived cases; `[^\n]` is the workaround for the second.
fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void {
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
const snap = pane.sel_snap[0..pane.nsel_snap];
var out: [MAX_SELS]modal.HxRange = undefined;
var m: usize = 0;
if (pat.len > 0) if (mvzr.compile(pat)) |re| {
// helix smart-case: a pattern with no uppercase in it matches
// case-blind. mvzr has no such flag — "lowercase your string" is
// its own advice — and ASCII folding is byte for byte, so a
// lowercased copy of the surface has exactly the same offsets.
var hay_all = text;
if (for (pat) |c| {
if (std.ascii.isUpper(c)) break false;
} else true) {
const low = p.scratch.allocator().dupe(u8, text) catch return;
for (low) |*c| c.* = std.ascii.toLower(c.*);
hay_all = low;
}
for (snap) |r| {
const from = @min(r.anchor, r.head);
const to = @min(@max(r.anchor, r.head), text.len);
if (from >= to) continue;
const hay = hay_all[from..to];
var at: usize = 0;
var piece = from; // split: where the next piece begins
while (at < hay.len and m < MAX_SELS) {
const hit_at = re.matchPos(at, hay) orelse break;
if (split) {
out[m] = .{ .anchor = piece, .head = from + hit_at.start };
m += 1;
piece = from + hit_at.end;
} else if (from + hit_at.start != to) {
// a match sitting right off the END of the range is
// dropped (helix: what `\b` and empty matches produce
// there), everything else becomes a range
out[m] = .{ .anchor = from + hit_at.start, .head = from + hit_at.end };
m += 1;
}
// an empty match would otherwise never advance
at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1;
}
if (split and piece < to and m < MAX_SELS) {
out[m] = .{ .anchor = piece, .head = to };
m += 1;
}
}
};
if (m == 0) {
// the text CAN move under an armed prompt (a tag chord runs a
// builtin), and these are raw offsets into the surface as it was
for (snap) |*r| {
r.anchor = @min(r.anchor, text.len);
r.head = @min(r.head, text.len);
}
return setPaneRanges(pane, pl, text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl);
}
setPaneRanges(pane, pl, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO)
}
/// Pane keeps compact codepoints for dump/layout stability; this pair is
/// the only bridge to the parser's typed state. Recognition never reads
/// these representation fields directly.
fn paneNormalState(pane: *const Pane) normal_input.State {
const prefix: normal_input.Prefix = if (pane.pending == config.goto_prefix)
.goto
else if (pane.pending == config.view_prefix)
.view
else if (pane.pending == config.match_prefix)
.match
else if (pane.pending == config.find_char_fwd)
.find_fwd
else if (pane.pending == config.find_char_back)
.find_back
else if (pane.pending == config.till_char_fwd)
.till_fwd
else if (pane.pending == config.till_char_back)
.till_back
else if (pane.pending == config.replace_prefix)
.replace
else if (pane.pending == config.next_prefix)
.next
else if (pane.pending == config.prev_prefix)
.prev
else
.none;
const match_sub: normal_input.MatchSub = if (pane.pending2 == config.match_inside)
.inside
else if (pane.pending2 == config.match_around)
.around
else if (pane.pending2 == config.surround_add)
.surround_add
else if (pane.pending2 == config.surround_replace)
.surround_replace
else if (pane.pending2 == config.surround_delete)
.surround_delete
else
.none;
return .{
.count = pane.count,
.prefix = prefix,
.match_sub = match_sub,
.held_char = pane.pending_ch,
};
}
fn putPaneNormalState(pane: *Pane, state: normal_input.State) void {
pane.count = state.count;
pane.pending = switch (state.prefix) {
.none => 0,
.goto => config.goto_prefix,
.view => config.view_prefix,
.match => config.match_prefix,
.find_fwd => config.find_char_fwd,
.find_back => config.find_char_back,
.till_fwd => config.till_char_fwd,
.till_back => config.till_char_back,
.replace => config.replace_prefix,
.next => config.next_prefix,
.prev => config.prev_prefix,
};
pane.pending2 = switch (state.match_sub) {
.none => 0,
.inside => config.match_inside,
.around => config.match_around,
.surround_add => config.surround_add,
.surround_replace => config.surround_replace,
.surround_delete => config.surround_delete,
};
pane.pending_ch = state.held_char;
}
/// Everything one keystroke may CONSUME on the way through the modal
/// handler. A key means the same thing at every cursor, so the replay puts
/// all of it back before each pass and keeps whatever the PRIMARY's pass
/// left. (sticky_col is deliberately absent: it is per-range, and rides
/// along in SelRange.sticky instead.)
const KeyState = struct {
mode: Mode,
select: bool,
count: u32,
pending: u21,
pending2: u21,
pending_ch: u21,
find_op: u8,
find_ch: u21,
append_at: @FieldType(Pane, "append_at"),
fn of(pane: *Pane) KeyState {
return .{
.mode = pane.mode,
.select = pane.select,
.count = pane.count,
.pending = pane.pending,
.pending2 = pane.pending2,
.pending_ch = pane.pending_ch,
.find_op = pane.find_op,
.find_ch = pane.find_ch,
.append_at = pane.append_at,
};
}
fn into(s: KeyState, pane: *Pane) void {
pane.mode = s.mode;
pane.select = s.select;
pane.count = s.count;
pane.pending = s.pending;
pane.pending2 = s.pending2;
pane.pending_ch = s.pending_ch;
pane.find_op = s.find_op;
pane.find_ch = s.find_ch;
pane.append_at = s.append_at;
}
};
/// what a replayed key does at each cursor
const Replay = union(enum) {
normal: normal_input.Action,
insert: Key,
};
/// Run one keystroke at EVERY cursor, by replaying the single-selection
/// handler once per range. This IS the multiple-cursor mechanism, and it
/// is why one cursor costs nothing: with `nsel == 0` nobody calls it, and
/// the handler underneath is the same code the 800 differential cases pin.
///
/// Two rules make the replay legal without helix's change-mapping:
/// * ranges are visited LAST FIRST, so an edit never disturbs the
/// row/col of a range still waiting its turn — everything it touches
/// is below.
/// * a finished pass's result is recorded as a distance from the END of
/// the surface, which an edit strictly before it cannot change (the
/// text and the position shift by exactly the same amount).
fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void {
const id = p.active;
const serial = pane.serial;
// the whole selection in pane coordinates, document order. pane.sels
// is already ordered, so this only slots the primary into place.
var list: [MAX_SELS]SelRange = undefined;
var n: usize = 0;
var pri: usize = 0;
const prim: SelRange = .{
.row = pane.cur_row,
.col = pane.cur_col,
.arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row,
.acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col,
.sticky = pane.sticky_col,
};
const pr = selStart(prim);
var placed = false;
for (pane.sels[0..pane.nsel]) |s| {
const sr = selStart(s);
if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) {
pri = n;
list[n] = prim;
n += 1;
placed = true;
}
list[n] = s;
n += 1;
}
if (!placed) {
pri = n;
list[n] = prim;
n += 1;
}
const saved = KeyState.of(pane);
const explicit = pane.vsel.explicit;
var after = saved;
var after_expl = explicit;
// each pass's result: cursor and anchor cells as distances from the
// end of the surface text, plus the range's own j/k goal column
var res: [MAX_SELS]struct { cur: usize, anc: usize, sticky: i32 } = undefined;
p.multi_on = true;
p.multi_stop = false;
var passes: usize = 0;
var i: usize = n;
while (i > 0) {
i -= 1;
p.multi_first = passes == 0;
passes += 1;
saved.into(pane);
pane.nsel = 0; // the handler underneath sees ONE selection
pane.cur_row = list[i].row;
pane.cur_col = list[i].col;
pane.vsel = .{
.active = list[i].arow != list[i].row or list[i].acol != list[i].col or pane.select,
.row = list[i].arow,
.col = list[i].acol,
.explicit = explicit,
};
pane.msel.active = false;
pane.sticky_col = list[i].sticky;
switch (what) {
.normal => |normal_action| p.executeNormalAction(pane, normal_action),
.insert => |insert_key| p.insertKey(pane, insert_key),
}
// the stop check comes FIRST: the pass that set it may have freed
// this very pane (a builtin closing it), so nothing below may read
// through the pointer
if (p.multi_stop) break;
if (i == pri) {
after = KeyState.of(pane);
after_expl = pane.vsel.explicit;
}
const pl = p.paneCursorLines(pane) catch {
p.multi_stop = true; // out of memory mid-replay: collapse, don't guess
break;
};
const text = p.flatSurface(pane, pl) catch {
p.multi_stop = true;
break;
};
const co = modal.hxOff(text, .{ .row = @intCast(@max(0, pane.cur_row - pl.row0)), .col = @intCast(@max(0, pane.cur_col)) });
const ao = if (pane.vsel.active)
modal.hxOff(text, .{ .row = @intCast(@max(0, pane.vsel.row - pl.row0)), .col = @intCast(@max(0, pane.vsel.col)) })
else
co;
res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = pane.sticky_col };
}
p.multi_on = false;
p.multi_first = false;
if (p.multi_stop) {
// the pass reached outside the buffer (a builtin, a language
// query) and may have closed or reused the pane it ran on: drop
// back to one cursor rather than replaying it n more times
p.multi_stop = false;
const pn = p.panes[id] orelse return;
if (pn.serial == serial) pn.nsel = 0;
return;
}
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
var rs: [MAX_SELS]modal.HxRange = undefined;
var st: [MAX_SELS]i32 = undefined;
for (res[0..n], 0..) |r, k| {
rs[k] = cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len));
st[k] = r.sticky;
}
setPaneRanges(pane, pl, text, rs[0..n], st[0..n], pri, after_expl);
after.into(pane);
pane.ensureCursorVisible(); // the view follows the PRIMARY, not the last pass
}
/// a range's start CELL (document order key) — the smaller of its two ends
fn selStart(s: SelRange) struct { row: i32, col: i32 } {
if (s.arow < s.row or (s.arow == s.row and s.acol < s.col)) return .{ .row = s.arow, .col = s.acol };
return .{ .row = s.row, .col = s.col };
}
/// The last line a goto may land on: helix skips the empty trailing line.
/// Called from the three `g`/`G` Action branches that need it and nowhere
/// else — it used to be eager at the top of body-normal execution, so every
/// keystroke of every kind paid a full count of the buffer's newlines.
/// "Does the buffer end in a newline" is the same question as the walk to
/// the last line start that stood here, and it is one byte instead of a
/// second pass.
fn maxLine(text: []const u8) usize {
const nl = modal.hxLineCount(text);
return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1;
}
/// point-target motion: collapse there (extend in select mode)
fn pointMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, target: usize) void {
setPaneRange(pane, pl, text, modal.hxPutCursor(text, range, target, pane.select), false);
}
/// word motions select their traversed span (extend mode: head only)
fn wordMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, cnt: usize, target: modal.WordTarget) void {
const wr = modal.hxWordMove(text, range, cnt, target);
const res = if (pane.select) modal.hxPutCursor(text, range, modal.hxCursor(text, wr), true) else wr;
setPaneRange(pane, pl, text, res, false);
}
/// f/t/F/T: anchor at the old cursor cell, head on the hit (not found: no move)
fn findMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, ch: u21, fwd: bool, till: bool, cnt: usize) void {
if (ch > 0x7f) return; // ponytail: ASCII targets only (byte columns)
const cur = modal.hxCursor(text, range);
const t = modal.hxFindTarget(text, cur, @intCast(ch), fwd, till, cnt) orelse return;
const res = if (pane.select)
modal.hxPutCursor(text, range, t, true)
else
modal.hxPutCursor(text, .{ .anchor = cur, .head = cur }, t, true);
setPaneRange(pane, pl, text, res, false);
}
/// j/k and friends: sticky goal column, clamped onto short lines' newline
fn verticalMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, down: bool, cnt: usize) void {
const cur = modal.hxCursor(text, range);
const pos = panePos(pane, text, cur);
const goal: usize = if (pane.sticky_col >= 0) @intCast(pane.sticky_col) else pos.col;
// modal.hxVertTarget with the row we already have and the indexed
// offset conversion — it would otherwise recount the buffer's newlines
// and walk to the target line, two more full passes per j/k
const t = if (indexOf(pane, text)) |idx| blk: {
const nline = if (down) @min(pos.row + @max(1, cnt), idx.len - 1) else pos.row -| @max(1, cnt);
break :blk paneOff(pane, text, .{ .row = nline, .col = goal });
} else modal.hxVertTarget(text, cur, down, cnt, goal);
// extend mode never walks onto the empty trailing line (helix)
if (pane.select and t == text.len and text.len > 0 and text[text.len - 1] == '\n') return;
setPaneRange(pane, pl, text, modal.hxPutCursor(text, range, t, pane.select), false);
pane.sticky_col = @intCast(goal);
}
/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows
fn halfPageMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, down: bool) void {
const half: i32 = @max(1, @divTrunc(@as(i32, pane.rows), 2));
pane.scrollBy(if (down) half else -half);
verticalMove(pane, pl, text, range, down, @intCast(half));
}
/// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift
/// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0
fn scrollViewMove(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, delta: i32) void {
const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2));
pane.scrollBy(delta);
const top = pane.scroll();
const last_row: i32 = @intCast((if (indexOf(pane, text)) |idx| idx.len else modal.hxLineCount(text)) - 1);
const cur = modal.hxCursor(text, range);
if (delta > 0) {
const snap: i32 = @max(0, @min(top + margin, last_row));
const head = paneLineStart(pane, text, @intCast(snap));
if (head <= cur) return;
const anchor = if (pane.select) range.anchor else head;
setPaneRange(pane, pl, text, .{ .anchor = anchor, .head = head }, false);
} else {
const snap: i32 = @max(0, @min(top + @as(i32, pane.rows) - margin - 1, last_row));
const head = paneLineStart(pane, text, @intCast(snap));
if (head >= cur) return;
const anchor = if (pane.select) range.anchor else head;
setPaneRange(pane, pl, text, .{ .anchor = anchor, .head = head }, false);
}
}
/// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window)
fn gotoWindow(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, which: enum { top, center, bottom }, cnt: usize) void {
const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2));
const top = pane.scroll();
const last_row: i32 = @intCast((if (indexOf(pane, text)) |idx| idx.len else modal.hxLineCount(text)) - 1);
const last_vis: i32 = @min(@as(i32, pane.rows) - 1, last_row - top);
const n: i32 = @intCast(cnt - 1);
var vline: i32 = switch (which) {
.top => top + margin + n,
.center => top + @divTrunc(last_vis, 2),
.bottom => top + last_vis - (margin + n),
};
vline = @max(vline, top + margin);
vline = @min(vline, top + last_vis - margin);
const row: i32 = std.math.clamp(vline, 0, last_row);
pointMove(pane, pl, text, range, paneLineStart(pane, text, @intCast(row)));
}
/// helix Range::line_range — the inclusive line span a range covers
fn rangeLineSpan(text: []const u8, r: modal.HxRange) struct { start: usize, end: usize } {
const from = @min(r.anchor, r.head);
const to = @max(r.anchor, r.head);
const to_adj = if (from == to) to else @max(modal.prevGrapheme(text, to), from);
return .{ .start = modal.hxLineOf(text, from), .end = modal.hxLineOf(text, to_adj) };
}
fn lineStartOrEof(text: []const u8, line: usize) usize {
if (line >= modal.hxLineCount(text)) return text.len;
return modal.lineStartOffset(text, line);
}
/// helix `x` extend_line_below: full lines incl. the newline, cursor ON
/// the last one's '\n'; an already-line-bounded selection grows downward
fn lineSelect(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange, cnt: usize) void {
const span = rangeLineSpan(text, range);
const start = modal.lineStartOffset(text, span.start);
const end = lineStartOrEof(text, span.end + 1);
const full = @min(range.anchor, range.head) == start and @max(range.anchor, range.head) == end;
const head = lineStartOrEof(text, span.end + cnt + @intFromBool(full));
setPaneRange(pane, pl, text, .{ .anchor = start, .head = head }, true);
}
/// helix `X` extend_to_line_bounds (direction kept)
fn lineBoundsSelect(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange) void {
const span = rangeLineSpan(text, range);
const start = modal.lineStartOffset(text, span.start);
const end = lineStartOrEof(text, span.end + 1);
const r: modal.HxRange = if (range.head < range.anchor)
.{ .anchor = end, .head = start }
else
.{ .anchor = start, .head = end };
setPaneRange(pane, pl, text, r, true);
}
/// helix `Alt-x` shrink_to_line_bounds (single-line selections untouched)
fn shrinkSelToLineBounds(pane: *Pane, pl: PaneLines, text: []const u8, range: modal.HxRange) void {
const span = rangeLineSpan(text, range);
if (span.start == span.end) return;
const from = @min(range.anchor, range.head);
const to = @max(range.anchor, range.head);
var start = modal.lineStartOffset(text, span.start);
var end = lineStartOrEof(text, span.end + 1);
if (start != from) start = lineStartOrEof(text, span.start + 1);
if (end != to) end = modal.lineStartOffset(text, span.end);
const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
const r: modal.HxRange = if (range.head < range.anchor)
.{ .anchor = end, .head = start }
else
.{ .anchor = start, .head = end };
setPaneRange(pane, pl, text, r, expl);
}
/// Keys that are about the selection LIST, or about the session rather
/// than the text: they act ONCE however many cursors there are. The
/// multi-cursor family rewrites the list wholesale, and the rest would
/// either fight the replay (Esc, undo) or fire n times (`:`, `/`, n/N, SPC).
///
fn handleNormal(p: *Pardes, pane: *Pane, key: Key) void {
var state = paneNormalState(pane);
const parsed = normal_input.parse(&state, normalInput(key));
putPaneNormalState(pane, state);
const semantic = switch (parsed) {
.pending, .ignored, .unbound => return,
.action => |value| value,
};
if (pane.nsel == 0 or semantic.scope() == .once)
return p.executeNormalAction(pane, semantic);
p.replaySels(pane, .{ .normal = semantic });
}
/// Text-pane adapter for the semantic BODY-NORMAL vocabulary. Parsing is
/// complete before this function runs; this switch reads document state
/// only to execute the already-recognized action.
fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: normal_input.Action) void {
pane.pinCursor();
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
const lines = pl.lines;
const range = paneRange(pane, text, pl.row0);
const cur = modal.hxCursor(text, range);
switch (semantic) {
.escape => {
pane.select = false;
return p.runBuiltin(.Toggleterm, p.active, "", null);
},
.goto => |go| switch (go.target) {
.file_start => {
const line = if (go.explicit_count) @min(@as(usize, go.count) - 1, maxLine(text)) else 0;
return pointMove(pane, pl, text, range, modal.lineStartOffset(text, line));
},
.last_line => return pointMove(pane, pl, text, range, modal.lineStartOffset(text, maxLine(text))),
.line_start => return pointMove(pane, pl, text, range, modal.lineStartOffset(text, modal.hxLineOf(text, cur))),
.line_end => {
const line = modal.hxLineOf(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(pane, pl, text, range, @max(ls, modal.prevGrapheme(text, modal.hxLineEndIdx(text, line))));
},
.first_nonws => {
const line = modal.hxLineOf(text, cur);
const ls = modal.lineStartOffset(text, line);
const slice = text[ls..modal.hxLineEndIdx(text, line)];
const nw = modal.firstNonWs(slice);
if (nw == slice.len) return;
return pointMove(pane, pl, text, range, ls + nw);
},
.line_down => return verticalMove(pane, pl, text, range, true, go.count),
.line_up => return verticalMove(pane, pl, text, range, false, go.count),
.column => {
const line = modal.hxLineOf(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(pane, pl, text, range, @min(ls + (@as(usize, go.count) - 1), modal.hxLineEndIdx(text, line)));
},
.view_top => return gotoWindow(pane, pl, text, range, .top, go.count),
.view_center => return gotoWindow(pane, pl, text, range, .center, go.count),
.view_bottom => return gotoWindow(pane, pl, text, range, .bottom, go.count),
},
.view => |view| switch (view) {
.top => {
pane.scrollBy(pane.cur_row - pane.scroll());
pane.ensureCursorVisible();
},
.center => {
pane.scrollBy(pane.cur_row - (pane.scroll() + @divTrunc(@as(i32, pane.rows), 2) - 1));
pane.ensureCursorVisible();
},
.bottom => {
pane.scrollBy(pane.cur_row - (pane.scroll() + @as(i32, pane.rows) - 1));
pane.ensureCursorVisible();
},
.scroll_down => return scrollViewMove(pane, pl, text, range, 1),
.scroll_up => return scrollViewMove(pane, pl, text, range, -1),
},
.find => |find| {
const op: u8 = switch (find.kind) {
.forward => @intCast(config.find_char_fwd),
.backward => @intCast(config.find_char_back),
.till_forward => @intCast(config.till_char_fwd),
.till_backward => @intCast(config.till_char_back),
};
pane.find_op = op;
pane.find_ch = find.char;
return findMove(
pane,
pl,
text,
range,
find.char,
find.kind == .forward or find.kind == .till_forward,
find.kind == .till_forward or find.kind == .till_backward,
find.count,
);
},
.replace_char => |char| return p.normalReplaceChar(pane, char),
.match_bracket => {
const mc = modal.matchBracket(lines, modal.hxPos(text, cur)) orelse return;
return pointMove(pane, pl, text, range, modal.hxOff(text, mc));
},
.textobject => |object| return p.textobjectSelect(pane, pl, object.char, object.around),
.surround_add => |char| return p.surroundAdd(pane, char),
.surround_delete => |char| return p.surroundDelete(pane, pl, char),
.surround_replace => |replace| return p.surroundReplace(pane, pl, replace.from, replace.to),
.paragraph => |paragraph| {
const r2 = modal.hxParaMove(text, range, paragraph.count, paragraph.direction == .forward, pane.select);
return setPaneRange(pane, pl, text, r2, false);
},
.add_newline => |newline| return p.addNewline(pane, newline.direction == .forward, newline.count),
.diagnostic => |diagnostic| {
const fwd = diagnostic.direction == .forward;
if (!diagnostic.endpoint) {
if (output_pane.resultsFrom(p, pane, .{ .query = .diagnostics }) and
p.searchStep(p.active, if (fwd) 1 else -1)) return;
return p.lspRequest(p.active, .diagnostics, "");
}
if (!output_pane.resultsFrom(p, pane, .{ .query = .diagnostics }))
return p.lspRequest(p.active, .diagnostics, "");
if (!fwd) {
pane.search_row = null;
_ = p.searchStep(p.active, 1);
return;
}
const rp = p.panes[pane.search_pane orelse return] orelse return;
const rf = rp.file orelse return;
pane.search_row = std.mem.count(u8, rf.content, "\n");
_ = p.searchStep(p.active, -1);
},
.move => |move| switch (move.motion) {
.left => {
var target = cur;
for (0..move.count) |_| target = modal.prevGrapheme(text, target);
return pointMove(pane, pl, text, range, target);
},
.right => {
var target = cur;
for (0..move.count) |_| target = modal.nextGrapheme(text, target);
return pointMove(pane, pl, text, range, target);
},
.down => return verticalMove(pane, pl, text, range, true, move.count),
.up => return verticalMove(pane, pl, text, range, false, move.count),
.next_word_start => return wordMove(pane, pl, text, range, move.count, .next_word_start),
.prev_word_start => return wordMove(pane, pl, text, range, move.count, .prev_word_start),
.next_word_end => return wordMove(pane, pl, text, range, move.count, .next_word_end),
.next_long_word_start => return wordMove(pane, pl, text, range, move.count, .next_long_word_start),
.prev_long_word_start => return wordMove(pane, pl, text, range, move.count, .prev_long_word_start),
.next_long_word_end => return wordMove(pane, pl, text, range, move.count, .next_long_word_end),
},
.repeat_find => |count| {
if (pane.find_op == 0 or pane.find_ch > 0x7f) return;
const fwd = pane.find_op == config.find_char_fwd or pane.find_op == config.till_char_fwd;
const till = pane.find_op == config.till_char_fwd or pane.find_op == config.till_char_back;
var repeated = range;
var moved = false;
for (0..count) |_| {
const cc = modal.hxCursor(text, repeated);
const target = modal.hxFindTarget(text, cc, @intCast(pane.find_ch), fwd, till, 1) orelse break;
repeated = if (pane.select)
modal.hxPutCursor(text, repeated, target, true)
else
modal.hxPutCursor(text, .{ .anchor = cc, .head = cc }, target, true);
moved = true;
}
if (!moved) return;
return setPaneRange(pane, pl, text, repeated, false);
},
.line => |line_kind| switch (line_kind) {
.start => return pointMove(pane, pl, text, range, modal.lineStartOffset(text, modal.hxLineOf(text, cur))),
.end => {
const line = modal.hxLineOf(text, cur);
const ls = modal.lineStartOffset(text, line);
return pointMove(pane, pl, text, range, @max(ls, modal.prevGrapheme(text, modal.hxLineEndIdx(text, line))));
},
.first_nonws => {
const line = modal.hxLineOf(text, cur);
const ls = modal.lineStartOffset(text, line);
const slice = text[ls..modal.hxLineEndIdx(text, line)];
const nw = modal.firstNonWs(slice);
if (nw == slice.len) return;
return pointMove(pane, pl, text, range, ls + nw);
},
},
.goto_line => |go| {
if (!go.explicit) return;
const line = @min(@as(usize, go.count) - 1, maxLine(text));
return pointMove(pane, pl, text, range, modal.lineStartOffset(text, line));
},
.page => |page| switch (page.kind) {
// Counts were parsed historically but these four text view
// actions intentionally move exactly one viewport unit.
.half_down => return halfPageMove(pane, pl, text, range, true),
.half_up => return halfPageMove(pane, pl, text, range, false),
.down => return scrollViewMove(pane, pl, text, range, @as(i32, pane.rows)),
.up => return scrollViewMove(pane, pl, text, range, -@as(i32, pane.rows)),
},
.insert => |insert| {
const where: InsertAt = switch (insert.kind) {
.at => .at,
.append => .append,
.line_start => .line_start,
.line_end => .line_end,
.open_below => .open_below,
.open_above => .open_above,
};
return p.enterInsert(pane, where, insert.count);
},
.select => |select| switch (select.kind) {
.mode => {
if (pane.select) {
pane.select = false;
} else {
pane.select = true;
if (pane.msel.active) {
setPaneRange(pane, pl, text, range, true);
} else if (!pane.vsel.active) {
pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = true };
} else {
pane.vsel.explicit = true;
}
}
pane.cur_pinned = true;
},
.line => return lineSelect(pane, pl, text, range, select.count),
.line_bounds => return lineBoundsSelect(pane, pl, text, range),
.shrink_to_line_bounds => return shrinkSelToLineBounds(pane, pl, text, range),
.collapse => return setPaneRange(pane, pl, text, .{ .anchor = cur, .head = cur }, false),
.flip => {
const explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
return setPaneRange(pane, pl, text, .{ .anchor = range.head, .head = range.anchor }, explicit);
},
.all => return setPaneRange(pane, pl, text, .{ .anchor = 0, .head = text.len }, false),
},
.multi => |multi| {
if (multi.kind == .keep_primary) {
pane.nsel = 0;
return;
}
return multiSelAction(pane, pl, text, multi.kind, multi.count);
},
.select_regex => |split| return p.startSelRegex(pane, split),
.edit => |edit| switch (edit.kind) {
.delete => return p.normalDelete(pane, true),
.delete_noyank => return p.normalDelete(pane, false),
.change => return p.normalChange(pane),
.yank => return p.normalYank(pane),
.replace_with_yank => return p.normalReplaceYank(pane),
.paste_after => {
pane.count = edit.count;
return p.normalPaste(pane, false);
},
.paste_before => {
pane.count = edit.count;
return p.normalPaste(pane, true);
},
.switch_case => return p.normalCase(pane, .toggle),
.lowercase => return p.normalCase(pane, .lower),
.uppercase => return p.normalCase(pane, .upper),
.join_lines => return p.normalJoin(pane),
.indent => return p.normalIndent(pane, edit.count, true),
.unindent => return p.normalIndent(pane, edit.count, false),
.comment_toggle => return p.normalToggleComment(pane),
.undo => return p.doUndo(pane),
.redo => return p.doRedo(pane),
},
.lsp => |request| return p.lspRequest(p.active, switch (request) {
.definition => .definition,
.declaration => .declaration,
.type_definition => .type_definition,
.implementation => .implementation,
.references => .references,
.format => .format,
}, ""),
.adjust_number => |delta| return p.normalAdjustNumber(pane, delta),
.leader => {
p.leader_on = true;
p.leader_n = 0;
},
.command_line => {
p.enterTagEdit(pane, -1);
if (pane.tag_edit) pane.mode = .normal;
},
.pipe_selection => return p.startPipe(pane),
.search => return p.startSearch(pane, config.search_marker),
.search_step => |direction| {
const delta: i32 = if (direction == .forward) 1 else -1;
if (p.searchStep(p.active, delta)) return;
if (pane.isTerminal()) return p.lookStep(pane, pl, delta);
},
}
}
// ---- selection pipe (`|`): visible prompt, async shell, atomic edit ----
fn startPipe(p: *Pardes, pane: *Pane) void {
const f = pane.file orelse return;
if (!output_pane.fileTraits(f.output).saves) return;
if (!pane.tag_init) {
pane.tag_tail.appendSlice(p.gpa, curTail(pane)) catch return;
pane.tag_init = true;
}
pane.pipe_at = @intCast(pane.tag_tail.items.len);
pane.tag_tail.appendSlice(p.gpa, config.pipe_marker) catch return;
pane.pipe_edit = true;
pane.tag_edit = true;
pane.tag_sel = false;
pane.mode = .insert;
pane.pending = 0;
pane.tag_col = @intCast((p.tagPrefix(pane) catch return).len + pane.tag_tail.items.len);
}
/// Snapshot command/cwd/ranges/selection bytes before emitting the id-only
/// effect. Every allocation is owned by pipe_wait, so the frontend can
/// copy it synchronously and the core can keep editing immediately after.
fn submitPipe(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const f = pane.file orelse return;
if (!output_pane.fileTraits(f.output).saves) return;
const tail = pane.tag_tail.items;
const armed = tail[@min(pane.pipe_at, tail.len)..];
if (!std.mem.startsWith(u8, armed, config.pipe_marker)) return;
const command = armed[config.pipe_marker.len..];
if (command.len == 0) return;
var ranges: [MAX_SELS]modal.HxRange = undefined;
const got = paneRanges(pane, f.content, 0, &ranges);
const inputs = p.gpa.alloc(selection_pipe.Input, got.n) catch return;
var made: usize = 0;
for (ranges[0..got.n], 0..) |range, i| {
const lo = @min(range.anchor, range.head);
const hi = @max(range.anchor, range.head);
if (hi > f.content.len) break;
const copy = p.gpa.dupe(u8, f.content[lo..hi]) catch break;
inputs[i] = .{ .bytes = copy };
made += 1;
}
if (made != got.n) {
for (inputs[0..made]) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
}
const command_copy = p.gpa.dupe(u8, command) catch {
for (inputs) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
};
const cwd_copy = p.gpa.dupe(u8, paneDir(pane)) catch {
p.gpa.free(command_copy);
for (inputs) |input| p.gpa.free(@constCast(input.bytes));
p.gpa.free(inputs);
return;
};
p.pipe_seq +%= 1;
if (p.pipe_wait) |*old| old.deinit(p.gpa);
p.pipe_wait = .{
.id = p.pipe_seq,
.pane = id,
.serial = pane.serial,
.revision = f.revision,
.command = command_copy,
.cwd = cwd_copy,
.inputs = inputs,
.ranges = ranges,
.primary = @intCast(got.pri),
.explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active,
};
p.emit(.{ .pipe = .{ .id = p.pipe_seq } });
}
/// Frontends call this while draining a .pipe effect, then immediately
/// copy the borrowed view into a worker-owned selection_pipe.Job.
pub fn pipeRequest(p: *const Pardes, id: u32) ?selection_pipe.Request {
if (p.pipe_wait) |*wait| {
if (wait.id == id) return wait.request();
}
return null;
}
fn pipeResponse(p: *Pardes, id: u32, success: bool, outputs: []const []const u8) void {
if (p.pipe_wait == null or p.pipe_wait.?.id != id) return;
var wait = p.pipe_wait.?;
p.pipe_wait = null;
defer wait.deinit(p.gpa);
if (!success or outputs.len != wait.inputs.len) return;
const pane = p.panes[wait.pane] orelse return;
if (pane.serial != wait.serial) return;
const f = if (pane.file) |*file| file else return;
if (!output_pane.fileTraits(f.output).saves or f.revision != wait.revision) return;
var total_output: usize = 0;
var removed: usize = 0;
var previous_end: usize = 0;
for (outputs, wait.ranges[0..outputs.len]) |output, range| {
if (output.len > selection_pipe.max_stdout_bytes) return;
total_output = std.math.add(usize, total_output, output.len) catch return;
if (total_output > selection_pipe.max_total_stdout_bytes) return;
const lo = @min(range.anchor, range.head);
const hi = @max(range.anchor, range.head);
if (lo < previous_end or hi > f.content.len) return;
removed = std.math.add(usize, removed, hi - lo) catch return;
previous_end = hi;
}
const kept = f.content.len - removed;
const final_len = std.math.add(usize, kept, total_output) catch return;
const replacement = p.gpa.alloc(u8, final_len) catch return;
var new_ranges: [MAX_SELS]modal.HxRange = undefined;
var read_at: usize = 0;
var write_at: usize = 0;
for (outputs, wait.ranges[0..outputs.len], 0..) |output, range, i| {
const lo = @min(range.anchor, range.head);
const hi = @max(range.anchor, range.head);
@memcpy(replacement[write_at .. write_at + (lo - read_at)], f.content[read_at..lo]);
write_at += lo - read_at;
const out_start = write_at;
@memcpy(replacement[write_at .. write_at + output.len], output);
write_at += output.len;
const out_end = write_at;
new_ranges[i] = if (range.anchor > range.head)
.{ .anchor = out_end, .head = out_start }
else
.{ .anchor = out_start, .head = out_end };
read_at = hi;
}
@memcpy(replacement[write_at..], f.content[read_at..]);
// One async request is one history transaction, even at 64 cursors.
p.pushUndo(pane);
file_pane.setContent(p, f, replacement);
const pl = p.paneCursorLines(pane) catch return;
setPaneRanges(pane, pl, f.content, new_ranges[0..outputs.len], &.{}, wait.primary, wait.explicit);
pane.select = false;
pane.ensureCursorVisible();
}
// ---- search (`/`, Find, n/N): results into an output buffer, look the rows ----
const Search = enum { text, find, grep };
const SearchStart = enum { top, cursor };
fn paneDir(pane: *const Pane) []const u8 {
if (pane.file) |f| return std.fs.path.dirname(f.path) orelse "/";
if (comptime pdf_enabled) if (pane.pdf) |pv|
return std.fs.path.dirname(pv.path) orelse "/";
if (pane.image) |iv| return std.fs.path.dirname(iv.path) orelse "/";
return pane.cwdSlice();
}
const PdfSearchResult = struct { rows: usize = 0, anchor: ?usize = null };
/// Ask MuPDF for each page's logical hits, so the result list and the
/// quads used to highlight/reveal can never disagree. Locations spell
/// `path:PAGE:HIT`, reusing Spot.col as a one-based page-local hit id.
/// The compact snippet is the query itself: pairing MuPDF geometry back to
/// extracted lines would be heuristic, and a plausible wrong line is less
/// honest than the exact occurrence identity already in the address.
fn searchPdf(
p: *Pardes,
pane: *Pane,
pat: []const u8,
start: SearchStart,
out: *std.ArrayList(u8),
) PdfSearchResult {
if (comptime !pdf_enabled) return .{};
const pv = &(pane.pdf orelse return .{});
p.setPdfSearchQuery(pv, pat);
const arena = p.scratch.allocator();
const shown = std.fs.path.basename(pv.path);
var result: PdfSearchResult = .{};
const max_hits = 512;
var snippet_len = @min(pat.len, 200);
while (snippet_len > 0 and snippet_len < pat.len and pat[snippet_len] & 0xc0 == 0x80)
snippet_len -= 1;
const snippet = pat[0..snippet_len];
for (0..pv.page_count) |page| {
if (result.rows >= max_hits) break;
var found = pv.document.search(p.gpa, page, pat) catch continue;
defer found.deinit(p.gpa);
// A native right-click selection identifies the occurrence the
// user is already on. Compare hit centers against its oriented
// selection quads; the next step then advances past that hit.
const cursor_hit: ?usize = if (start == .cursor and page == pv.page) cursor: {
const selection = pv.selection orelse break :cursor null;
for (found.quads) |item| {
const q = item.quad;
const center: PdfPoint = .{
.x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4,
.y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4,
};
if (selection.contains(center)) break :cursor item.hit;
}
break :cursor null;
} else null;
for (0..found.hit_count) |hit_index| {
if (result.rows >= max_hits) break;
if (start == .cursor and
(page < pv.page or (page == pv.page and cursor_hit != null and hit_index <= cursor_hit.?)))
result.anchor = result.rows;
const row = std.fmt.allocPrint(arena, "{s}:{d}:{d} {s}\n", .{
shown, page + 1, hit_index + 1, snippet,
}) catch return result;
out.appendSlice(arena, row) catch return result;
result.rows += 1;
}
}
return result;
}
/// `/` (and the Find builtin) on any pane: type the pattern into the tag
/// tail after `marker` — the existing modal one-line editor, visible while
/// typing, nothing that disappears. Enter/Esc are intercepted in handleKey.
pub fn startSearch(p: *Pardes, pane: *Pane, marker: []const u8) void {
if (!pane.tag_init) {
pane.tag_tail.appendSlice(p.gpa, curTail(pane)) catch return;
pane.tag_init = true;
}
pane.search_at = @intCast(pane.tag_tail.items.len);
pane.tag_tail.appendSlice(p.gpa, marker) catch return;
pane.search_edit = true;
pane.tag_edit = true;
pane.tag_sel = false;
pane.mode = .insert;
pane.pending = 0;
// tag_col is a RENDERED-tag column, so the end of the tail is past the
// prefix (search_at stays a tail offset — it slices tag_tail)
pane.tag_col = @intCast((p.tagPrefix(pane) catch return).len + pane.tag_tail.items.len);
}
/// Enter on an armed input: the pattern is everything past the marker's
/// `/` (so a pattern may itself contain slashes), and the marker names the
/// search — " Find /" walks the filesystem for NAMES, " Grep /" for
/// CONTENTS, " /" reads the pane's own text. No `/` left means the editor
/// ate the marker: nothing to run.
fn submitSearch(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
// `s`/`S` have already applied themselves keystroke by keystroke;
// Enter re-runs the final pattern so a submit is one code path with
// the preview and cannot disagree with what is on screen.
if (selRegexArmed(pane)) |a| return p.applySelRegex(pane, a.pat, a.split);
const tail = pane.tag_tail.items;
const armed = tail[@min(pane.search_at, tail.len)..];
const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return;
if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]);
if (std.mem.startsWith(u8, armed, config.symbol_marker)) return p.lspRequest(id, .workspace_symbols, armed[slash + 1 ..]);
const kind: Search = if (std.mem.startsWith(u8, armed, config.find_marker))
.find
else if (std.mem.startsWith(u8, armed, config.grep_marker))
.grep
else
.text;
p.runSearch(id, armed[slash + 1 ..], kind, .top);
}
/// Fill this pane's results buffer with everything matching `pat_raw`
/// (plain substring, case-insensitive) — ONE function for both searches,
/// because they differ only in where the rows come from and agree on every
/// row being a LOOK TARGET, which is what makes n/N work:
/// text (`/`) — the pane's own flat text, the same view Look and Execute
/// read, so a terminal searches its scrollback exactly as a file
/// searches its content. Rows are `location text`, the location ended
/// by a SPACE (a trailing `:` would read as part of it): the pane's
/// path when it has a real file, else `@pN`.
/// find — the pane's DIRECTORY, walked like fd. Rows are bare paths.
/// grep — the CONTENTS of every file under every pane's directory,
/// walked like `grep -R`. Rows are `path:LINE:COL-ENDCOL text`, the
/// path relative to THIS pane's directory (absolute for a hit outside
/// it).
/// Both searches that match TEXT name the match's whole span, so looking a
/// row — which is all n/N do — selects what matched rather than parking on
/// its first cell. Find's rows are bare paths and have nothing to span.
/// No matches = an empty buffer.
///
/// `start` is where the WALK begins, which belongs to the gesture and not
/// to the search: a click POINTS at one of the hits, so its list is armed
/// there and the first step goes to the next one (acme's button-3 walking a
/// word). `/`, Find and Grep point at nothing, so their list is walked from
/// the top, which is also the only place a list of OTHER files could start.
pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart) void {
const pane = p.panes[id] orelse return;
const pat = std.mem.trim(u8, pat_raw, " \t\r\n");
if (pat.len == 0) return;
const arena = p.scratch.allocator();
// where the pane lives: a file's directory, a shell's cwd — the walk
// root, and the directory the results buffer is named in.
const dir = paneDir(pane);
var out: std.ArrayList(u8) = .empty;
var nrows: usize = 0;
var anchor: ?usize = null;
if (kind == .grep) {
// One walk per PLACE the session is open on: every pane's
// directory, minus the ones another pane's already contains, so a
// tree two panes sit in is greped once and a pane deep inside
// another's tree adds nothing. Slot order, so the same session
// gives the same buffer twice running.
var roots: [MAX_PANES][]const u8 = undefined;
var nroots: usize = 0;
for (p.panes) |slot| {
const pp = slot orelse continue;
const d = paneDir(pp);
var covered = false;
var k: usize = 0;
while (k < nroots) {
if (pathUnder(d, roots[k])) {
covered = true;
break;
}
if (pathUnder(roots[k], d)) { // this one swallows a root already kept
nroots -= 1;
roots[k] = roots[nroots];
continue;
}
k += 1;
}
if (covered) continue;
roots[nroots] = d;
nroots += 1;
}
for (roots[0..nroots]) |r| look.grep(arena, p.gpa, r, dir, pat, &out);
} else if (kind == .find) look.find(arena, dir, pat, &out) else if (hasPdf(pane)) {
const found = p.searchPdf(pane, pat, start, &out);
nrows = found.rows;
anchor = found.anchor;
} else {
const pl = p.paneCursorLines(pane) catch return;
// a real file names itself; a terminal or an output buffer has no path
const has_path = if (pane.file) |f| f.output == null else false;
var idbuf: [16]u8 = undefined;
// relative to `dir`, like Find's rows — and `dir` IS this file's
// own directory, so that is exactly its basename
const loc: []const u8 = if (has_path)
std.fs.path.basename(pane.file.?.path)
else
std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{id}) catch return;
// the hit at or before the cursor is the one you are ON, so arming
// there makes the first step land on the NEXT one: a click on the
// second `foo` goes to the third, not back to the first.
const cl: usize = @intCast(@max(0, pane.cur_row));
const cc: usize = @intCast(@max(0, pane.cur_col));
for (pl.lines, 0..) |ln, i| {
const at = std.ascii.indexOfIgnoreCase(ln, pat) orelse continue;
if (start == .cursor and (i < cl or (i == cl and at <= cc))) anchor = nrows;
nrows += 1;
// the row names the MATCH's span, not just its first cell, so
// n/N land ON the hit with it selected (config.range_sep)
const row = std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{
loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"),
}) catch return;
out.appendSlice(arena, row) catch return;
}
}
const content = p.gpa.dupe(u8, out.items) catch return;
// the buffer records WHICH search filled it, pattern and all: Find and
// Grep are builtins (words you can execute), the bare `/` is a key
const from: output_pane.Origin = switch (kind) {
.text => .search,
.find => .{ .cmd = .Find },
.grep => .{ .cmd = .Grep },
};
// The SAME search asked again REFILLS the list it already opened —
// right-clicking a word in four places is one +Search walked four
// times, not four +Searches over identical rows. A different pattern
// still gets its own buffer, and that IS the old rule: two searches are
// two lists, both stay open at their sizes, and the new one stacks
// directly below this pane (placeDoc). Focus stays here either way.
// ...and it is ANY open list this search already filled, not only the
// one n/N are armed on: search `foo`, then `bar`, then `foo` again and
// the third search re-arms foo's own buffer rather than opening its
// identical twin below it. Same directory only — the rows are written
// relative to it, so another dir's list is a different list. Never the
// searching pane itself (a `/` inside a +Search writes its own rows).
for (p.panes, 0..) |slot, i| {
if (i == id) continue;
const rp = slot orelse continue;
const rf = if (rp.file) |*f| f else continue;
const o = rf.output orelse continue;
if (!std.meta.eql(o.from, from) or !std.mem.eql(u8, o.arg(), pat)) continue;
if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue;
// a refill that changes NOTHING keeps its place: a right click on
// an already-armed word is an `n`, and throwing the list back to
// the top only to scroll down to the stepped row is a jump with no
// information in it.
const same = std.mem.eql(u8, rf.content, content);
file_pane.setContent(p, rf, content);
if (!same) rf.scroll = 0;
pane.search_pane = i;
pane.search_row = anchor;
return;
}
const free = p.freeSlot() orelse {
p.gpa.free(content);
return;
};
const np = output_pane.open(p, free, dir, from, pat, content) catch {
p.gpa.free(content);
return;
};
p.placeDoc(id, free, np);
p.active = id;
pane.search_pane = free;
pane.search_row = anchor;
}
/// n/N: step to the next/previous row of this pane's results buffer and
/// ACT on it — which of the two acme verbs that is comes from the buffer's
/// own traits, so this is one motion over "a list of things you can run",
/// not two kinds of stepping. A location list (every search, the jumplist,
/// every language answer) Looks the leading `path:LINE:COL` word; a command
/// list (ThemeSel) Execs the whole row. False = no live search: a
/// terminal's n/N falls back to lookStep, anything else stays put.
fn searchStep(p: *Pardes, id: usize, delta: i32) bool {
const pane = p.panes[id] orelse return false;
const rid = pane.search_pane orelse return false;
const rp = p.panes[rid] orelse return false;
const rf = if (rp.file) |*f| f else return false;
// one question covers both hazards: a freed slot can be reused by an
// unrelated pane, and a buffer of PROSE has nowhere to step to
const tr = output_pane.fileTraits(rf.output);
if (!tr.steps) return false;
// fresh results: n starts at the first row, N has nothing behind it
const nrows: i64 = @intCast(std.mem.count(u8, rf.content, "\n"));
const step: i64 = if (pane.search_row) |c| @as(i64, @intCast(c)) + delta else if (delta > 0) 0 else -1;
if (step < 0 or step >= nrows) return true; // armed, nowhere left to go
const r: i32 = @intCast(step);
pane.search_row = @intCast(step);
// select the result row in the results pane and keep it in view
rp.msel = .{ .active = true, .r0 = r, .r1 = r };
rp.vsel.active = false;
rp.nsel = 0;
rp.cur_row = r;
rp.cur_col = 0;
rp.cur_pinned = true;
// in view, but WITHOUT scrolloff: a results pane is short, and a
// three-row margin on a seven-row one means every single n scrolls the
// list out from under the eye. A row already on screen moves nothing.
const off = rp.scroll();
const last = off + @as(i32, rp.rows) - 1;
if (r < off) rp.scrollBy(r - off) else if (r > last) rp.scrollBy(r - last);
const ln = modal.lineSlice(rf.content, @intCast(step));
// Both arms are the BUILTIN, run on the results pane — the same call a
// middle or right click on that row would make, so a stepped row and a
// clicked row can never drift apart. A command row goes whole (its
// argument is the tail after the name); a location row is cut to the
// leading file-ish word, since the rest of it is the matched text.
if (tr.executes) {
p.runBuiltin(config.exec_cmd, rid, "", std.mem.trim(u8, ln, " \t\r"));
} else {
var hi: usize = 0;
while (hi < ln.len and config.isFileChar(ln[hi])) hi += 1;
p.runBuiltin(config.look_cmd, rid, "", ln[0..hi]);
}
// the look may focus what it opened — a Find row opens a whole new
// file pane every time — so focus comes back to the pane that owns the
// search and the next n keeps stepping. A `/` row looks at the
// searching pane itself, so this is what already happened there.
p.active = id;
return true;
}
/// Ask the backend something about the symbol under the cursor. Only a
/// real file can be asked: a terminal's rows are a program's output and an
/// output buffer is our own text, neither of which has a language behind
/// it. Unsupported kinds never get here (the keymap drops them), so a
/// backend that answers nothing simply never opens a buffer.
pub fn lspRequest(p: *Pardes, id: usize, kind: lsp.Kind, arg: []const u8) void {
if (!p.multiOnce()) return; // one question per keystroke, from the primary
if (!lsp.supports.contains(kind)) return;
const pane = p.panes[id] orelse return;
// `status` is about the BACKEND, not about a document, so it answers
// from ANY pane — a terminal, a +Search, anywhere. That matters
// precisely when the pane you are sitting in is the thing going wrong.
// Every other kind needs a real file: a terminal's rows are a
// program's output and an output buffer is our own text.
if (kind != .status) {
const f = pane.file orelse return;
if (f.output != null) return;
}
if (arg.len > 128) return; // the effect's arg is a Buf(128)
const off = if (pane.file) |f| modal.hxOff(f.content, .{
.row = @intCast(@max(0, pane.cur_row)),
.col = @intCast(@max(0, pane.cur_col)),
}) else 0;
p.lsp_seq +%= 1;
p.lsp_wait = .{ .id = p.lsp_seq, .kind = kind, .pane = id, .arg = .from(arg) };
p.emit(.{ .lsp = .{
.id = p.lsp_seq,
.kind = kind,
.pane = @intCast(id),
.offset = @intCast(off),
.arg = .from(arg),
} });
}
/// A worker answered. Rows are `+Search` format with ABSOLUTE paths, so
/// both dispositions below are the ordinary look path:
/// one row, a goto -> jump straight there (helix jumps on a single
/// location and shows a picker on several)
/// anything else -> an output buffer, which n/N already steps. That
/// buffer IS the picker; there was never one to write.
pub fn lspResponse(p: *Pardes, id: u32, rows: []const u8) void {
const w = p.lsp_wait orelse return;
if (w.id != id) return; // superseded by a newer press, or the pane died
p.lsp_wait = null;
const pane = p.panes[w.pane] orelse return;
if (rows.len == 0) return;
const from: output_pane.Origin = .{ .query = w.kind };
const nrows = std.mem.count(u8, rows, "\n");
if (output_pane.traits(from).jumps and nrows == 1) {
const ln = std.mem.trimEnd(u8, rows, "\n");
var hi: usize = 0;
while (hi < ln.len and config.isFileChar(ln[hi])) hi += 1;
// exactly what a `/` result row does when n steps onto it: look the
// `path:LINE:COL` token from the pane that asked, so placement,
// dedup-onto-an-open-pane and centering are the ONE look path.
// (helix would also push its jumplist here; pardes has none, so
// there is nothing to push — do not read this as one.)
return p.lookAt(w.pane, ln[0..hi]);
}
const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice();
const content = p.gpa.dupe(u8, rows) catch return;
const free = p.freeSlot() orelse {
p.gpa.free(content);
return;
};
const np = output_pane.open(p, free, dir, from, w.arg.slice(), content) catch {
p.gpa.free(content);
return;
};
p.placeDoc(w.pane, free, np);
p.active = w.pane;
// prose is not a list of locations: n/N over a hover blurb would step
// to nowhere, so only stepping buffers arm the stepper — and WHICH
// query filled it is now the buffer's own record, not a field here.
if (output_pane.traits(from).steps) {
pane.search_pane = free;
pane.search_row = null;
}
}
/// n/N on a terminal pane: a MOTION over lookable tokens. Select the
/// next/prev whitespace-separated token that look.resolve can turn into a
/// file/dir (several per line: an ls row hops big.txt -> plain.txt), park
/// the cursor at its start, open NOTHING — Enter's normal-mode handler
/// looks the selection. Wraps around when nothing lies in the direction
/// (fresh out of tty mode the cursor sits below the output, so the first
/// n lands on the first token). Deliberately only THIS pane's directory,
/// where the look itself walks every pane's: the motion resolves every
/// token it steps over, so the other directories would cost tokens ×
/// panes realpaths on a single keystroke — and a token the motion skips
/// is still openable by looking it, which is all n/N is a shortcut for.
fn lookStep(p: *Pardes, pane: *Pane, pl: PaneLines, delta: i32) void {
_ = p; // a pure motion now: Enter's normal-mode handler does the look
pane.pinCursor(); // fresh out of tty mode the cursor still tracks the shell
const nrows: i32 = @intCast(pl.lines.len);
if (nrows == 0) return;
var realbuf: [4096]u8 = undefined;
var k: i32 = 0;
while (k < nrows) : (k += 1) {
const r = @mod(pane.cur_row + delta * k, nrows);
const ln = pl.lines[@intCast(r)];
var hit_t0: usize = 0;
var hit_t1: usize = 0;
var i: usize = 0;
while (i < ln.len) {
while (i < ln.len and (ln[i] == ' ' or ln[i] == '\t')) i += 1;
const t0 = i;
while (i < ln.len and ln[i] != ' ' and ln[i] != '\t') i += 1;
if (i == t0) break;
// on the cursor's own row (no wrap yet) only tokens strictly
// past the cursor count, in the motion's direction
if (k == 0) {
if (delta > 0 and @as(i32, @intCast(t0)) <= pane.cur_col) continue;
if (delta < 0 and @as(i32, @intCast(t0)) >= pane.cur_col) continue;
}
if (look.resolve(ln[t0..i], pane.cwdSlice(), &realbuf) == .none) continue;
hit_t0 = t0;
hit_t1 = i;
if (delta > 0) break; // first token forward; keep the last one backward
}
if (hit_t1 == 0) continue;
// anchor the selection at the token's end, cursor at its START;
// EXPLICIT: Enter's look chord acts on it
pane.vsel = .{ .active = true, .row = r, .col = @intCast(hit_t1 - 1), .explicit = true };
pane.msel.active = false;
pane.nsel = 0;
pane.cur_row = r;
pane.cur_col = @intCast(hit_t0);
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
}
// nothing lookable anywhere: stay put
}
const EditText = struct { text: []u8, row0: i32 };
/// The pane's editable text and the absolute surface row its first line
/// sits at: a file's whole content at row 0, or a terminal's edit buffer
/// at its anchor. Terminals materialize the buffer here on first use and
/// grow it whenever an edit reaches past an end, seeding from — and from
/// then on standing in for — the shell rows it swallows.
/// `col` is the caller's cursor column: row `lo` is padded out to it with
/// spaces, because a terminal cursor may sit past the end of a row (acme:
/// you click anywhere and type there, which is what the insertion runs
/// did by padding at render time). Insert-mode callers pass their column;
/// everything else passes -1 and leaves the text alone.
/// Null if the pane holds no editable text (an image or PDF projection).
fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText {
if (pane.file) |f| return .{ .text = f.content, .row0 = 0 };
if (pane.image != null or hasPdf(pane)) return null;
const want_lo = @max(0, @min(lo, hi));
const want_hi = @max(want_lo, @max(lo, hi));
const fresh = pane.ovl == null;
const old: Ovl = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} };
const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text));
const up = old.row - want_lo; // shell rows to prepend
const down = want_hi - (old.row + lines - 1); // surface rows past its end
if (fresh or up > 0 or down > 0) {
const rows = term_pane.shellRows(p, pane) catch return null;
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(p.gpa);
const row0 = old.row - @max(0, up);
var g: i32 = row0;
while (g < old.row) : (g += 1) {
buf.appendSlice(p.gpa, if (@as(usize, @intCast(g)) < rows.len) rows[@intCast(g)] else "") catch return null;
buf.append(p.gpa, '\n') catch return null;
}
if (fresh)
buf.appendSlice(p.gpa, if (@as(usize, @intCast(old.row)) < rows.len) rows[@intCast(old.row)] else "") catch return null
else
buf.appendSlice(p.gpa, old.text) catch return null;
var k: i32 = 0;
while (k < down) : (k += 1) {
const src = old.row + old.rows + k;
buf.append(p.gpa, '\n') catch return null;
buf.appendSlice(p.gpa, if (@as(usize, @intCast(src)) < rows.len) rows[@intCast(src)] else "") catch return null;
}
const text = buf.toOwnedSlice(p.gpa) catch return null;
if (pane.ovl) |o| p.gpa.free(o.text);
pane.ovl = .{ .row = row0, .rows = old.rows + @max(0, up) + @max(0, down), .text = text };
}
const o = &pane.ovl.?;
const r: usize = @intCast(@max(0, want_lo - o.row));
const llen: i32 = @intCast(modal.lineSlice(o.text, r).len);
if (col > llen) {
const spaces = p.gpa.alloc(u8, @intCast(col - llen)) catch return null;
defer p.gpa.free(spaces);
@memset(spaces, ' ');
const text = modal.insertAt(p.gpa, o.text, .{ .row = r, .col = @intCast(llen) }, spaces) catch return null;
p.gpa.free(o.text);
o.text = text;
}
return .{ .text = o.text, .row0 = o.row };
}
/// editText for an op whose selection can END on a line's newline cell:
/// eating that newline joins with the line BELOW, so a terminal's buffer
/// has to cover that row too (a file's content always already does).
fn editTextEol(p: *Pardes, pane: *Pane, b: Bounds) ?EditText {
const eb = p.editText(pane, b.lo_row, b.hi_row, -1) orelse return null;
const r: usize = @intCast(@max(0, b.hi_row - eb.row0));
if (r + 1 < modal.lineCount(eb.text)) return eb;
if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb;
return p.editText(pane, b.lo_row, b.hi_row + 1, -1);
}
/// install a rewritten editable text (frees the old one)
fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void {
if (pane.file) |*f| return file_pane.setContent(p, f, new);
if (pane.ovl) |*o| {
p.gpa.free(o.text);
o.text = new;
} else p.gpa.free(new);
}
const InsertAt = enum { at, append, line_start, line_end, open_below, open_above };
fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void {
if (hasPdf(pane)) return;
pane.pinCursor();
// snapshot once per insert session (WITH the pre-insert selection) so
// `u` undoes the whole session and restores what was selected
p.pushUndo(pane);
pane.select = false;
pane.append_at = null;
pane.sticky_col = -1;
const pl = p.paneCursorLines(pane) catch {
pane.mode = .insert;
pane.msel.active = false;
pane.vsel.active = false;
pane.pending = 0;
return;
};
const text = p.flatSurface(pane, pl) catch return;
const cur = toModalCursor(pane, pl);
const llen: usize = if (cur.row < pl.lines.len) pl.lines[cur.row].len else 0;
// helix selection-aware entry: `i` to the selection's START (the
// selection flips and survives until the first edit); `a` one past
// its END, remembering the origin cell for the Esc restore
const b: ?Bounds = if (pane.vsel.active) vselBounds(pane) else null;
switch (where) {
.at => {
if (b) |bb| {
pane.cur_row = bb.lo_row;
pane.cur_col = bb.lo_col;
pane.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false };
pane.cur_pinned = true;
}
},
.append => {
const lo_row = if (b) |bb| bb.lo_row else pane.cur_row;
const lo_col = if (b) |bb| bb.lo_col else pane.cur_col;
const hi_row = if (b) |bb| bb.hi_row else pane.cur_row;
const hi_col = if (b) |bb| bb.hi_col else pane.cur_col;
pane.append_at = .{ .row = lo_row, .col = lo_col };
const gap = modal.nextGrapheme(text, modal.hxOff(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) }));
const gc = modal.hxPos(text, gap);
pane.cur_row = @intCast(gc.row);
pane.cur_col = @intCast(gc.col);
pane.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false };
pane.cur_pinned = true;
},
.line_start => {
fromModalCursor(pane, pl, modal.firstNonWsOf(pl.lines, cur));
pane.vsel.active = false;
},
.line_end => {
pane.cur_col = @intCast(llen);
pane.cur_pinned = true;
pane.vsel.active = false;
},
.open_below, .open_above => {
pane.vsel.active = false;
const below = where == .open_below;
// helix `open`: the new line copies the current line's full
// indent LEVELS; <n>o opens n lines, cursor on the first
const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else pane.cur_row;
const eb = p.editText(pane, abs, abs, -1) orelse return;
const row: usize = @intCast(@max(0, abs - eb.row0));
const ind = modal.hxIndentString(modal.lineSlice(eb.text, row));
const arena = p.scratch.allocator();
var block: std.ArrayList(u8) = .empty;
for (0..cnt) |_| {
if (below) {
block.append(arena, '\n') catch return;
block.appendSlice(arena, ind) catch return;
} else {
block.appendSlice(arena, ind) catch return;
block.append(arena, '\n') catch return;
}
}
const at: modal.Cursor = if (below)
.{ .row = row, .col = modal.lineSlice(eb.text, row).len }
else
.{ .row = row, .col = 0 };
const new = modal.insertAt(p.gpa, eb.text, at, block.items) catch return;
p.setEditText(pane, new);
pane.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0;
pane.cur_col = @intCast(ind.len);
pane.cur_pinned = true;
// helix `open` with a COUNT leaves one cursor per line it
// opened — `3o` then typing fills all three. The lines are
// consecutive and start at the cursor, so this is just cnt
// points a row apart, the first one primary.
// (Inside a replay pass the extra ranges cannot be created:
// a pass produces exactly one range. `3o` at several cursors
// therefore opens the lines but keeps the cursors it had.)
if (cnt > 1 and !p.multi_on) opened: {
const pl2 = p.paneCursorLines(pane) catch break :opened;
const t2 = p.flatSurface(pane, pl2) catch break :opened;
var rs: [MAX_SELS]modal.HxRange = undefined;
const m = @min(cnt, MAX_SELS);
for (0..m) |k| {
const o = modal.hxOff(t2, .{ .row = @intCast(@max(0, pane.cur_row - pl2.row0) + @as(i32, @intCast(k))), .col = ind.len });
rs[k] = .{ .anchor = o, .head = o };
}
setPaneRanges(pane, pl2, t2, rs[0..m], &.{}, 0, false);
}
},
}
pane.mode = .insert;
pane.msel.active = false;
pane.pending = 0;
pane.ensureCursorVisible();
}
/// insert mode. ONE path for both pane kinds: a file edits its content, a
/// terminal edits the buffer standing in for its shell rows (editText
/// materializes and grows it), so typing, Enter, joins and the kill runs
/// mean exactly the same thing in a shell pane as in a document.
fn handleInsert(p: *Pardes, pane: *Pane, key: Key) void {
if (pane.nsel == 0) return p.insertKey(pane, key);
p.replaySels(pane, .{ .insert = key });
}
fn insertKey(p: *Pardes, pane: *Pane, key: Key) void {
// helix aliases: normalize to the base key and re-dispatch
if (hit(key, config.insert_backspace_alias)) return p.insertKey(pane, .{ .cp = Key.backspace });
if (hit(key, config.insert_enter_alias)) return p.insertKey(pane, .{ .cp = Key.enter });
if (hit(key, config.insert_delete_alias)) return p.insertKey(pane, .{ .cp = Key.delete });
// a selection carried into insert (i/a) survives only until the next
// key: helix maps it through every edit, pardes drops it instead —
// its only pardes use (the acme chords) needs explicit selections
// anyway, and those never enter insert mode
pane.vsel.active = false;
if (!pane.cur_pinned) pane.pinCursor();
// arrows and paging are pure motion over the WHOLE surface, so they
// run before editText — a terminal must not freeze shell rows into an
// edit buffer just because you walked across them
switch (key.cp) {
Key.left, Key.right, Key.up, Key.down => {
const pl = p.paneCursorLines(pane) catch return;
const cur0 = toModalCursor(pane, pl);
const nc = switch (key.cp) {
Key.left => modal.charLeft(cur0),
Key.right => modal.charRight(pl.lines, cur0),
Key.up => modal.lineUp(pl.lines, cur0),
Key.down => modal.lineDown(pl.lines, cur0),
else => cur0,
};
fromModalCursor(pane, pl, nc);
pane.ensureCursorVisible();
return;
},
Key.page_up, Key.page_down => {
// helix binds insert pageup/pagedown to the same view
// scroll + cursor snap as normal mode
const pl = p.paneCursorLines(pane) catch return;
const flat = p.flatSurface(pane, pl) catch return;
const range = paneRange(pane, flat, pl.row0);
const step: i32 = @intCast(@max(1, pane.rows));
scrollViewMove(pane, pl, flat, range, if (key.cp == Key.page_down) step else -step);
return;
},
Key.home => {
pane.cur_col = 0;
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
},
Key.end => {
// helix insert End: past the last char (goto_line_end_newline)
const pl = p.paneCursorLines(pane) catch return;
const cur0 = toModalCursor(pane, pl);
pane.cur_col = @intCast(if (cur0.row < pl.lines.len) pl.lines[cur0.row].len else 0);
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
},
else => {},
}
const eb = p.editText(pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return;
const text = eb.text;
const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) };
if (key.text.len > 0 and !key.ctrl and !key.alt) {
const new = modal.insertAt(p.gpa, text, c, key.text) catch return;
p.setEditText(pane, new);
for (key.text) |ch| {
if (ch == '\n') {
pane.cur_row += 1;
pane.cur_col = 0;
} else pane.cur_col += 1;
}
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
}
// helix insert-mode kills (word/line; deleteSpan is exclusive)
if (hit(key, config.delete_word_backward)) {
// helix delete_word_backward: to the previous word start —
// crossing the newline at col 0, which takes the word before it
// too, so on the buffer's first line a terminal grows up one row
const e2 = if (c.row == 0 and c.col == 0)
(p.editText(pane, pane.cur_row - 1, pane.cur_row, 0) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col };
const g = modal.hxOff(e2.text, c2);
if (g == 0) return;
const wr = modal.hxWordMove(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start);
const from = @min(wr.anchor, wr.head);
const fc = modal.hxPos(e2.text, from);
const new = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return;
p.setEditText(pane, new);
pane.cur_row = @as(i32, @intCast(fc.row)) + e2.row0;
pane.cur_col = @intCast(fc.col);
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
}
if (hit(key, config.delete_word_forward)) {
// helix delete_word_forward: to the next word END (trailing
// whitespace survives), crossing newlines at line ends — at the
// buffer's last line a terminal grows down one row to allow it
const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text))
(p.editText(pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return)
else
eb;
const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col };
const g = modal.hxOff(e2.text, c2);
const wr = modal.hxWordMove(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end);
const to = @max(wr.anchor, wr.head);
if (to <= g) return;
const new = modal.deleteSpan(p.gpa, e2.text, c2, modal.hxPos(e2.text, to)) catch return;
p.setEditText(pane, new);
pane.cur_pinned = true;
return;
}
if (hit(key, config.kill_to_line_start)) {
const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return;
p.setEditText(pane, new);
pane.cur_col = 0;
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
}
if (hit(key, config.kill_to_line_end)) {
const llen = modal.lineSlice(text, c.row).len;
const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return;
p.setEditText(pane, new);
pane.cur_pinned = true;
return;
}
switch (key.cp) {
Key.enter => {
// helix insert_newline: the new line copies the current
// line's full indent LEVELS (plain-text heuristic)
const ind = modal.hxIndentString(modal.lineSlice(text, c.row));
const arena = p.scratch.allocator();
const block = std.fmt.allocPrint(arena, "\n{s}", .{ind}) catch return;
const new = modal.insertAt(p.gpa, text, c, block) catch return;
p.setEditText(pane, new);
pane.cur_row += 1;
pane.cur_col = @intCast(ind.len);
pane.cur_pinned = true;
pane.ensureCursorVisible();
},
Key.backspace => {
if (pane.cur_col > 0) {
const new = modal.deleteChar(p.gpa, text, .{ .row = c.row, .col = c.col - 1 }) catch return;
p.setEditText(pane, new);
pane.cur_col -= 1;
pane.cur_pinned = true;
pane.ensureCursorVisible();
return;
}
// at col 0: eat the newline above (join up) — a terminal grows
// its buffer over the row it is joining with
if (pane.cur_row <= 0) return;
const e2 = p.editText(pane, pane.cur_row - 1, pane.cur_row, 0) orelse return;
const row: usize = @intCast(@max(0, pane.cur_row - e2.row0));
if (row == 0) return;
const prevlen = modal.lineSlice(e2.text, row - 1).len;
const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return;
p.setEditText(pane, new);
pane.cur_row -= 1;
pane.cur_col = @intCast(prevlen);
pane.cur_pinned = true;
pane.ensureCursorVisible();
},
Key.delete => {
// delete forward; at line end eat the newline (join), which on
// a terminal means the buffer swallowing the row below
const line = modal.lineSlice(text, c.row);
if (c.col < line.len) {
const new = modal.deleteChar(p.gpa, text, c) catch return;
p.setEditText(pane, new);
} else {
const e2 = p.editText(pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return;
const row: usize = @intCast(@max(0, pane.cur_row - e2.row0));
if (row + 1 >= modal.lineCount(e2.text)) return;
const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return;
p.setEditText(pane, new);
}
pane.cur_pinned = true;
},
Key.tab => {
// helix insert_tab with a Spaces indent style: spaces to
// the next tab stop (smart-tab machinery skipped)
const pad = modal.INDENT_W - (c.col % modal.INDENT_W);
const spaces = " ";
const new = modal.insertAt(p.gpa, text, c, spaces[0..pad]) catch return;
p.setEditText(pane, new);
pane.cur_col += @intCast(pad);
pane.cur_pinned = true;
pane.ensureCursorVisible();
},
else => {},
}
}
const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 };
/// a range's two cells, normalized to document order
fn cellBounds(s: SelRange) Bounds {
if (s.row < s.arow or (s.row == s.arow and s.col < s.acol))
return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol };
return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col };
}
/// the char selection [anchor, cursor] normalized to document order
fn vselBounds(pane: *Pane) Bounds {
return cellBounds(.{ .row = pane.cur_row, .col = pane.cur_col, .arow = pane.vsel.row, .acol = pane.vsel.col });
}
/// the char selection as text. Read off the pane's SURFACE (file content /
/// terminal shell rows + edit buffer), not the rendered body: a yank of a
/// whole line has to carry its newline, the way a file's does, or p/P
/// paste it charwise. Scratch-owned.
fn vselText(p: *Pardes, pane: *Pane) []const u8 {
const arena = p.scratch.allocator();
const b = vselBounds(pane);
const text = p.surfaceText(pane) orelse return "";
return modal.rangeText(arena, text, .{ .row = @intCast(@max(0, b.lo_row)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row)), .col = @intCast(@max(0, b.hi_col)) }) catch "";
}
/// join surface rows [r0, r1] (absolute) with '\n'; scratch-owned
fn yankRows(p: *Pardes, pane: *Pane, r0: i32, r1: i32) []const u8 {
const arena = p.scratch.allocator();
const pl = p.paneCursorLines(pane) catch return "";
var out: std.ArrayList(u8) = .empty;
var i = r0;
while (i <= r1) : (i += 1) {
if (i > r0) out.append(arena, '\n') catch return "";
if (i >= 0 and @as(usize, @intCast(i)) < pl.lines.len)
out.appendSlice(arena, pl.lines[@intCast(i)]) catch return "";
}
return out.items;
}
/// the whole pane surface as flat text, absolute rows from 0 (read-only:
/// unlike editText it never materializes a terminal's edit buffer)
fn surfaceText(p: *Pardes, pane: *Pane) ?[]const u8 {
if (pane.file) |f| return f.content;
const pl = p.paneCursorLines(pane) catch return null;
return p.flatSurface(pane, pl) catch null;
}
// ---- edit operations (d / c / y / p) ----
fn normalDelete(p: *Pardes, pane: *Pane, yank: bool) void {
pane.select = false; // helix delete exits select mode
pane.sticky_col = -1;
if (pane.vsel.active) {
const b = vselBounds(pane);
if (yank) p.setYank(p.vselText(pane)); // read the range before the move
p.pushUndo(pane);
const eb = p.editTextEol(pane, b) orelse {
pane.vsel.active = false;
return;
};
const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch {
pane.vsel.active = false;
return;
};
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
pane.cur_row = b.lo_row;
pane.cur_col = b.lo_col;
clampCursor(pane, d.content, eb.row0);
return;
}
if (pane.msel.active) {
const r0 = @min(pane.msel.r0, pane.msel.r1);
const r1 = @max(pane.msel.r0, pane.msel.r1);
p.pushUndo(pane);
// linewise: a line's newline lives on the row below it
const eb = p.editText(pane, r0, r1 + 1, -1) orelse {
pane.msel.active = false;
return;
};
const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, r0 - eb.row0)), @intCast(@max(0, r1 - eb.row0))) catch {
pane.msel.active = false;
return;
};
p.setEditText(pane, d.content);
if (yank) p.setYank(d.deleted);
p.gpa.free(d.deleted);
const n = modal.lineCount(d.content);
pane.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0;
pane.cur_col = 0;
pane.msel.active = false;
pane.cur_pinned = true;
pane.ensureCursorVisible();
} else {
p.pushUndo(pane);
const eb = p.editTextEol(pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return;
const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) };
if (yank) {
const arena = p.scratch.allocator();
p.setYank(modal.rangeText(arena, eb.text, c, c) catch return);
}
// deleteRange (not deleteChar): the cursor may sit ON a '\n'
// cell, where a delete joins the lines (helix 1-wide selection)
const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return;
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
const llen = modal.lineSlice(d.content, c.row).len;
pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen)));
}
}
fn normalYank(p: *Pardes, pane: *Pane) void {
pane.select = false; // helix yank exits select mode, selection KEPT
if (pane.vsel.active) {
// helix: yank moves neither the cursor nor the selection
p.setYank(p.vselText(pane));
return;
}
if (pane.msel.active) {
p.setYank(p.yankRows(pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1)));
} else {
// helix: a bare cursor IS a 1-wide selection — yank the char
// under it, file and terminal alike (the line-yank vim-ism died
// with the motion model). vselText already speaks both.
const save = pane.vsel;
pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = false };
p.setYank(p.vselText(pane));
pane.vsel = save;
}
}
/// helix p/P: a yank ending in '\n' pastes as whole lines below/above
/// the SELECTION's line span; anything else splices inline at the
/// selection's outer edge. The paste (repeated <count> times) becomes
/// the implicit selection, cursor on its last char (linewise: ON the
/// last pasted line's newline).
fn normalPaste(p: *Pardes, pane: *Pane, before: bool) void {
const y0 = p.yank orelse return;
if (y0.len == 0) return;
p.pushUndo(pane);
pane.select = false;
pane.sticky_col = -1;
const cnt: usize = @max(1, pane.count);
pane.count = 0;
const arena = p.scratch.allocator();
var y: []const u8 = y0;
if (cnt > 1) {
var buf: std.ArrayList(u8) = .empty;
for (0..cnt) |_| buf.appendSlice(arena, y0) catch return;
y = buf.items;
}
const b: Bounds = if (pane.vsel.active)
vselBounds(pane)
else
.{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col };
const eb = p.editText(pane, b.lo_row, b.hi_row, -1) orelse return;
const row0 = eb.row0;
if (y[y.len - 1] == '\n') {
const block_text = y[0 .. y.len - 1];
// a yanked BLANK line is "\n": the block is empty and lineCount
// says 0 lines, but it still pastes as one (empty) line — without
// the floor every `n - 1` below underflows and panics.
const n = @max(1, modal.lineCount(block_text));
var out: []u8 = undefined;
if (before) {
const row: usize = @intCast(@max(0, b.lo_row - row0));
const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return;
out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return;
pane.cur_row = @as(i32, @intCast(row + n - 1)) + row0;
} else {
const row: usize = @intCast(@max(0, b.hi_row - row0));
out = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return;
pane.cur_row = @as(i32, @intCast(row + n)) + row0;
}
p.setEditText(pane, out);
pane.vsel = .{ .active = true, .row = pane.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false };
// cursor ON the last pasted line's '\n' (helix)
const llen = modal.lineSlice(out, @intCast(@max(0, pane.cur_row - row0))).len;
pane.cur_col = @intCast(llen);
} else {
const at: modal.Cursor = if (before)
.{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) }
else blk: {
const hrow: usize = @intCast(@max(0, b.hi_row - row0));
const gcol = @as(usize, @intCast(@max(0, b.hi_col))) + 1;
if (gcol > modal.lineSlice(eb.text, hrow).len) break :blk .{ .row = hrow + 1, .col = 0 };
break :blk .{ .row = hrow, .col = gcol };
};
const out = modal.insertAt(p.gpa, eb.text, at, y) catch return;
p.setEditText(pane, out);
pane.vsel = .{ .active = y.len > 1, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false };
const end = modal.advanceBy(at, y);
if (end.col > 0) {
pane.cur_row = @as(i32, @intCast(end.row)) + row0;
pane.cur_col = @intCast(end.col - 1);
} else {
pane.cur_row = @as(i32, @intCast(end.row -| 1)) + row0;
pane.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len);
}
}
pane.msel.active = false;
pane.cur_pinned = true;
pane.ensureCursorVisible();
}
fn normalChange(p: *Pardes, pane: *Pane) void {
pane.select = false;
pane.sticky_col = -1;
if (pane.vsel.active) {
const b = vselBounds(pane);
const eb = p.editTextEol(pane, b) orelse return;
// helix: a LINEWISE selection (whole lines incl. their final
// newline) deletes the lines and opens a fresh one above,
// copying the indent of the line that moves up
const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len;
if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) {
p.setYank(p.vselText(pane));
p.pushUndo(pane);
const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return;
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
const n = modal.lineCount(d.content);
const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1);
const ind = modal.hxIndentString(modal.lineSlice(d.content, row));
const arena = p.scratch.allocator();
const block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return;
const new = modal.insertAt(p.gpa, d.content, .{ .row = row, .col = 0 }, block) catch return;
p.setEditText(pane, new);
pane.cur_row = @as(i32, @intCast(row)) + eb.row0;
pane.cur_col = @intCast(ind.len);
pane.vsel.active = false;
pane.msel.active = false;
pane.cur_pinned = true;
pane.mode = .insert;
pane.pending = 0;
pane.ensureCursorVisible();
return;
}
p.setYank(p.vselText(pane));
p.pushUndo(pane);
const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch {
pane.vsel.active = false;
return;
};
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
pane.cur_row = b.lo_row;
pane.cur_col = b.lo_col;
clampCursor(pane, d.content, eb.row0);
pane.mode = .insert;
pane.pending = 0;
return;
}
if (pane.msel.active) {
const r0 = @min(pane.msel.r0, pane.msel.r1);
const r1 = @max(pane.msel.r0, pane.msel.r1);
p.pushUndo(pane);
const eb = p.editText(pane, r0, r1 + 1, -1) orelse return;
// keep one empty line at r0, drop the rest; yank the removed
var buf: std.ArrayList(u8) = .empty;
const arena = p.scratch.allocator();
const lo: usize = @intCast(@max(0, r0 - eb.row0));
const hi: usize = @intCast(@max(0, r1 - eb.row0));
var r: usize = lo;
while (r <= hi) : (r += 1) {
if (r > lo) buf.append(arena, '\n') catch break;
buf.appendSlice(arena, modal.lineSlice(eb.text, r)) catch break;
}
p.setYank(buf.items);
var body: []u8 = eb.text;
if (hi > lo) {
const d = modal.deleteLines(p.gpa, body, lo + 1, hi) catch {
pane.msel.active = false;
return;
};
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
body = d.content;
}
const cl = modal.clearLine(p.gpa, body, lo) catch {
pane.msel.active = false;
return;
};
p.setEditText(pane, cl);
pane.cur_row = r0;
pane.cur_col = 0;
pane.msel.active = false;
pane.cur_pinned = true;
pane.mode = .insert;
pane.pending = 0;
pane.ensureCursorVisible();
} else {
p.pushUndo(pane);
const eb = p.editTextEol(pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return;
const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) };
const arena = p.scratch.allocator();
p.setYank(modal.rangeText(arena, eb.text, c, c) catch return);
const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return;
p.setEditText(pane, d.content);
p.gpa.free(d.deleted);
const llen = modal.lineSlice(d.content, c.row).len;
pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen)));
pane.mode = .insert;
pane.pending = 0;
}
}
// ---- helix change ops (r R ~ ` J > < Ctrl-a m-mode ]space) ----
// Terminals go through the same edit buffer as files: since editText
// materializes one over whatever rows the op names, every one of these
// works the same in a shell pane as in a document.
/// the selection as an inclusive cursor range in `content`, whose first
/// line is absolute row `row0`: vsel span, msel line span, else the char
/// under the cursor (helix's implicit 1-wide selection)
fn selRange(pane: *Pane, content: []const u8, row0: i32) modal.Range {
if (pane.vsel.active) {
const b = vselBounds(pane);
return .{
.a = .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) },
.b = .{ .row = @intCast(@max(0, b.hi_row - row0)), .col = @intCast(@max(0, b.hi_col)) },
};
}
if (pane.msel.active) {
const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0));
const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0));
const llen = modal.lineSlice(content, r1).len;
return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = llen -| 1 } };
}
const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) };
return .{ .a = c, .b = c };
}
/// the rows an op's selection spans, absolute (what editText must cover)
fn selRows(pane: *Pane) Bounds {
if (pane.vsel.active) return vselBounds(pane);
if (pane.msel.active) return .{
.lo_row = @min(pane.msel.r0, pane.msel.r1),
.lo_col = 0,
.hi_row = @max(pane.msel.r0, pane.msel.r1),
.hi_col = 0,
};
return .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col };
}
/// `r<ch>`: overwrite the selection (or the cursor char) with ch —
/// newlines included (helix), so `xrz` joins the selected lines
fn normalReplaceChar(p: *Pardes, pane: *Pane, ch: u8) void {
pane.select = false;
const eb = p.editTextEol(pane, selRows(pane)) orelse return;
const r = selRange(pane, eb.text, eb.row0);
p.pushUndo(pane);
const new = modal.replaceChars(p.gpa, eb.text, r.a, r.b, ch) catch return;
p.setEditText(pane, new);
}
/// `R`: replace the selection (or the cursor char) with the yank register;
/// the pasted text becomes the selection, head on its last char (which
/// for a trailing-newline yank is the '\n' cell of the last full line)
fn normalReplaceYank(p: *Pardes, pane: *Pane) void {
const y = p.yank orelse return;
if (y.len == 0) return;
pane.select = false;
const eb = p.editTextEol(pane, selRows(pane)) orelse return;
const r = selRange(pane, eb.text, eb.row0);
p.pushUndo(pane);
const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, y) catch return;
p.setEditText(pane, new);
pane.msel.active = false;
pane.vsel = .{ .active = y.len > 1, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false };
const end = modal.advanceBy(r.a, y);
if (end.col > 0) {
pane.cur_row = @as(i32, @intCast(end.row)) + eb.row0;
pane.cur_col = @intCast(end.col - 1);
} else {
// the yank ended in '\n': the cursor lands ON that newline
pane.cur_row = @as(i32, @intCast(end.row -| 1)) + eb.row0;
pane.cur_col = @intCast(modal.lineSlice(new, end.row -| 1).len);
}
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
}
/// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char),
/// keeping the selection (helix)
fn normalCase(p: *Pardes, pane: *Pane, op: modal.CaseOp) void {
pane.select = false;
const eb = p.editTextEol(pane, selRows(pane)) orelse return;
const r = selRange(pane, eb.text, eb.row0);
p.pushUndo(pane);
const new = modal.changeCase(p.gpa, eb.text, r.a, r.b, op) catch return;
p.setEditText(pane, new);
}
/// a change to apply to file content: delete [from, to), insert `ins` at
/// `from`. Ascending and disjoint.
const TextChange = struct { from: usize, to: usize, ins: []const u8 };
/// map an original-text offset through a change list (insertions AT a
/// position push it right — helix Assoc::After; positions inside a
/// deleted span collapse to its start)
fn mapThroughChanges(chs: []const TextChange, pos: usize) usize {
var delta: i64 = 0;
for (chs) |ch| {
if (pos < ch.from) break;
if (ch.from == ch.to) {
delta += @intCast(ch.ins.len);
continue;
}
if (pos == ch.from) break;
if (pos < ch.to) return @intCast(@as(i64, @intCast(ch.from)) + delta);
delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from));
}
return @intCast(@as(i64, @intCast(pos)) + delta);
}
/// apply a change list. gpa-owned result.
fn applyChanges(p: *Pardes, text: []const u8, chs: []const TextChange) ![]u8 {
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(p.gpa);
var copied: usize = 0;
for (chs) |ch| {
try out.appendSlice(p.gpa, text[copied..ch.from]);
try out.appendSlice(p.gpa, ch.ins);
copied = ch.to;
}
try out.appendSlice(p.gpa, text[copied..]);
return out.toOwnedSlice(p.gpa);
}
/// `J`: helix join_selections — join the selection's line span (a bare
/// cursor joins with the next line): each '\n' + following indent become
/// one space, EXCEPT before content-less lines (no space) — and on the
/// buffer's last line the trailing newline is deleted. The selection and
/// cursor map through the edit; the count is ignored (helix).
fn normalJoin(p: *Pardes, pane: *Pane) void {
// a join always eats the newline of its last line, so the buffer has
// to reach one row PAST the selection
const sr = selRows(pane);
const eb = p.editText(pane, sr.lo_row, sr.hi_row + 1, -1) orelse return;
const text = eb.text;
const range = paneRange(pane, text, eb.row0);
const span = rangeLineSpan(text, range);
const nlines = modal.hxLineCount(text);
var end = span.end;
if (span.start == end) end = @min(end + 1, nlines - 1);
if (end <= span.start) return;
const arena = p.scratch.allocator();
var chs: std.ArrayList(TextChange) = .empty;
var l = span.start;
while (l < end) : (l += 1) {
const from = modal.hxLineEndIdx(text, l);
var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1);
while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1;
const sep: []const u8 = if (to == modal.hxLineEndIdx(text, @min(l + 1, nlines - 1))) "" else " ";
chs.append(arena, .{ .from = from, .to = to, .ins = sep }) catch return;
}
if (chs.items.len == 0) return;
p.pushUndo(pane);
const cur_off = modal.hxOff(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) });
const anc_off = if (pane.vsel.active)
modal.hxOff(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) })
else
cur_off;
const new = p.applyChanges(text, chs.items) catch return;
const nc = mapThroughChanges(chs.items, cur_off);
const na = mapThroughChanges(chs.items, anc_off);
p.setEditText(pane, new);
const cc = modal.hxPos(new, nc);
const ac = modal.hxPos(new, na);
pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
pane.cur_col = @intCast(cc.col);
if (pane.vsel.active) {
pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0;
pane.vsel.col = @intCast(ac.col);
}
pane.msel.active = false;
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
}
/// `>` / `<`: helix indent/unindent over the selection's line span.
/// Blank (all-whitespace) lines are skipped; `>` inserts count levels
/// realigned to the next INDENT_W stop; `<` removes up to count levels of
/// leading whitespace (a tab advances to the next stop). Cursor and
/// selection map through the edit.
fn normalIndent(p: *Pardes, pane: *Pane, cnt: usize, add: bool) void {
pane.select = false;
const sr = selRows(pane);
const eb = p.editText(pane, sr.lo_row, sr.hi_row, -1) orelse return;
const text = eb.text;
const range = paneRange(pane, text, eb.row0);
const span = rangeLineSpan(text, range);
const arena = p.scratch.allocator();
// one run of spaces, sliced per line: `>` never inserts more than this
const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return;
@memset(pad, ' ');
var chs: std.ArrayList(TextChange) = .empty;
var l = span.start;
while (l <= span.end) : (l += 1) {
const ls = modal.lineStartOffset(text, l);
const le = modal.hxLineEndIdx(text, l);
const line = text[ls..le];
const nw = modal.firstNonWs(line);
if (nw == line.len) continue; // blank lines stay blank (helix)
if (add) {
const ins = modal.INDENT_W * cnt - (nw % modal.INDENT_W);
chs.append(arena, .{ .from = ls, .to = ls, .ins = pad[0..ins] }) catch return;
} else {
const want = modal.INDENT_W * cnt;
var w: usize = 0;
var pos: usize = 0;
while (pos < line.len) {
if (line[pos] == ' ') {
w += 1;
} else if (line[pos] == '\t') {
w = (w / modal.INDENT_W + 1) * modal.INDENT_W;
} else break;
pos += 1;
if (w >= want) break;
}
if (pos > 0) chs.append(arena, .{ .from = ls, .to = ls + pos, .ins = "" }) catch return;
}
}
if (chs.items.len == 0) return;
p.pushUndo(pane);
const cur_off = modal.hxOff(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) });
const anc_off = if (pane.vsel.active)
modal.hxOff(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) })
else
cur_off;
const new = p.applyChanges(text, chs.items) catch return;
const nc = mapThroughChanges(chs.items, cur_off);
const na = mapThroughChanges(chs.items, anc_off);
p.setEditText(pane, new);
const cc = modal.hxPos(new, nc);
const ac = modal.hxPos(new, na);
pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
pane.cur_col = @intCast(cc.col);
if (pane.vsel.active) {
pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0;
pane.vsel.col = @intCast(ac.col);
}
pane.msel.active = false;
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
}
/// `Ctrl-c`: helix toggle_comments. Every line the selection touches gets
/// the language's line-comment token put in front of it — or taken off,
/// and WHICH of the two is decided once for the whole set: one uncommented
/// non-blank line among them and everything gets commented. That single
/// decision is why Action.scope runs this once instead of per cursor;
/// replayed, a half-commented block would end up half-commented the other
/// way round.
///
/// The rest is helix's find_line_comment, quirks included: the token goes
/// in at the SHALLOWEST indent in the set (so a deeper line is commented
/// mid-whitespace), all-blank lines are skipped entirely and do not vote,
/// and uncommenting also eats one space after the token unless some line
/// lacks it.
fn normalToggleComment(p: *Pardes, pane: *Pane) void {
const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active;
pane.select = false; // helix exit_select_mode
// the buffer must cover every cursor's rows, not just the primary's
var b = selRows(pane);
for (pane.sels[0..pane.nsel]) |s| {
b.lo_row = @min(b.lo_row, @min(s.row, s.arow));
b.hi_row = @max(b.hi_row, @max(s.row, s.arow));
}
// ...and ONE ROW PAST them, like normalJoin: a selection may end on
// its last line's newline cell, and a terminal buffer that stops at
// that line has nowhere to put it (a file's content always does).
// Never past the surface's own last row, though — materialising a row
// that does not exist yet would ADD a blank line to the pane, and this
// op may well decide to change nothing.
const pl0 = p.paneCursorLines(pane) catch return;
const last_row = pl0.row0 + @as(i32, @intCast(pl0.lines.len)) - 1;
const eb = p.editText(pane, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return;
const text = eb.text;
var rs: [MAX_SELS]modal.HxRange = undefined;
const got = paneRanges(pane, text, eb.row0, &rs);
const nlines = modal.hxLineCount(text);
const arena = p.scratch.allocator();
// the lines the ranges cover, each ONE ONCE and in order (helix's
// min_next_line: two cursors on one line comment it once)
var lines: std.ArrayList(usize) = .empty;
var next: usize = 0;
for (rs[0..got.n]) |r| {
const span = rangeLineSpan(text, r);
var l = @max(span.start, next);
const end = @min(span.end + 1, nlines);
while (l < end) : (l += 1) lines.append(arena, l) catch return;
next = @max(next, end);
}
// which token: the file's EXTENSION, which is the same thing
// src/syntax.zig tells languages apart by, read off the one table in
// config. A terminal and an output buffer have no extension and get
// the default, which is what helix does for a buffer with no language.
const ext = if (pane.file) |f| std.fs.path.extension(f.path) else "";
var token: []const u8 = config.comment_token_default;
lang: for (config.comment_tokens) |row| {
for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) {
token = row.token;
break :lang;
};
}
var commented = true;
var indent: usize = std.math.maxInt(usize);
var margin: usize = 1;
var live: usize = 0;
for (lines.items) |l| {
const line = text[modal.lineStartOffset(text, l)..modal.hxLineEndIdx(text, l)];
const nw = modal.firstNonWs(line);
if (nw == line.len) continue;
indent = @min(indent, nw);
if (!std.mem.startsWith(u8, line[nw..], token)) commented = false;
if (nw + token.len >= line.len or line[nw + token.len] != ' ') margin = 0;
live += 1;
}
if (live == 0) return; // nothing but blank lines
const ins = std.fmt.allocPrint(arena, "{s} ", .{token}) catch return;
var chs: std.ArrayList(TextChange) = .empty;
for (lines.items) |l| {
const ls = modal.lineStartOffset(text, l);
const le = modal.hxLineEndIdx(text, l);
const line = text[ls..le];
if (modal.firstNonWs(line) == line.len) continue; // blank lines untouched
const at = ls + indent;
// the @min can never bind: margin is 1 only when every line has a
// space after its own token, which is a byte past `at + token.len`
chs.append(arena, if (commented)
.{ .from = at, .to = @min(at + token.len + margin, le), .ins = "" }
else
.{ .from = at, .to = at, .ins = ins }) catch return;
}
p.pushUndo(pane);
// one edit, and the WHOLE selection rides through it (helix maps the
// selection with the transaction)
var cells: [MAX_SELS]SelRange = undefined;
const new = p.applyChanges(text, chs.items) catch return;
for (rs[0..got.n], 0..) |r, i| {
const c = rangeCells(new, .{
.anchor = mapThroughChanges(chs.items, r.anchor),
.head = mapThroughChanges(chs.items, r.head),
});
const cc = modal.hxPos(new, c.cur);
const ac = modal.hxPos(new, c.anc);
cells[i] = .{
.row = @as(i32, @intCast(cc.row)) + eb.row0,
.col = @intCast(cc.col),
.arow = @as(i32, @intCast(ac.row)) + eb.row0,
.acol = @intCast(ac.col),
};
}
p.setEditText(pane, new);
const pl2 = p.paneCursorLines(pane) catch return;
const t2 = p.flatSurface(pane, pl2) catch return;
for (cells[0..got.n], 0..) |s, i| rs[i] = cellRange(t2, s.arow - pl2.row0, s.acol, s.row - pl2.row0, s.col);
setPaneRanges(pane, pl2, t2, rs[0..got.n], &.{}, got.pri, expl);
}
/// `Ctrl-a` / `Ctrl-x`: increment/decrement the SELECTION as a decimal
/// integer (helix: the selected fragment itself, no number scan around
/// the cursor); a fragment that isn't an integer is a no-op. The new
/// number becomes the selection, cursor on its last char.
fn normalAdjustNumber(p: *Pardes, pane: *Pane, delta: i64) void {
const eb = p.editTextEol(pane, selRows(pane)) orelse return;
const r = selRange(pane, eb.text, eb.row0);
const arena = p.scratch.allocator();
const frag = modal.rangeText(arena, eb.text, r.a, r.b) catch return;
const rep = (modal.hxIncrement(arena, frag, delta) catch null) orelse return;
p.pushUndo(pane);
pane.select = false;
const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, rep) catch return;
p.setEditText(pane, new);
const start = modal.lineStartOffset(new, r.a.row) + r.a.col;
const cc = modal.hxPos(new, start + rep.len - 1);
pane.vsel = .{ .active = rep.len > 1, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false };
pane.msel.active = false;
pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
pane.cur_col = @intCast(cc.col);
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
}
/// `]Space` / `[Space`: add blank lines below/above, the cursor staying
/// on its text line (the selection rides along)
fn addNewline(p: *Pardes, pane: *Pane, below: bool, cnt: usize) void {
const eb = p.editText(pane, pane.cur_row, pane.cur_row, -1) orelse return;
p.pushUndo(pane);
const row: usize = @intCast(@max(0, pane.cur_row - eb.row0));
const arena = p.scratch.allocator();
const nl = arena.alloc(u8, cnt) catch return;
@memset(nl, '\n');
const llen = modal.lineSlice(eb.text, row).len;
const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return;
p.setEditText(pane, new);
if (!below) {
pane.cur_row += @intCast(cnt); // the line moved down; stay on it
if (pane.vsel.active and pane.vsel.row >= @as(i32, @intCast(row))) pane.vsel.row += @intCast(cnt);
} else if (pane.vsel.active and pane.vsel.row > @as(i32, @intCast(row))) {
pane.vsel.row += @intCast(cnt);
}
pane.cur_pinned = true;
pane.ensureCursorVisible();
}
/// pair mapping for m-mode: either bracket names the pair; anything else
/// surrounds with itself (quotes)
fn pairFor(ch: u21) ?struct { o: u8, c: u8 } {
return switch (ch) {
'(', ')' => .{ .o = '(', .c = ')' },
'[', ']' => .{ .o = '[', .c = ']' },
'{', '}' => .{ .o = '{', .c = '}' },
'<', '>' => .{ .o = '<', .c = '>' },
else => if (ch <= 0x7f) .{ .o = @intCast(ch), .c = @intCast(ch) } else null,
};
}
/// `mi<obj>` / `ma<obj>`: select inside/around a textobject (pure range
/// math over the motion surface — works on terminals too). Word and
/// paragraph objects are helix textobject.rs ports; pairs/quotes are the
/// plain-text scans (quotes line-scoped — ponytail).
fn textobjectSelect(p: *Pardes, pane: *Pane, pl: PaneLines, obj: u21, around: bool) void {
const text = p.flatSurface(pane, pl) catch return;
const range = paneRange(pane, text, pl.row0);
switch (obj) {
'w', 'W' => {
const r = modal.hxTextobjectWord(text, range, around, obj == 'W');
return setPaneRange(pane, pl, text, r, false);
},
'p' => {
const r = modal.hxTextobjectParagraph(text, range, around, 1);
return setPaneRange(pane, pl, text, r, false);
},
else => {},
}
const cur = modal.hxPos(text, modal.hxCursor(text, range));
const pair: ?modal.Range = switch (obj) {
'\'', '"', '`' => modal.enclosingQuote(pl.lines, cur, @intCast(obj)),
'(', ')' => modal.enclosingPair(pl.lines, cur, '(', ')'),
'[', ']' => modal.enclosingPair(pl.lines, cur, '[', ']'),
'{', '}' => modal.enclosingPair(pl.lines, cur, '{', '}'),
'<', '>' => modal.enclosingPair(pl.lines, cur, '<', '>'),
else => null,
};
const pr = pair orelse return;
var a = modal.hxOff(text, pr.a);
var head = modal.nextGrapheme(text, modal.hxOff(text, pr.b));
if (!around) {
// inside: shrink off the delimiters; an EMPTY pair collapses to
// a 1-wide cursor on the closing char (helix)
a = modal.nextGrapheme(text, a);
head = modal.prevGrapheme(text, head);
}
setPaneRange(pane, pl, text, .{ .anchor = a, .head = head }, false);
}
/// `ms<ch>`: wrap the selection (or the cursor char) in a pair; the wrap
/// including the pair becomes the selection
fn surroundAdd(p: *Pardes, pane: *Pane, ch: u21) void {
const pr = pairFor(ch) orelse return;
pane.select = false;
const eb = p.editTextEol(pane, selRows(pane)) orelse return;
const r = selRange(pane, eb.text, eb.row0);
p.pushUndo(pane);
var new = modal.insertAt(p.gpa, eb.text, .{ .row = r.b.row, .col = r.b.col + 1 }, &[1]u8{pr.c}) catch return;
p.setEditText(pane, new);
new = modal.insertAt(p.gpa, new, .{ .row = r.a.row, .col = r.a.col }, &[1]u8{pr.o}) catch return;
p.setEditText(pane, new);
pane.msel.active = false;
pane.vsel = .{ .active = true, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false };
pane.cur_row = @as(i32, @intCast(r.b.row)) + eb.row0;
pane.cur_col = @intCast(r.b.col + 1 + @as(usize, if (r.a.row == r.b.row) 1 else 0));
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
}
/// `md<ch>`: delete the enclosing pair's chars; the cursor maps through
fn surroundDelete(p: *Pardes, pane: *Pane, pl: PaneLines, ch: u21) void {
const pr = pairFor(ch) orelse return;
// the pair is found over the motion surface, whose rows are absolute;
// the edit runs in the buffer covering those rows, and every offset
// below is taken in THAT text so the cursor maps through it
const cur = toModalCursor(pane, pl);
const r = (if (pr.o == pr.c)
modal.enclosingQuote(pl.lines, cur, pr.o)
else
modal.enclosingPair(pl.lines, cur, pr.o, pr.c)) orelse return;
const lo: i32 = @intCast(@min(r.a.row, cur.row));
const hi: i32 = @intCast(@max(r.b.row, cur.row));
const eb = p.editText(pane, lo + pl.row0, hi + pl.row0, -1) orelse return;
const text = eb.text;
const drow = pl.row0 - eb.row0; // surface row -> buffer row
const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col };
const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col };
p.pushUndo(pane);
const a_off = modal.hxOff(text, ra);
const b_off = modal.hxOff(text, rb);
const cur_off = modal.hxOff(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col });
// the close first, so the open's position stays valid
var new = modal.deleteChar(p.gpa, text, rb) catch return;
p.setEditText(pane, new);
new = modal.deleteChar(p.gpa, new, ra) catch return;
p.setEditText(pane, new);
var nc = cur_off;
if (nc > b_off) nc -= 1;
if (nc > a_off) nc -= 1;
const cc = modal.hxPos(new, nc);
pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0;
pane.cur_col = @intCast(cc.col);
pane.vsel.active = false;
pane.msel.active = false;
pane.cur_pinned = true;
pane.ensureCursorVisible();
}
/// `mr<from><to>`: swap the enclosing <from> pair's chars for <to>'s
fn surroundReplace(p: *Pardes, pane: *Pane, pl: PaneLines, from: u21, to: u21) void {
const fp = pairFor(from) orelse return;
const tp = pairFor(to) orelse return;
const cur = toModalCursor(pane, pl);
const r = (if (fp.o == fp.c)
modal.enclosingQuote(pl.lines, cur, fp.o)
else
modal.enclosingPair(pl.lines, cur, fp.o, fp.c)) orelse return;
const eb = p.editText(pane, @as(i32, @intCast(r.a.row)) + pl.row0, @as(i32, @intCast(r.b.row)) + pl.row0, -1) orelse return;
const drow = pl.row0 - eb.row0; // surface row -> buffer row
const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow);
const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow);
p.pushUndo(pane);
const out = p.gpa.dupe(u8, eb.text) catch return;
out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o;
out[modal.lineStartOffset(out, br) + r.b.col] = tp.c;
p.setEditText(pane, out);
}
// ---- dumb undo/redo: whole-state snapshots, one per edit op ----
/// pull the cursor back inside `text` after a rewrite; `row0` is the
/// absolute surface row of its first line (0 for a file)
fn clampCursor(pane: *Pane, text: []const u8, row0: i32) void {
const n = modal.lineCount(text);
const row: usize = @min(@as(usize, @intCast(@max(0, pane.cur_row - row0))), if (n == 0) 0 else n - 1);
const llen = modal.lineSlice(text, row).len;
pane.cur_row = @as(i32, @intCast(row)) + row0;
pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, pane.cur_col))), llen));
pane.cur_pinned = true;
pane.vsel.active = false;
pane.msel.active = false;
pane.ensureCursorVisible();
}
fn pushUndo(p: *Pardes, pane: *Pane) void {
// one keystroke, one undo step — even when it edited at ten cursors.
// (The content-equality guard below cannot do this on its own: by the
// second pass the buffer HAS changed, so it would push again.)
if (p.multi_on and !p.multi_first) return;
if (pane.file) |*f| {
if (f.undo.items.len > 0 and std.mem.eql(u8, f.undo.items[f.undo.items.len - 1].content, f.content)) return;
const snap: FileSnap = .{
.content = p.gpa.dupe(u8, f.content) catch return,
.cur_row = pane.cur_row,
.cur_col = pane.cur_col,
.vsel = pane.vsel,
};
f.undo.append(p.gpa, snap) catch {
p.gpa.free(snap.content);
return;
};
if (f.undo.items.len > UNDO_MAX) p.gpa.free(f.undo.orderedRemove(0).content);
for (f.redo.items) |s| p.gpa.free(s.content);
f.redo.clearRetainingCapacity();
} else {
const cur = pane.ovl orelse Ovl{ .rows = 0 };
if (pane.ed_undo.getLastOrNull()) |top| {
const same = if (top.ovl) |o| pane.ovl != null and o.row == cur.row and
o.rows == cur.rows and std.mem.eql(u8, o.text, cur.text) else pane.ovl == null;
if (same) return;
}
const snap = term_pane.snap(p, pane) orelse return;
pane.ed_undo.append(p.gpa, snap) catch {
if (snap.ovl) |o| p.gpa.free(o.text);
return;
};
if (pane.ed_undo.items.len > EDIT_UNDO_MAX) {
const drop = pane.ed_undo.orderedRemove(0);
if (drop.ovl) |o| p.gpa.free(o.text);
}
for (pane.ed_redo.items) |sn| if (sn.ovl) |o| p.gpa.free(o.text);
pane.ed_redo.clearRetainingCapacity();
}
}
fn doUndo(p: *Pardes, pane: *Pane) void {
if (pane.file) |*f| {
if (f.undo.items.len == 0) return;
const cur: FileSnap = .{
.content = p.gpa.dupe(u8, f.content) catch return,
.cur_row = pane.cur_row,
.cur_col = pane.cur_col,
.vsel = pane.vsel,
};
f.redo.append(p.gpa, cur) catch {
p.gpa.free(cur.content);
return;
};
const prev = f.undo.pop() orelse return;
file_pane.setContent(p, f, prev.content);
file_pane.restoreSnap(pane, f, prev);
return;
}
if (pane.ed_undo.items.len == 0) return;
const cur = term_pane.snap(p, pane) orelse return;
pane.ed_redo.append(p.gpa, cur) catch {
if (cur.ovl) |o| p.gpa.free(o.text);
return;
};
term_pane.restoreSnap(p, pane, pane.ed_undo.pop() orelse return);
}
fn doRedo(p: *Pardes, pane: *Pane) void {
if (pane.file) |*f| {
if (f.redo.items.len == 0) return;
const cur: FileSnap = .{
.content = p.gpa.dupe(u8, f.content) catch return,
.cur_row = pane.cur_row,
.cur_col = pane.cur_col,
.vsel = pane.vsel,
};
f.undo.append(p.gpa, cur) catch {
p.gpa.free(cur.content);
return;
};
const next = f.redo.pop() orelse return;
file_pane.setContent(p, f, next.content);
file_pane.restoreSnap(pane, f, next);
return;
}
if (pane.ed_redo.items.len == 0) return;
const cur = term_pane.snap(p, pane) orelse return;
pane.ed_undo.append(p.gpa, cur) catch {
if (cur.ovl) |o| p.gpa.free(o.text);
return;
};
term_pane.restoreSnap(p, pane, pane.ed_redo.pop() orelse return);
}
/// Something outside pardes rewrote a file we have open. Commit the buffer
/// we are holding — unsaved edits and all — onto the undo stack, then swap
/// in the bytes from disk.
///
/// THAT IS THE WHOLE DESIGN, not an implementation detail. An external
/// update is pushed exactly like an edit the user typed, so `u` walks back
/// to the buffer as it was a keystroke ago and unsaved work is never lost.
/// It is also why the feature is nearly free: pardes never has to merge its
/// buffer against the new file, never has to ask "reload? keep? diff?", and
/// there is no third state between "what is on disk" and "what I typed" —
/// the undo stack, which already exists, IS the history of both.
fn fileChanged(p: *Pardes, id: u8, bytes: []const u8) void {
const pane = p.panes[id] orelse return;
if (pane.file == null) return;
const f = &pane.file.?;
// the disk arrived at what we already hold: an undo step that changes
// nothing is worse than no undo step
if (std.mem.eql(u8, f.content, bytes)) return;
const new = p.gpa.dupe(u8, bytes) catch return;
p.pushUndo(pane);
file_pane.setContent(p, f, new);
// keep the cursor where it was, clamped onto the new text: restoreSnap
// reads only the cursor and selection out of the snapshot it is handed,
// so handing it the pane's own is exactly "clamp what you have".
file_pane.restoreSnap(pane, f, .{
.content = undefined,
.cur_row = pane.cur_row,
.cur_col = pane.cur_col,
.vsel = pane.vsel,
});
}
fn handleMouse(p: *Pardes, m: Mouse) void {
const mcol = @min(m.col, p.screen_w -| 1);
const mrow = @min(m.row, p.screen_h -| 1);
p.hover_col = mcol;
p.hover_row = mrow;
const hovered: ?usize = for (p.panes, 0..) |slot, i| {
if (slot == null) continue;
const r = p.rects[i];
if (mcol >= r.x and mcol < r.x + r.w and mrow >= r.y and mrow < r.y + r.h) break i;
} else null;
// any press that is NOT the execute+select chord abandons a pending
// chord argument
if (m.kind == .press and
!(m.button == config.select_button and p.drag == .select and p.drag.select.button == config.exec_button))
{
if (p.chord_arg) |a| {
p.gpa.free(a);
p.chord_arg = null;
}
}
// ...and any press at all takes the keyboard back off the topbar: the
// mouse names where focus goes, so leaving a cursor parked on row 0
// while you click into a pane would just be a lie
if (m.kind == .press) p.topbar_col = null;
switch (m.button) {
.none => {}, // hover tracked above; motion has no other meaning
.wheel_up, .wheel_down => {
if (m.kind != .press) return;
// re-arms the drift guard below; vertical always scrolls, so
// the answer is never in doubt here
_ = config.wheelTick(&p.wheel_guard, true);
const id = hovered orelse return;
const pane = p.panes[id].?;
if (hasPdf(pane))
p.pdfVerticalWheel(pane, if (m.button == .wheel_up) -1 else 1)
else
pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows);
},
.wheel_left, .wheel_right => {
if (m.kind != .press) return;
// a mostly-vertical two-finger swipe's sideways drift dies
// here rather than sliding the view out from under a scroll.
// Charged against the gesture, not the pane, so it runs before
// we ask what is hovered.
if (!config.wheelTick(&p.wheel_guard, false)) return;
const id = hovered orelse return;
const pane = p.panes[id].?;
if (hasPdf(pane)) {
p.pdfHorizontalWheel(pane, if (m.button == .wheel_right) 1 else -1);
// ponytail: no right clamp — overscroll shows blank and the
// next cursor move or left wheel pulls it back
} else if (pane.file != null and !p.wrap_on) {
// wrapped there is nothing off to the right to reach
pane.hscroll = @max(0, pane.hscroll + (if (m.button == .wheel_right) config.wheel_cols else -config.wheel_cols));
}
},
config.select_button => switch (m.kind) {
.press => {
// acme 2-1: a select press during an EXECUTE drag captures
// a selection (heldSelection) as the execute's argument;
// the execute drag keeps running to its release, which
// consumes it.
if (p.drag == .select and p.drag.select.button == config.exec_button) {
if (p.heldSelection(p.drag.select.id)) |tx| {
if (p.chord_arg) |old| p.gpa.free(old);
p.chord_arg = p.gpa.dupe(u8, tx) catch null;
}
return;
}
// acme 3-1: a select tap during a LOOK drag cancels the
// look; the rest of the gesture is inert
if (p.drag == .select and p.drag.select.button == config.look_button) {
if (p.panes[p.drag.select.id]) |t| t.sel[@intFromEnum(config.look_button)].state = .none;
p.drag = .none;
return;
}
if (mrow < TOPBAR_H) return; // topbar: a select click is deliberately inert
// the layout box (gutter cells of the tag row) wins over
// the resize handles: a tag-only pane's single row IS its
// pair's h-handle, and the box must stay grabbable to move
if (hovered) |mid| {
const mr = p.rects[mid];
if (mcol < mr.x + config.GUTTER and mrow < mr.y + BOX_H) {
p.drag = .{ .move = .{ .id = mid, .cur_x = mcol, .cur_y = mrow } };
return;
}
}
// resize handles next: a pane's own trailing edge (v: the
// left column's last col; h: the upper pane's last row).
// The v test still wins outright, but it now also asks
// whether this same cell is one of ITS OWN column's h
// handles — that cell is the corner where the two lines
// cross, and grabbing it drags both boundaries at once
// (see Drag.border_v for why only the left column counts).
for (0..p.ncol -| 1) |c| {
if (mcol == p.col_x[c] + p.col_w[c] -| 1) {
var corner: ?usize = null;
for (0..p.col_n[c] -| 1) |k| {
const r = p.rects[p.col_terms[c][k]];
if (mrow == r.y + r.h -| 1) {
corner = k;
break;
}
}
p.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner_idx = corner, .cur_y = mrow } };
return;
}
}
for (0..p.ncol) |cc| {
if (mcol < p.col_x[cc] or mcol >= p.col_x[cc] + p.col_w[cc]) continue;
for (0..p.col_n[cc] -| 1) |k| {
const r = p.rects[p.col_terms[cc][k]];
if (mrow == r.y + r.h -| 1) {
p.drag = .{ .border_h = .{ .col = cc, .top_idx = k, .cur_y = mrow } };
return;
}
}
}
const id = hovered orelse return;
const r = p.rects[id];
const pane = p.panes[id] orelse return;
if (mcol < r.x + config.GUTTER) {
// gutter scrollbar: a left click scrolls UP to that row
p.active = id;
pane.scrollBy(-(@as(i32, mrow) - @as(i32, r.y + BOX_H)));
} else if (mrow < r.y + BOX_H) {
// left press on the tag row: focus the tag AT that
// column (a rendered-tag column — the mouse and the tag
// agree, no clamp into the tail) and anchor a sweep, so
// dragging selects any span of it, path included
p.active = id;
p.enterTagEdit(pane, @as(i32, mcol) - @as(i32, r.x + config.GUTTER));
pane.tag_anchor = pane.tag_col;
p.drag = .{ .tag = .{ .id = id } };
} else {
p.active = id;
exitTagEdit(pane); // clicking the body leaves tag editing
const sc: i32 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER);
const v: i32 = @as(i32, mrow) - @as(i32, r.y);
pane.sel[sel_slot] = .{ .state = .dragging, .c0 = sc, .c1 = sc, .r0 = v, .r1 = v };
const pdf_native = if (comptime pdf_enabled) p.pdfNativeReady(pane) else false;
if (pdf_native) _ = p.beginPdfDrag(pane, mcol, mrow, false);
// Ctrl rides on the drag rather than firing here: the
// click does not place the modal cursor until RELEASE
// (dragRelease), and a goto asked at press time would
// answer about wherever the cursor happened to be.
p.drag = .{ .select = .{
.id = id,
.button = config.select_button,
.ctrl = m.ctrl,
.pdf = if (comptime pdf_enabled) .{ .native = pdf_native } else .{},
} };
}
},
.drag => p.dragUpdate(mcol, mrow),
.release => p.dragRelease(config.select_button),
.motion => {},
},
config.exec_button, config.look_button => switch (m.kind) {
.press => {
// acme 1-2 / 1-3: the execute (Cut) or look (Paste) button
// tapped while the select button holds a selection drag
if (p.drag == .select and p.drag.select.button == config.select_button) {
p.chordCutPaste(m.button == config.exec_button);
return;
}
// acme 2-3 / 3-2: tapping the OTHER of execute/look during
// an execute or look drag cancels it (textselect23's mask)
if (p.drag == .select) {
if (p.panes[p.drag.select.id]) |t| t.sel[@intFromEnum(p.drag.select.button)].state = .none;
p.drag = .none;
return;
}
if (mrow < TOPBAR_H) {
// global tagbar: EXECUTE runs the command under the
// click (a stray select click must never Kill)
if (m.button == config.exec_button) {
var tb_buf: [1200]u8 = undefined;
const word = wordAtCol(p.topbar(&tb_buf), mcol);
// a topbar word runs on the PRESS — there is no
// drag to chord into, so the argument is simply
// whatever is selected right now: select a word,
// then click Grep, and it greps that word.
if (word.len > 0) _ = p.execute(p.active, p.withArg(word, p.heldSelection(p.active)));
}
return;
}
const id = hovered orelse return;
const r = p.rects[id];
const pane = p.panes[id] orelse return;
if (mcol < r.x + config.GUTTER and mrow >= r.y + BOX_H) {
// gutter: right scrolls DOWN to here, mirroring left's up;
// middle matches left. Right focuses (look lands you
// there); middle does not.
const local = @as(i32, mrow) - @as(i32, r.y + BOX_H);
if (m.button == config.look_button) p.active = id;
pane.scrollBy(if (m.button == config.look_button) local else -local);
} else if (mcol >= r.x + config.GUTTER) {
if (m.button == config.look_button) p.active = id;
const c: i32 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER);
const v: i32 = @as(i32, mrow) - @as(i32, r.y);
pane.sel[@intFromEnum(m.button)] = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v };
// Once a body gesture starts over a native PDF, keep
// it native even when the point misses a letterbox or
// selection fails. pdfDragRelease makes a null anchor
// inert instead of executing hidden projected text.
// Tag clicks remain ordinary text/builtin gestures.
const pdf_native = if (comptime pdf_enabled)
mrow >= r.y + BOX_H and p.pdfNativeReady(pane)
else
false;
if (pdf_native) _ = p.beginPdfDrag(pane, mcol, mrow, true);
p.drag = .{ .select = .{
.id = id,
.button = m.button,
.pdf = if (comptime pdf_enabled) .{ .native = pdf_native } else .{},
} };
}
},
.drag => p.dragUpdate(mcol, mrow),
.release => p.dragRelease(m.button),
.motion => {},
},
}
}
fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16) void {
switch (p.drag) {
.border_v => |*d| {
const c = d.left_col;
d.cur_x = if (c + 1 < p.ncol)
clampBorderCol(p.col_x[c], p.col_w[c], p.col_w[c + 1], mcol)
else
mcol;
// a corner also drives left_col's pane pair, off the SAME mouse
// position but through its own clamp — the geometry a clamp
// reads (widths for x, heights for y) is frozen for the whole
// drag and never crosses axes, so one edge parked at its stop
// leaves the other tracking the mouse
if (d.corner_idx) |k| if (k + 1 < p.col_n[c]) {
const a = p.rects[p.col_terms[c][k]];
const b = p.rects[p.col_terms[c][k + 1]];
d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow);
} else {
d.cur_y = mrow;
};
},
.border_h => |*d| {
const cc = d.col;
const k = d.top_idx;
if (k + 1 < p.col_n[cc]) {
const a = p.rects[p.col_terms[cc][k]];
const b = p.rects[p.col_terms[cc][k + 1]];
d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow);
} else d.cur_y = mrow;
},
.move => |*d| {
d.cur_x = mcol;
d.cur_y = mrow;
},
.select => |*s| {
if (p.panes[s.id]) |pane| {
const r = p.rects[s.id];
const b = @intFromEnum(s.button);
pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER);
pane.sel[b].r1 = @as(i32, mrow) - @as(i32, r.y);
if (comptime pdf_enabled) {
if (s.pdf.native) {
if (p.updatePdfSelection(pane, mcol, mrow, false))
s.pdf.selection_changed = true;
}
}
}
},
.tag => |d| {
// the tag cursor follows the mouse across the rendered tag; the
// row is ignored (a tag is one line) and the anchor stays where
// the press put it, so this is the mouse's `v`
const pane = p.panes[d.id] orelse return;
const end: i32 = @intCast((p.tagPrefix(pane) catch return).len + pane.tag_tail.items.len);
const c = @as(i32, mcol) - @as(i32, p.rects[d.id].x + config.GUTTER);
pane.tag_col = @intCast(std.math.clamp(c, 0, end));
pane.tag_sel = pane.tag_col != pane.tag_anchor;
},
.none => {},
}
}
fn pdfDragRelease(p: *Pardes, pane: *Pane, s: @FieldType(Drag, "select")) void {
if (comptime !pdf_enabled) return;
const pv = &(pane.pdf orelse return);
const b = @intFromEnum(s.button);
const sl = pane.sel[b];
pane.sel[b].state = .none; // native quads, not the projected text grid
// Every native drag keeps its geometry/text live while holding the
// baked highlight stable. Commit before chord/Exec/Look dispatch;
// those paths may clear or even delete the pane.
if (s.pdf.selection_changed) p.invalidatePdfRaster(pv);
if (s.chorded) {
clearPdfDrag(pv);
return;
}
if (s.button == config.select_button) {
const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1;
if (!dragged) {
p.clearPdfSelection(pane);
}
pane.cur_pinned = true;
pane.mode = .normal;
pane.msel.active = false;
pane.vsel.active = false;
pane.pending = 0;
pane.nsel = 0;
clearPdfDrag(pv);
return;
}
if (pv.drag_anchor == null or pv.selection_text.len == 0) {
clearPdfDrag(pv);
return;
}
const text = pv.selection_text;
// Exec can run Del and free `pane`; end every pv access before the
// builtin dispatch so no deferred cleanup writes through dead state.
clearPdfDrag(pv);
const arg = p.chord_arg;
p.chord_arg = null;
defer if (arg) |a| p.gpa.free(a);
const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd;
p.runBuiltin(cmd, s.id, "", p.withArg(text, arg));
}
fn dragRelease(p: *Pardes, button: Mouse.Button) void {
// a release of a button OTHER than the one driving a select drag is
// the middle+left chord's left release: the middle drag keeps going
if (p.drag == .select and button != p.drag.select.button) return;
defer p.drag = .none;
switch (p.drag) {
.border_v => |d| {
const c = d.left_col;
if (c + 1 < p.ncol) {
const combined: f32 = @floatFromInt(p.col_w[c] + p.col_w[c + 1]);
// the handle is the left pane's LAST column (inclusive), so
// the new width includes it — a no-drag click changes nothing
var nl: f32 = @floatFromInt((d.cur_x + 1) -| p.col_x[c]);
nl = std.math.clamp(nl, @as(f32, config.MINW), @max(@as(f32, config.MINW), combined - config.MINW));
const pair = p.col_weight[c] + p.col_weight[c + 1];
p.col_weight[c] = pair * (nl / combined);
p.col_weight[c + 1] = pair - p.col_weight[c];
}
// and the corner's other half. The two commits are independent
// — column weights are widths, pane vweights are heights, and
// neither reads the other — so the order here does not matter
// and a failed one cannot lose the other.
if (d.corner_idx) |k| p.applyRowSplit(c, k, d.cur_y);
},
.border_h => |d| p.applyRowSplit(d.col, d.top_idx, d.cur_y),
.move => |d| {
p.moveTerm(d.id, d.cur_x, d.cur_y);
// a file moved into the left column evicts a lone unused shell
if (p.panes[d.id]) |mt| if (mt.file != null) {
if (p.layoutFindTerm(d.id)) |f| if (f.col == 0)
p.evictLonePristineTty(0, d.id);
};
},
.select => |s| {
const pane = p.panes[s.id] orelse return;
if (comptime pdf_enabled) {
if (s.pdf.native) return p.pdfDragRelease(pane, s);
}
if (s.chorded) {
// a cut/paste chord consumed this drag; the release is inert
pane.sel[@intFromEnum(s.button)].state = .none;
return;
}
const b = @intFromEnum(s.button);
pane.sel[b].state = .done;
if (s.button == config.select_button) {
// keep a dragged selection highlighted; a plain click clears
// it. Either way pin the cursor; files also enter normal
// mode, terminals keep the mode they had (tty keeps the
// mouse usable, insert keeps typing where you clicked).
const sl = pane.sel[sel_slot];
const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1;
if (!dragged) pane.sel[sel_slot].state = .none;
const body_vis = sl.r1 - @as(i32, BOX_H);
if (body_vis >= 0 and pane.mode != .tty) {
// the row the user clicked, as the LAST FRAME drew it:
// which line it showed and the byte column it started
// at, so a click lands on the character under the
// pointer whether or not that row is a continuation
const w = pane.wrapAt(body_vis);
pane.cur_row = w.line;
pane.cur_col = if (pane.file != null) @max(0, sl.c1 - @as(i32, config.PREFIX_W)) + w.at else sl.c1;
pane.cur_pinned = true;
if (!pane.isTerminal()) pane.mode = .normal;
pane.msel.active = false;
pane.pending = 0;
// a chord/motion selection is residue: a fresh click
// dismisses it rather than dragging the anchored span
// to the click (explicit v/x keeps vim's click-extend)
if (!pane.vsel.explicit) pane.vsel.active = false;
pane.nsel = 0; // a click says WHERE the one cursor is
// Ctrl-click IS `gd`, asked now that the cursor has
// landed — the mouse spelling of the keyboard motion,
// through the identical request. A ctrl-DRAG still
// selects and still asks, about where it started,
// which is the same thing `gd` would answer.
if (s.ctrl) p.lspRequest(s.id, .definition, "");
}
} else {
// acme execute (middle) / look (right): a no-drag click
// expands to the word under it first; a captured chord
// argument rides along and is consumed here.
// WHERE THE CLICK LANDED, before any expansion — as a body
// position, the way the left button converts its drag end.
const clk = pane.sel[b];
const cvis = clk.r0 - @as(i32, BOX_H);
const cw = pane.wrapAt(cvis);
const crow = cw.line;
const ccol = if (pane.file != null)
@max(0, clk.c0 - @as(i32, config.PREFIX_W)) + cw.at
else
clk.c0;
// A click INSIDE a live selection takes the WHOLE selection
// and expands nothing: you already said what you meant, and
// the file-ish word heuristic can only cut it down — a path
// with a space in it, `git log -p`, half a URL. This is the
// rule the keyboard chords follow (an explicit modal
// selection wins over the word under the cursor), asked of
// where the click landed rather than where the cursor is,
// so a selection left lying in a pane never traps the
// buttons: click OUTSIDE it and the ordinary word expansion
// is back. A kept left sweep is screen-coordinate; the
// modal one (v/x, n/N) is in absolute rows, hence the two
// spellings of the same question.
const ls = pane.sel[sel_slot];
const held: ?[]const u8 = if (ls.state == .done and
spanHas(clk.r0, clk.c0, ls.r0, ls.c0, ls.r1, ls.c1))
(p.selectionText(pane, ls) catch null)
else if (pane.vsel.active and pane.vsel.explicit)
(if (spanHas(crow, ccol, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col))
p.currentSelText(pane)
else
null)
else if (pane.msel.active and crow >= @min(pane.msel.r0, pane.msel.r1) and
crow <= @max(pane.msel.r0, pane.msel.r1))
p.currentSelText(pane)
else
null;
if (held == null) p.expandSel(pane, &pane.sel[b]);
// A look that names no file SEARCHES from where you are, so
// the click has to say where that is and the search walks
// forward from there. Not PINNED — a shell's cursor still
// belongs to the shell, and the search reads this in the
// same event.
if (s.button == config.look_button and cvis >= 0 and pane.mode != .tty) {
pane.cur_row = crow;
pane.cur_col = ccol;
}
const txt = held orelse (p.selectionText(pane, pane.sel[b]) catch null);
const arg = p.chord_arg;
p.chord_arg = null;
defer if (arg) |a| p.gpa.free(a);
const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd;
if (txt) |tx| p.runBuiltin(cmd, s.id, "", p.withArg(tx, arg));
}
},
.tag => {}, // dragUpdate already left the tag cursor + selection set
.none => {},
}
}
/// Commit a horizontal border to the pane weights: in column `cc`, the pane
/// at index `k` and the one under it split their combined height at row
/// `cur_y`. Shared by the plain h-drag and the h half of a corner drag —
/// the same gesture landing on the same boundary must settle identically
/// whether or not a column edge came along for the ride.
fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void {
if (k + 1 >= p.col_n[cc]) return;
const a = p.panes[p.col_terms[cc][k]] orelse return;
const b = p.panes[p.col_terms[cc][k + 1]] orelse return;
const ra = p.rects[p.col_terms[cc][k]];
const rb = p.rects[p.col_terms[cc][k + 1]];
const combined: f32 = @floatFromInt(ra.h + rb.h);
var nt: f32 = @floatFromInt((cur_y + 1) -| ra.y);
nt = std.math.clamp(nt, @as(f32, BOX_H), @max(@as(f32, BOX_H), combined - BOX_H));
const pair = a.vweight + b.vweight;
a.vweight = pair * (nt / combined);
b.vweight = pair - a.vweight;
}
/// acme 1-2 (Cut) / 1-3 (Paste): middle or right tapped while the left
/// button holds a selection drag. The first tap converts the mouse
/// selection into the modal one (vsel anchored at the drag start, cursor
/// at its end; a plain click is a bare cursor). Cut yanks + deletes the
/// selection; Paste replaces it with the yank register, or splices the
/// register in literally at a bare cursor — so 1-2 then 1-3 in one hold
/// nets out to Snarf (copy: the text returns, the register keeps it).
/// In a tty-mode shell 1-3 instead pastes into the pty (forwarded click
/// + bracketed paste) and 1-2 is inert.
fn chordCutPaste(p: *Pardes, cut: bool) void {
const s = &p.drag.select;
const pane = p.panes[s.id] orelse return;
if (comptime pdf_enabled) if (pane.pdf) |pv| {
if (!s.chorded) {
s.chorded = true;
pane.sel[sel_slot].state = .none;
}
// A PDF is immutable: its Cut-side chord is Snarf (copy), while
// Paste has no document mutation to perform.
if (cut and pv.selection_text.len > 0) p.setYank(pv.selection_text);
return;
};
if (pane.mode == .tty) {
// tty: nothing can be cut — 1-2 stays inert; the pty owns the
// screen. 1-3 pastes like a terminal emulator: the click is
// forwarded first (only when the app listens for mouse) so
// mouse-aware programs put their cursor under it, then the
// register is typed — bracketed when the app set mode 2004
// (readline/vim/helix strip the markers), else with \n turned
// to \r like any unbracketed paste.
if (!s.chorded) {
s.chorded = true;
pane.sel[sel_slot].state = .none; // drop the sweep highlight
}
if (cut) return;
const y = p.yank orelse return;
if (y.len == 0) return;
const m = &pane.vt.modes;
if (m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any)) {
// dragUpdate keeps sel[sel_slot] tracking the held select button, so
// the click lands where the mouse is at this tap; 1-based,
// body-relative (the tag row is ours, not the app's)
const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999));
const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, BOX_H) + 1, 1, 9999));
var mb: [32]u8 = undefined;
if (m.get(.mouse_format_sgr)) {
p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return);
} else {
// ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them
const cb: u8 = @intCast(32 + @min(col, 222));
const rb: u8 = @intCast(32 + @min(row, 222));
p.emitWrite(s.id, &[_]u8{ 0x1b, '[', 'M', 32, cb, rb, 0x1b, '[', 'M', 35, cb, rb });
}
}
if (m.get(.bracketed_paste)) {
p.emitWrite(s.id, "\x1b[200~");
p.emitWrite(s.id, y);
p.emitWrite(s.id, "\x1b[201~");
} else {
const cp = p.scratch.allocator().dupe(u8, y) catch return;
for (cp) |*c| {
if (c.* == '\n') c.* = '\r';
}
p.emitWrite(s.id, cp);
}
return;
}
if (!s.chorded) {
s.chorded = true;
const sl = pane.sel[sel_slot];
pane.sel[sel_slot].state = .none;
const pfx: i32 = if (pane.file != null) config.PREFIX_W else 0;
// both ends of the sweep through the same last-frame map, so a
// chord over wrapped rows cuts the text that was under it
const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, BOX_H)));
const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H)));
const row0 = w0.line;
const row1 = w1.line;
const col0 = @max(0, sl.c0 - pfx) + w0.at;
const col1 = @max(0, sl.c1 - pfx) + w1.at;
pane.cur_row = row1;
pane.cur_col = col1;
pane.cur_pinned = true;
pane.msel.active = false;
pane.pending = 0;
if (!pane.isTerminal()) pane.mode = .normal;
pane.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false };
pane.nsel = 0;
}
if (cut) {
if (pane.vsel.active) p.normalDelete(pane, true);
} else if (pane.vsel.active) {
p.normalReplaceYank(pane);
} else if (pane.file) |*f| {
// bare cursor: splice the register in literally (no linewise
// magic) so a paste right after a cut restores the text exactly
const y = p.yank orelse return;
if (y.len == 0) return;
const at = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) };
p.pushUndo(pane);
const new = modal.insertAt(p.gpa, f.content, at, y) catch return;
file_pane.setContent(p, f, new);
pane.vsel = .{ .active = y.len > 1, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false };
const end = modal.advanceBy(at, y);
if (end.col > 0) {
pane.cur_row = @intCast(end.row);
pane.cur_col = @intCast(end.col - 1);
} else {
// the register ended in '\n': the cursor lands ON that newline
pane.cur_row = @intCast(end.row -| 1);
pane.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len);
}
pane.cur_pinned = true;
pane.sticky_col = -1;
pane.ensureCursorVisible();
} else p.normalPaste(pane, true); // terminal: splice run text at the cursor
}
/// tty mode: encode the key the way a terminal would and send it to the pty.
fn forwardKey(p: *Pardes, id: usize, key: Key) void {
var cbuf: [1]u8 = undefined;
const bytes: ?[]const u8 = blk: {
if (key.ctrl) {
if (key.cp >= 'a' and key.cp <= 'z') {
cbuf[0] = @intCast(key.cp - 0x60);
break :blk cbuf[0..1];
}
if (key.cp == '@') {
cbuf[0] = 0;
break :blk cbuf[0..1];
}
if (key.cp >= '[' and key.cp <= '_') {
cbuf[0] = @intCast(key.cp - 0x40);
break :blk cbuf[0..1];
}
if (key.cp >= 'A' and key.cp <= 'Z') {
cbuf[0] = @intCast(key.cp - 0x40);
break :blk cbuf[0..1];
}
}
if (key.text.len > 0) break :blk key.text;
break :blk switch (key.cp) {
Key.enter => "\r",
Key.backspace => "\x7f",
Key.tab => "\t",
Key.escape => "\x1b",
Key.up => "\x1b[A",
Key.down => "\x1b[B",
Key.right => "\x1b[C",
Key.left => "\x1b[D",
Key.delete => "\x1b[3~",
else => null,
};
};
if (bytes) |b| p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(b) } });
}
// ---- layout surgery ----
pub fn layoutFindTerm(p: *Pardes, id: usize) ?struct { col: usize, idx: usize } {
for (0..p.ncol) |c| {
for (0..p.col_n[c]) |k| {
if (p.col_terms[c][k] == id) return .{ .col = c, .idx = k };
}
}
return null;
}
fn layoutInsert(p: *Pardes, c: usize, idx: usize, id: usize) void {
var k = p.col_n[c];
while (k > idx) : (k -= 1) p.col_terms[c][k] = p.col_terms[c][k - 1];
p.col_terms[c][idx] = id;
p.col_n[c] += 1;
}
/// Remove from the layout. An emptied column hands its width to a neighbor
/// (else every surviving column reflows sideways) before shifting down.
pub fn layoutRemove(p: *Pardes, id: usize) void {
const f = p.layoutFindTerm(id) orelse return;
const c = f.col;
var k = f.idx;
while (k + 1 < p.col_n[c]) : (k += 1) p.col_terms[c][k] = p.col_terms[c][k + 1];
p.col_n[c] -= 1;
if (p.col_n[c] == 0) {
if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] += p.col_weight[c];
var j = c;
while (j + 1 < p.ncol) : (j += 1) {
p.col_terms[j] = p.col_terms[j + 1];
p.col_n[j] = p.col_n[j + 1];
p.col_weight[j] = p.col_weight[j + 1];
}
p.ncol -= 1;
}
}
pub fn layoutAppendColumn(p: *Pardes, id: usize) void {
p.layoutInsertColumn(p.ncol, id);
}
/// a fresh single-pane column at index `at` (the columns from there on
/// shift right); an equal weight, so the others narrow proportionally
fn layoutInsertColumn(p: *Pardes, at: usize, id: usize) void {
if (p.ncol >= MAX_COLS) return;
const c = @min(at, p.ncol);
var j = p.ncol;
while (j > c) : (j -= 1) {
p.col_terms[j] = p.col_terms[j - 1];
p.col_n[j] = p.col_n[j - 1];
p.col_weight[j] = p.col_weight[j - 1];
}
p.col_weight[c] = 1;
p.col_terms[c][0] = id;
p.col_n[c] = 1;
p.ncol += 1;
}
/// Snap every pane in column `c` to its on-screen row count so later
/// weight edits move ONLY the panes they name: computeGeom rounds
/// round(avail*w/vsum) per pane, and with fractional weights a split or
/// absorb elsewhere in the column can jiggle a bystander by a row.
fn snapColWeights(p: *Pardes, c: usize) void {
for (0..p.col_n[c]) |k| {
const pid = p.col_terms[c][k];
if (p.panes[pid]) |pp| pp.vweight = @floatFromInt(@max(1, p.rects[pid].h));
}
}
/// Hand a dying pane's rows to ONE sibling (the pane above, or below for
/// the topmost) so the rest of the column keeps its sizes bit-identical —
/// the deletion mirror of splitBelow. Call while `id` is still in the
/// layout, with rects current.
pub fn absorbVWeight(p: *Pardes, id: usize) void {
const f = p.layoutFindTerm(id) orelse return;
if (p.col_n[f.col] <= 1) return;
p.snapColWeights(f.col);
// the pane above, but never a result list: walking past a stack of them
// lands on the pane that spawned it, so those keep their heights and
// only the spawner grows. The topmost pane has only what is below it.
var sib = if (f.idx > 0) p.col_terms[f.col][f.idx - 1] else p.col_terms[f.col][f.idx + 1];
var k = f.idx;
while (k > 0) : (k -= 1) {
sib = p.col_terms[f.col][k - 1];
if (p.panes[sib]) |pp| if (if (pp.file) |ff| output_pane.fileTraits(ff.output).doc else true) break;
}
if (p.panes[sib]) |s| s.vweight += @as(f32, @floatFromInt(@max(1, p.rects[id].h)));
}
/// The parent a new pane splits from must be tall enough that splitBelow
/// leaves the NEW pane at least 2 body rows (the parent keeps tag+1 row,
/// the new pane needs tag+2). A too-short choice is swapped for a
/// qualifying pane (same column first, keeping the split local), else the
/// tallest pane anywhere.
fn splitParent(p: *Pardes, want: usize) usize {
const need = 2 * BOX_H + 3;
if (p.rects[want].h >= need) return want;
if (p.layoutFindTerm(want)) |f| for (0..p.col_n[f.col]) |k| {
if (p.rects[p.col_terms[f.col][k]].h >= need) return p.col_terms[f.col][k];
};
var tallest = want;
for (0..p.ncol) |c| for (0..p.col_n[c]) |k| {
const pid = p.col_terms[c][k];
if (p.rects[pid].h >= need) return pid;
if (p.rects[pid].h > p.rects[tallest].h) tallest = pid;
};
return tallest;
}
/// Open a window BELOW `src` (acme-style) without rebalancing the column:
/// shrink ONLY src to its content height (cursor row kept visible) and hand
/// the freed rows to `nw` — together they fill src's old slot and the other
/// panes keep their sizes bit-identical (weights snap to row counts).
fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void {
const src = p.panes[src_id] orelse return;
const src_h = p.rects[src_id].h;
const body: u16 = if (src_h > BOX_H) src_h - BOX_H else 1;
const cur: u16 = if (!src.isTerminal()) body / 2 else @as(u16, @intCast(src.vt.screens.active.cursor.y)) + 1;
// cap keep so a content-full source still leaves the new pane a tag +
// a few body rows (an Alt-n from a full shell was born 0 rows tall)
const keep = std.math.clamp(cur, 1, @max(1, body -| (BOX_H + 3)));
if (p.layoutFindTerm(src_id)) |f| for (0..p.col_n[f.col]) |k| {
const pid = p.col_terms[f.col][k];
if (p.panes[pid]) |pp| if (pp != nw) {
pp.vweight = @floatFromInt(@max(1, p.rects[pid].h));
};
};
src.vweight = @floatFromInt(BOX_H + keep);
nw.vweight = @floatFromInt(@max(1, src_h -| (BOX_H + keep)));
// a non-doc buffer is worth exactly its own text: a three-hit +Search
// is four rows, not half the source. Nothing else can want the rows,
// so they go straight back to the pane they were taken from.
if (nw.file) |f| if (!output_pane.fileTraits(f.output).doc) {
// trimmed: every row ends in a newline, and the empty line after
// the last one is not a result
const want: f32 = @floatFromInt(BOX_H + file_pane.lineCount(std.mem.trimEnd(u8, f.content, "\n")));
if (want < nw.vweight) {
src.vweight += nw.vweight - want;
nw.vweight = want;
}
};
}
/// a shell nobody has touched: no typing, cursor on the first prompt line,
/// no scrollback — a throwaway placeholder a file may replace
fn isPristineTty(pane: *Pane) bool {
if (!pane.isTerminal()) return false;
if (pane.ovl != null) return false;
if (pane.vt.screens.active.cursor.y != 0) return false;
return pane.vt.screens.active.pages.scrollbar().total <= pane.rows;
}
/// when a doc lands in `col`, a lone pristine shell there is clutter — drop
/// it; absorbVWeight hands its space to the doc
fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void {
var n_tty: usize = 0;
var tty_id: usize = 0;
for (0..p.col_n[col]) |k| {
const cid = p.col_terms[col][k];
if (p.panes[cid]) |ct| if (ct.isTerminal()) {
n_tty += 1;
tty_id = cid;
};
}
if (n_tty != 1) return;
const tt = p.panes[tty_id] orelse return;
if (!isPristineTty(tt)) return;
p.computeGeom(); // a just-stacked doc has no rect yet; absorb snaps to rows
p.absorbVWeight(tty_id);
p.layoutRemove(tty_id);
p.deinitPane(tt);
p.panes[tty_id] = null;
if (p.active == tty_id) p.active = keep_id;
}
/// a terminal already in `dir`, else a fresh shell there at the bottom of
/// the rightmost column. Backs middle-click send from a file pane. Does NOT
/// focus (execute keeps you where you were; look focuses).
fn ttyForDir(p: *Pardes, dir: []const u8) ?usize {
for (p.panes, 0..) |slot, i| if (slot) |tt| {
if (!tt.isTerminal()) continue;
if (std.mem.eql(u8, tt.cwdSlice(), dir)) return i;
};
const free = p.freeSlot() orelse return null;
const nt = p.newShell(free, dir) catch return null;
nt.greet = false;
const rc = if (p.ncol > 0) p.ncol - 1 else 0;
if (p.col_n[rc] > 0) {
const src = p.splitParent(p.col_terms[rc][p.col_n[rc] - 1]);
const f = p.layoutFindTerm(src).?;
p.splitBelow(src, nt);
p.layoutInsert(f.col, f.idx + 1, free);
} else p.layoutInsert(rc, p.col_n[rc], free);
return free;
}
// ---- doc panes ----
pub fn openTutorView(p: *Pardes, id: usize) !*Pane {
const content = try p.gpa.dupe(u8, tutor_text);
errdefer p.gpa.free(content);
const path = try p.gpa.dupe(u8, "/Tutor");
errdefer p.gpa.free(path);
const pane = try p.newDocPane(id);
pane.file = .{ .path = path, .content = content };
pane.cur_pinned = true;
return pane;
}
/// TEST-ONLY, called by test/hxdiff.zig (the helix differential harness):
/// swap the tty_only boot pane for a file pane holding `content` verbatim
/// — file_pane.open minus the disk read (cases carry their buffer inline).
/// Unreachable from any shell; keep it dumb.
pub fn hxOpenFileContent(p: *Pardes, content: []const u8) !*Pane {
const copy = try p.gpa.dupe(u8, content);
errdefer p.gpa.free(copy);
const path = try p.gpa.dupe(u8, "/hxcase.txt");
errdefer p.gpa.free(path);
p.deinitPane(p.panes[0].?);
p.panes[0] = null;
const pane = try p.newDocPane(0);
pane.file = .{ .path = path, .content = copy };
pane.cur_pinned = true;
p.active = 0;
p.sync();
return pane;
}
fn openImageView(p: *Pardes, id: usize, path: []const u8) !*Pane {
const path_copy = try p.gpa.dupe(u8, path);
errdefer p.gpa.free(path_copy);
const pane = try p.newDocPane(id);
// Native pixels are the preference, not a capability observed at open
// time. drawImage dynamically falls back while a shell has no native
// image support; this matters because kitty detection finishes after
// argv images and restored panes have already been constructed.
pane.image = .{ .path = path_copy };
return pane;
}
fn openPdfView(p: *Pardes, id: usize, path: []const u8, page_one_based: usize) !*Pane {
if (comptime !pdf_enabled) return error.PdfDisabled;
var document = try pdf_impl.Document.open(path);
errdefer document.deinit();
const page_sizes = try p.gpa.alloc(pdf_impl.PageSize, document.pages);
errdefer p.gpa.free(page_sizes);
for (page_sizes, 0..) |*size, page_number|
size.* = try document.pageSize(page_number);
const page_starts = try p.gpa.alloc(u64, document.pages);
errdefer p.gpa.free(page_starts);
const page_heights = try p.gpa.alloc(u32, document.pages);
errdefer p.gpa.free(page_heights);
const path_copy = try p.gpa.dupe(u8, path);
errdefer p.gpa.free(path_copy);
const pane = try p.newDocPane(id);
const page = if (page_one_based > 0)
@min(page_one_based - 1, document.pages - 1)
else
0;
pane.pdf = .{
.path = path_copy,
.document = document,
.page = page,
.page_count = document.pages,
.page_sizes = page_sizes,
.page_starts = page_starts,
.page_heights = page_heights,
};
pane.cur_pinned = true;
return pane;
}
/// Mark same-page pixels stale while retaining the one visible RGBA and
/// its dimensions. drawPdf swaps in a replacement only after MuPDF and the
/// allocation both succeed, so a failed highlight rerender never blanks a
/// page which was already visible.
fn invalidatePdfRaster(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
_ = p;
pv.render_tried = false;
for (pv.rasters.items) |*raster| if (raster.valid and raster.page == pv.page) {
raster.tried = false;
break;
};
}
/// Tint and theme changes affect every page currently carried to a native
/// backend, including both sides of a continuous-strip page boundary.
/// Retain their old buffers until each replacement succeeds.
fn invalidateAllPdfRasters(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
_ = p;
pv.render_tried = false;
for (pv.rasters.items) |*raster| {
if (raster.valid) raster.tried = false;
}
}
fn releasePdfRaster(p: *Pardes, raster: *PdfRaster) void {
if (comptime !pdf_enabled) return;
if (raster.rgba.len > 0) p.gpa.free(raster.rgba);
raster.* = .{};
}
fn dropPdfRaster(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
for (pv.rasters.items) |*raster| p.releasePdfRaster(raster);
pv.rasters.clearRetainingCapacity();
pv.rgba = &.{};
pv.iw = 0;
pv.ih = 0;
pv.render_tried = false;
pv.render_request_valid = false;
}
fn dropPdfSearchResults(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (pv.search_results) |*results| results.deinit(p.gpa);
pv.search_results = null;
}
fn dropPdfSelection(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (pv.selection) |*selection| selection.deinit(p.gpa);
pv.selection = null;
if (pv.selection_text.len > 0) p.gpa.free(pv.selection_text);
pv.selection_text = &.{};
pv.selection_anchor = null;
pv.selection_head = null;
}
fn clearPdfDrag(pv: *PdfView) void {
if (comptime !pdf_enabled) return;
pv.drag_anchor = null;
pv.drag_head = null;
}
fn clearPdfSelection(p: *Pardes, pane: *Pane) void {
if (comptime !pdf_enabled) return;
const pv = &(pane.pdf orelse return);
const changed = pv.selection != null or pv.selection_text.len > 0;
p.dropPdfSelection(pv);
if (changed) p.invalidatePdfRaster(pv);
}
/// Drop semantic state tied to the active page. Plain cached pixels remain
/// reusable if that page is still adjacent in the continuous viewport.
fn invalidatePdfPage(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
p.dropPdfSearchResults(pv);
p.dropPdfSelection(pv);
clearPdfDrag(pv);
if (pv.text.len > 0) p.gpa.free(pv.text);
pv.text = &.{};
pv.text_tried = false;
pv.text_scroll = 0;
pv.highlights_dirty = pv.search_query.len > 0;
pv.search_reveal_pending = pv.search_query.len > 0;
pv.search_hit = 0;
}
/// Replace the full PDF query and discard only query-derived page state.
/// Resolution is lazy in drawPdf; fit and pan remain placement-only state.
fn setPdfSearchQuery(p: *Pardes, pv: *PdfView, query: []const u8) void {
if (comptime !pdf_enabled) return;
if (std.mem.eql(u8, pv.search_query, query)) return;
const owned = p.gpa.dupe(u8, query) catch return;
if (pv.search_query.len > 0) p.gpa.free(pv.search_query);
pv.search_query = owned;
pv.search_hit = 0;
p.dropPdfSearchResults(pv);
pv.highlights_dirty = query.len > 0;
pv.search_reveal_pending = query.len > 0;
p.invalidatePdfRaster(pv);
}
fn resolvePdfSearch(p: *Pardes, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (!pv.highlights_dirty) return;
pv.highlights_dirty = false;
p.dropPdfSearchResults(pv);
if (pv.search_query.len == 0) return;
const results = pv.document.search(p.gpa, pv.page, pv.search_query) catch return;
pv.search_hit = if (results.hit_count == 0)
0
else
@min(pv.search_hit, results.hit_count - 1);
pv.search_results = results;
}
fn normalizedPdfPixel(value: f32, dimension: usize) u32 {
const scaled = std.math.clamp(value, 0, 1) *
@as(f32, @floatFromInt(dimension));
return @intCast(@min(dimension - 1, @as(usize, @intFromFloat(scaled))));
}
fn rearmPdfRevealForViewport(p: *Pardes, pane: *Pane, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (pv.search_query.len == 0) return;
const viewport = p.pdfViewport(pane) orelse return;
if (!pv.reveal_viewport_valid or
pv.reveal_viewport_w != viewport.pixel_w or
pv.reveal_viewport_h != viewport.pixel_h or
pv.reveal_fit != pv.fit)
pv.search_reveal_pending = true;
}
fn revealPdfSearch(p: *Pardes, pane: *Pane, pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (!pv.search_reveal_pending) return;
const viewport = p.pdfViewport(pane) orelse return;
pv.reveal_viewport_w = viewport.pixel_w;
pv.reveal_viewport_h = viewport.pixel_h;
pv.reveal_fit = pv.fit;
pv.reveal_viewport_valid = true;
const results = pv.search_results orelse {
pv.search_reveal_pending = false;
return;
};
if (results.hit_count == 0 or results.quads.len == 0) {
pv.search_reveal_pending = false;
return;
}
pv.search_hit = @min(pv.search_hit, results.hit_count - 1);
const q = for (results.quads) |item| {
if (item.hit == pv.search_hit) break item.quad;
} else {
pv.search_reveal_pending = false;
return;
};
pv.search_reveal_pending = false;
const center_x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4;
const center_y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4;
if (pv.fit == .width) {
const laid_out = p.ensurePdfLayout(pane, pv) orelse return;
const page_y = @as(f64, @floatFromInt(pv.page_starts[pv.page])) +
@as(f64, center_y) * @as(f64, @floatFromInt(pv.page_heights[pv.page]));
const wanted = page_y - @as(f64, @floatFromInt(laid_out.pixel_h)) / 2;
const max_scroll = @as(f64, @floatFromInt(pv.document_height -| laid_out.pixel_h));
pv.document_scroll_y = std.math.clamp(wanted, 0, max_scroll);
return;
}
const geometry = p.pdfGeometry(pane) orelse return;
const full: u32 = @intCast(pv.iw);
const at = normalizedPdfPixel(center_x, pv.iw);
if (at >= geometry.src.x and at < geometry.src.x + geometry.src.w) return;
const overflow = full -| geometry.src.w;
if (overflow == 0) return;
const wanted = @min(overflow, at -| geometry.src.w / 2);
pv.pan_x = @intCast(
(@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow,
);
}
fn activatePdfPage(p: *Pardes, pane: *Pane, page: usize, reveal: bool) void {
if (comptime !pdf_enabled) return;
const pv = &(pane.pdf orelse return);
// Every ordinary page/navigation action supersedes an outline reveal.
// The outline path calls this first and installs its destination after.
pv.outline_reveal_pending = null;
const next = @min(page, pv.page_count -| 1);
if (next != pv.page) {
p.invalidatePdfPage(pv);
pv.page = next;
pane.cur_row = 0;
pane.cur_col = 0;
pane.vsel.active = false;
pane.msel.active = false;
pane.nsel = 0;
}
// Input events can be queued behind a scroll in the same shell batch.
// If the newly active adjacent page is already resident, publish its
// dimensions immediately so the following click/pan cannot combine
// its geometry with the prior page's aliases.
if (pdfRasterForPage(pv, next)) |raster| syncPdfRasterAliases(pv, raster);
if (reveal) {
pv.scroll_to_page_pending = true;
if (pv.layout_valid) {
pv.document_scroll_y = @floatFromInt(pv.page_starts[next]);
pv.scroll_to_page_pending = false;
}
} else {
// Scrolling into another page must not turn a pending search into
// a snap back to its center; manual document motion stays manual.
pv.search_reveal_pending = false;
}
}
/// Reveal one page in the continuous strip without reparsing the document.
fn setPdfPage(p: *Pardes, pane: *Pane, page: usize) void {
p.activatePdfPage(pane, page, true);
}
/// Builtin entry point. Public only because builtins.zig is the command
/// registry; the PdfView representation remains private to this module.
pub fn togglePdfFit(p: *Pardes, pane: *Pane) void {
if (comptime !pdf_enabled) return;
_ = p;
const pv = &(pane.pdf orelse return);
pv.fit = if (pv.fit == .width) .height else .width;
pv.pan_x = 0;
pv.pan_y = 0;
pv.layout_valid = false;
pv.scroll_to_page_pending = true;
pv.search_reveal_pending = pv.search_query.len > 0;
}
/// Builtin entry point for the exact disabled -> filtered -> full ring.
/// State belongs to one PDF pane; other document and terminal panes are
/// deliberately inert.
pub fn togglePdfTint(p: *Pardes, pane: *Pane) void {
if (comptime !pdf_enabled) return;
const pv = &(pane.pdf orelse return);
pv.tint = pv.tint.next();
p.invalidateAllPdfRasters(pv);
}
fn ensurePdfOutline(p: *Pardes, pv: *PdfView) ?*const pdf_impl.Outline {
if (comptime !pdf_enabled) return null;
if (!pv.outline_tried) {
pv.outline_tried = true;
pv.outline = pv.document.outline(p.gpa) catch null;
}
return if (pv.outline) |*outline| outline else null;
}
fn isPdfSectionsOutput(pane: *const Pane) bool {
if (comptime !pdf_enabled) return false;
const file = pane.file orelse return false;
const output = file.output orelse return false;
return switch (output.from) {
.cmd => |builtin| builtin == .PdfSections,
else => false,
};
}
/// Re-arm a remembered, unedited +PdfSections pane without consulting
/// MuPDF or rebuilding bytes which cannot have changed while its owning
/// document remains open. Serial + generated revision are the two cache
/// guards: a closed/reused slot or user edit falls through to a fresh
/// materialisation below.
fn rearmCleanPdfSections(p: *Pardes, id: usize, pane: *Pane, pv: *PdfView) bool {
const remembered = pv.sections_output orelse return false;
if (remembered.pane >= p.panes.len) return false;
const result = p.panes[remembered.pane] orelse return false;
if (result.serial != remembered.serial or !isPdfSectionsOutput(result)) return false;
const file = &result.file.?;
if (file.revision != remembered.revision) return false;
file.scroll = 0;
result.cur_row = 0;
result.cur_col = 0;
result.msel.active = false;
result.vsel.active = false;
result.nsel = 0;
pane.search_pane = remembered.pane;
pane.search_row = null;
p.active = id;
return true;
}
/// Lazily materialise this pane's cached MuPDF outline as a location list.
/// A clean live output is refreshed in place; an edited, closed, or reused
/// slot is never overwritten. Focus and n/N ownership stay on the PDF.
pub fn openPdfSections(p: *Pardes, id: usize) void {
if (comptime pdf_enabled) {
const pane = p.panes[id] orelse return;
const pv = &(pane.pdf orelse return);
if (p.rearmCleanPdfSections(id, pane, pv)) return;
const entries: []const pdf_impl.OutlineEntry = if (p.ensurePdfOutline(pv)) |outline|
outline.entries
else
&.{};
const content = PdfSectionRows.render(p.gpa, pv.path, entries) catch return;
const free = p.freeSlot() orelse {
p.gpa.free(content);
return;
};
const dir = std.fs.path.dirname(pv.path) orelse "/";
const result = output_pane.open(
p,
free,
dir,
.{ .cmd = .PdfSections },
"",
content,
) catch {
p.gpa.free(content);
return;
};
pv.sections_output = .{
.pane = free,
.serial = result.serial,
.revision = result.file.?.revision,
};
p.placeDoc(id, free, result);
p.computeGeom();
p.active = id;
pane.search_pane = free;
pane.search_row = null;
}
}
fn stepPdfPage(p: *Pardes, pane: *Pane, delta: i64) void {
if (comptime !pdf_enabled) return;
const pv = pane.pdf orelse return;
const current: i64 = @intCast(pv.page);
const last: i64 = @intCast(pv.page_count -| 1);
p.setPdfPage(pane, @intCast(std.math.clamp(current + delta, 0, last)));
}
const PdfViewport = struct {
pixel_w: u32,
pixel_h: u32,
};
const PdfVisiblePages = struct { first: usize = 0, len: usize = 0 };
const PdfPanAxis = enum { horizontal, vertical };
const PdfPanResult = enum { moved, edge, unavailable };
/// The image shells receive a cell rectangle while NativeGeometry works
/// in pixels. Keep this conversion in core state so navigation and drawing
/// agree even when the font metrics change at runtime.
fn pdfViewport(p: *const Pardes, pane: *const Pane) ?PdfViewport {
const r = for (p.panes, 0..) |slot, i| {
if (slot == pane) break p.rects[i];
} else return null;
const cols = r.w -| config.GUTTER;
const rows = r.h -| BOX_H;
if (cols == 0 or rows == 0) return null;
return .{
.pixel_w = @as(u32, cols) * @as(u32, p.cell_pixels.w),
.pixel_h = @as(u32, rows) * @as(u32, p.cell_pixels.h),
};
}
fn pdfPageHeight(size: pdf_impl.PageSize, viewport: PdfViewport, fit: PdfFitMode) u32 {
if (comptime !pdf_enabled) return 0;
if (fit == .height) return viewport.pixel_h;
const scaled = @as(f64, @floatFromInt(viewport.pixel_w)) *
@as(f64, size.height) / @as(f64, size.width);
return @max(1, @as(u32, @intFromFloat(@min(
@as(f64, @floatFromInt(std.math.maxInt(u32))),
@round(scaled),
))));
}
fn consumePdfOutlineReveal(pv: *PdfView, viewport: PdfViewport) void {
if (comptime !pdf_enabled) return;
const destination = pv.outline_reveal_pending orelse return;
pv.outline_reveal_pending = null;
const page = @min(destination.page, pv.page_count -| 1);
const size = pv.page_sizes[page];
const raw_y = destination.y orelse 0;
const y = if (std.math.isFinite(raw_y))
std.math.clamp(raw_y, 0, size.height)
else
0;
const y_fraction = @as(f64, y) / @as(f64, size.height);
pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[page])) +
y_fraction * @as(f64, @floatFromInt(pv.page_heights[page]));
// Fit-width has no horizontal overflow. In fit-height, derive the
// display-space crop from page geometry so x works before this page
// has ever been rasterised and does not force a render merely to pan.
if (destination.x) |raw_x| if (pv.fit == .height and std.math.isFinite(raw_x)) {
const display_width = @as(f64, @floatFromInt(viewport.pixel_h)) *
@as(f64, size.width) / @as(f64, size.height);
const viewport_width: f64 = @floatFromInt(viewport.pixel_w);
if (display_width > viewport_width) {
const x = std.math.clamp(raw_x, 0, size.width);
const target = @as(f64, x) / @as(f64, size.width) * display_width;
const overflow = display_width - viewport_width;
const wanted = std.math.clamp(target - viewport_width / 2, 0, overflow);
pv.pan_x = @intFromFloat(@round(
wanted / overflow * @as(f64, std.math.maxInt(u16)),
));
}
};
// The outline, not an older search hit, owns this explicit reveal.
// Record the current viewport so drawPdf's resize rearm agrees.
pv.search_reveal_pending = false;
pv.reveal_viewport_w = viewport.pixel_w;
pv.reveal_viewport_h = viewport.pixel_h;
pv.reveal_fit = pv.fit;
pv.reveal_viewport_valid = true;
}
/// Rebuild only O(page-count) point-size layout metadata. No page pixels
/// are touched, and ordinary scrolling never enters this path.
fn ensurePdfLayout(p: *Pardes, pane: *Pane, pv: *PdfView) ?PdfViewport {
if (comptime !pdf_enabled) return null;
const viewport = p.pdfViewport(pane) orelse return null;
// Pane-local geometry changes (divider drags, splits, closes) do not
// pass through Event.resize. Capture against the still-valid OLD
// layout here, immediately before replacing its page heights. A shell
// resize has already invalidated the layout after capturing, while an
// explicit page reveal owns scroll_to_page_pending; neither may be
// captured a second time or overridden by this implicit anchor.
if (pv.layout_valid and !pv.scroll_to_page_pending and
!pv.layout_anchor_pending and
(pv.layout_viewport_w != viewport.pixel_w or
pv.layout_viewport_h != viewport.pixel_h))
{
capturePdfLayoutAnchor(pv);
}
if (!pv.layout_valid or pv.layout_viewport_w != viewport.pixel_w or
pv.layout_viewport_h != viewport.pixel_h or pv.layout_fit != pv.fit)
{
var at: u64 = 0;
for (pv.page_sizes, 0..) |size, page| {
pv.page_starts[page] = at;
const height = pdfPageHeight(size, viewport, pv.fit);
pv.page_heights[page] = height;
at = std.math.add(u64, at, height) catch std.math.maxInt(u64);
if (page + 1 < pv.page_count)
at = std.math.add(u64, at, PDF_PAGE_GAP_PX) catch std.math.maxInt(u64);
}
pv.document_height = at;
pv.layout_viewport_w = viewport.pixel_w;
pv.layout_viewport_h = viewport.pixel_h;
pv.layout_fit = pv.fit;
pv.layout_valid = true;
if (pv.scroll_to_page_pending) {
pv.document_scroll_y = @floatFromInt(pv.page_starts[pv.page]);
pv.scroll_to_page_pending = false;
pv.layout_anchor_pending = false;
} else if (pv.layout_anchor_pending) {
const anchor_page = @min(pv.layout_anchor_page, pv.page_count -| 1);
pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[anchor_page])) +
pv.layout_anchor_fraction * @as(f64, @floatFromInt(pv.page_heights[anchor_page]));
pv.layout_anchor_pending = false;
}
}
consumePdfOutlineReveal(pv, viewport);
const max_scroll = @as(f64, @floatFromInt(pv.document_height -| viewport.pixel_h));
pv.document_scroll_y = std.math.clamp(pv.document_scroll_y, 0, max_scroll);
return viewport;
}
fn capturePdfLayoutAnchor(pv: *PdfView) void {
if (comptime !pdf_enabled) return;
if (!pv.layout_valid or pv.page_count == 0 or pv.document_height == 0) return;
const page = pdfPageAtOffset(pv, pv.document_scroll_y);
const start: f64 = @floatFromInt(pv.page_starts[page]);
const height: f64 = @floatFromInt(@max(@as(u32, 1), pv.page_heights[page]));
pv.layout_anchor_page = page;
pv.layout_anchor_fraction = std.math.clamp((pv.document_scroll_y - start) / height, 0, 1);
pv.layout_anchor_pending = true;
}
fn pdfPageAtOffset(pv: *const PdfView, offset: f64) usize {
if (comptime !pdf_enabled) return 0;
const y: u64 = @intFromFloat(std.math.clamp(
@floor(offset),
0,
@as(f64, @floatFromInt(pv.document_height -| 1)),
));
var lo: usize = 0;
var hi: usize = pv.page_count;
while (lo + 1 < hi) {
const mid = lo + (hi - lo) / 2;
if (pv.page_starts[mid] <= y) lo = mid else hi = mid;
}
const end = pv.page_starts[lo] + pv.page_heights[lo];
return if (y >= end and lo + 1 < pv.page_count) lo + 1 else lo;
}
fn pdfPageVisible(pv: *const PdfView, page: usize, viewport: PdfViewport) bool {
if (comptime !pdf_enabled) return false;
const top = @as(f64, @floatFromInt(pv.page_starts[page])) - pv.document_scroll_y;
const bottom = top + @as(f64, @floatFromInt(pv.page_heights[page]));
return bottom > 0 and top < @as(f64, @floatFromInt(viewport.pixel_h));
}
fn pdfVisiblePages(pv: *const PdfView, viewport: PdfViewport) PdfVisiblePages {
var out: PdfVisiblePages = .{};
var page = pdfPageAtOffset(pv, pv.document_scroll_y);
if (page > 0 and pdfPageVisible(pv, page - 1, viewport)) page -= 1;
out.first = page;
while (page < pv.page_count) : (page += 1) {
const top = @as(f64, @floatFromInt(pv.page_starts[page])) - pv.document_scroll_y;
if (top >= @as(f64, @floatFromInt(viewport.pixel_h))) break;
if (!pdfPageVisible(pv, page, viewport)) continue;
out.len += 1;
}
return out;
}
fn pdfRenderRequest(p: *const Pardes, pane: *const Pane) ?pdf_impl.RenderRequest {
if (comptime !pdf_enabled) return null;
const viewport = p.pdfViewport(pane) orelse return null;
return .{
.dpi = pdf_raster_policy.dpi,
.minimum_width = if (pdf_raster_policy.match_viewport) viewport.pixel_w else 0,
.minimum_height = if (pdf_raster_policy.match_viewport) viewport.pixel_h else 0,
.max_dimension = pdf_raster_policy.max_dimension,
};
}
fn pdfTintColors(p: *const Pardes) pdf_impl.TintColors {
if (comptime !pdf_enabled) return undefined;
const th = p.theme();
return .{
.background = th.bg orelse th.tag_bg,
.foreground = th.fg orelse th.tag_fg,
};
}
fn pdfTintKey(p: *const Pardes, pv: *const PdfView) PdfTintKey {
if (comptime !pdf_enabled) return undefined;
return .{ .mode = pv.tint, .colors = p.pdfTintColors() };
}
const PdfPlacedGeometry = struct {
geometry: image.NativeGeometry,
pixel_offset_y: f32,
};
fn pdfRasterForPage(pv: *PdfView, page: usize) ?*PdfRaster {
if (comptime !pdf_enabled) return null;
for (pv.rasters.items) |*raster|
if (raster.valid and raster.page == page) return raster;
return null;
}
fn syncPdfRasterAliases(pv: *PdfView, raster: *const PdfRaster) void {
if (comptime !pdf_enabled) return;
pv.rgba = raster.rgba;
pv.iw = raster.iw;
pv.ih = raster.ih;
pv.render_tried = raster.tried;
pv.render_request = raster.request;
pv.render_request_valid = raster.request_valid;
pv.render_revision = raster.revision;
}
fn pdfPlacedGeometry(
pv: *const PdfView,
raster: *const PdfRaster,
viewport: PdfViewport,
page: usize,
) ?PdfPlacedGeometry {
if (comptime !pdf_enabled) return null;
const page_h = pv.page_heights[page];
const base = image.nativeGeometry(
raster.iw,
raster.ih,
viewport.pixel_w,
page_h,
switch (pv.fit) {
.width => .width,
.height => .height,
},
pv.pan_x,
0,
) orelse return null;
if (base.dst.h == 0 or base.src.h == 0) return null;
const scroll_floor = @floor(pv.document_scroll_y);
const fractional: f32 = @floatCast(pv.document_scroll_y - scroll_floor);
const scroll_i: i64 = @intFromFloat(@min(
scroll_floor,
@as(f64, @floatFromInt(std.math.maxInt(i64))),
));
const start_i: i64 = @intCast(@min(
pv.page_starts[page],
@as(u64, std.math.maxInt(i64)),
));
const full_y = start_i - scroll_i + @as(i64, base.dst.y);
const full_bottom = full_y + @as(i64, base.dst.h);
const visible_y = @max(@as(i64, 0), full_y);
const visible_bottom = @min(@as(i64, viewport.pixel_h), full_bottom);
if (visible_bottom <= visible_y) return null;
const rel_y0: u64 = @intCast(visible_y - full_y);
const rel_y1: u64 = @intCast(visible_bottom - full_y);
const src_y0: u32 = base.src.y + @as(u32, @intCast(
rel_y0 * base.src.h / base.dst.h,
));
const src_y1: u32 = base.src.y + @as(u32, @intCast(@min(
@as(u64, base.src.h),
(rel_y1 * base.src.h + base.dst.h - 1) / base.dst.h,
)));
if (src_y1 <= src_y0) return null;
return .{
.geometry = .{
.src = .{
.x = base.src.x,
.y = src_y0,
.w = base.src.w,
.h = src_y1 - src_y0,
},
.dst = .{
.x = base.dst.x,
.y = @intCast(visible_y),
.w = base.dst.w,
.h = @intCast(visible_bottom - visible_y),
},
},
.pixel_offset_y = -fractional,
};
}
fn pdfGeometry(p: *const Pardes, pane: *const Pane) ?image.NativeGeometry {
if (comptime !pdf_enabled) return null;
const mutable = @constCast(pane);
const pv = if (mutable.pdf) |*view| view else return null;
const viewport = p.pdfViewport(pane) orelse return null;
const raster = pdfRasterForPage(pv, pv.page) orelse return null;
const placed = pdfPlacedGeometry(pv, raster, viewport, pv.page) orelse return null;
return placed.geometry;
}
fn pdfPageAtGridPoint(p: *const Pardes, pane: *const Pane, mrow: u16) ?usize {
if (comptime !pdf_enabled) return null;
const pv = pane.pdf orelse return null;
if (!pv.layout_valid) return null;
const r = for (p.panes, 0..) |slot, i| {
if (slot == pane) break p.rects[i];
} else return null;
if (mrow < r.y + BOX_H or mrow >= r.y + r.h) return null;
const local_y = @as(f64, @floatFromInt(
@as(u32, mrow - (r.y + BOX_H)) * p.cell_pixels.h + p.cell_pixels.h / 2,
));
const page = pdfPageAtOffset(&pv, pv.document_scroll_y + local_y);
const document_y = pv.document_scroll_y + local_y;
const start: f64 = @floatFromInt(pv.page_starts[page]);
if (document_y < start or
document_y >= start + @as(f64, @floatFromInt(pv.page_heights[page]))) return null;
return page;
}
fn pdfNativeReady(p: *const Pardes, pane: *const Pane) bool {
return p.native_images and p.pdfGeometry(pane) != null;
}
/// Convert a grid mouse position to normalized page space through the
/// exact crop/destination transform used by both native backends. Presses
/// in a letterbox return null; a live drag clamps to the page edge so a
/// sweep can finish naturally outside the image.
fn pdfPointAt(
p: *const Pardes,
pane: *const Pane,
mcol: u16,
mrow: u16,
clamp_to_page: bool,
) ?PdfPoint {
if (comptime !pdf_enabled) return null;
const pv = pane.pdf orelse return null;
const geometry = p.pdfGeometry(pane) orelse return null;
const r = for (p.panes, 0..) |slot, i| {
if (slot == pane) break p.rects[i];
} else return null;
const body_x = @as(i64, r.x + config.GUTTER);
const body_y = @as(i64, r.y + BOX_H);
var px = (@as(i64, mcol) - body_x) * p.cell_pixels.w + p.cell_pixels.w / 2;
var py = (@as(i64, mrow) - body_y) * p.cell_pixels.h + p.cell_pixels.h / 2;
if (clamp_to_page) {
px = std.math.clamp(
px,
@as(i64, geometry.dst.x),
@as(i64, geometry.dst.x + geometry.dst.w - 1),
);
py = std.math.clamp(
py,
@as(i64, geometry.dst.y),
@as(i64, geometry.dst.y + geometry.dst.h - 1),
);
} else if (px < 0 or py < 0 or
px > std.math.maxInt(u32) or py > std.math.maxInt(u32)) return null;
const source = geometry.sourcePoint(@intCast(px), @intCast(py)) orelse return null;
const fw: f32 = @floatFromInt(pv.iw);
const fh: f32 = @floatFromInt(pv.ih);
return .{
.x = (@as(f32, @floatFromInt(source.x)) + 0.5) / fw,
.y = (@as(f32, @floatFromInt(source.y)) + 0.5) / fh,
};
}
const PdfSelectionUpdate = enum { failed, unchanged, changed };
/// Transactionally replace the word-snapped selection and its owned text.
/// Drags defer the expensive baked-highlight raster until release;
/// snap-word execute/look presses may still request an immediate update.
fn setPdfSelection(
p: *Pardes,
pane: *Pane,
start: PdfPoint,
end: PdfPoint,
invalidate_raster: bool,
) PdfSelectionUpdate {
if (comptime !pdf_enabled) return .failed;
const pv = &(pane.pdf orelse return .failed);
if (pv.selection != null and
pv.selection_anchor != null and pv.selection_head != null and
pv.selection_anchor.?.x == start.x and pv.selection_anchor.?.y == start.y and
pv.selection_head.?.x == end.x and pv.selection_head.?.y == end.y) return .unchanged;
var selection = pv.document.select(p.gpa, pv.page, start, end) catch return .failed;
const text = pv.document.copySelection(
p.gpa,
pv.page,
selection.start,
selection.end,
) catch {
selection.deinit(p.gpa);
return .failed;
};
p.dropPdfSelection(pv);
pv.selection = selection;
pv.selection_text = text;
pv.selection_anchor = start;
pv.selection_head = end;
if (invalidate_raster) p.invalidatePdfRaster(pv);
return .changed;
}
fn beginPdfDrag(
p: *Pardes,
pane: *Pane,
mcol: u16,
mrow: u16,
snap_word: bool,
) bool {
if (comptime !pdf_enabled) return false;
const hit_page = p.pdfPageAtGridPoint(pane, mrow) orelse return false;
if (hit_page != pane.pdf.?.page) {
p.activatePdfPage(pane, hit_page, false);
if (pdfRasterForPage(&pane.pdf.?, hit_page)) |raster|
syncPdfRasterAliases(&pane.pdf.?, raster);
}
const pv = &pane.pdf.?;
clearPdfDrag(pv);
const point = p.pdfPointAt(pane, mcol, mrow, false) orelse {
return false;
};
pv.drag_anchor = point;
pv.drag_head = point;
if (!snap_word) return true;
if (pv.selection) |selection| if (selection.contains(point)) {
return true;
};
if (p.setPdfSelection(pane, point, point, true) == .failed) {
// The old selection is intentionally transactional and survives,
// but this outside click must not execute that stale text.
clearPdfDrag(pv);
return false;
}
return true;
}
fn beginPdfSelection(p: *Pardes, pane: *Pane, mcol: u16, mrow: u16) bool {
return p.beginPdfDrag(pane, mcol, mrow, true);
}
fn updatePdfSelection(
p: *Pardes,
pane: *Pane,
mcol: u16,
mrow: u16,
invalidate_raster: bool,
) bool {
if (comptime !pdf_enabled) return false;
const pv = &(pane.pdf orelse return false);
const anchor = pv.drag_anchor orelse return false;
const point = p.pdfPointAt(pane, mcol, mrow, true) orelse return false;
if (pv.drag_head) |head| if (head.x == point.x and head.y == point.y) return false;
const result = p.setPdfSelection(pane, anchor, point, invalidate_raster);
if (result != .failed) {
pv.drag_head = point;
}
return result == .changed;
}
fn pdfHighlights(p: *Pardes, pv: *PdfView) ![]const PdfHighlight {
if (comptime !pdf_enabled) return &.{};
var highlights: std.ArrayList(PdfHighlight) = .empty;
const arena = p.scratch.allocator();
if (pv.search_results) |results| {
try highlights.ensureUnusedCapacity(arena, results.quads.len);
for (results.quads) |item| highlights.appendAssumeCapacity(pdf_impl.Highlight.init(
item.quad,
.{ 0xff, 0xd5, 0x4f, 0x70 },
.search,
));
}
if (pv.selection) |selection| {
try highlights.ensureUnusedCapacity(arena, selection.quads.len);
// a page is not a grid of cells, so this is the one selection that
// paints as a translucent wash over rendered pixels rather than as
// a cell's background — but it is the same selection, so it is the
// same colour. The alpha stays hardcoded: it is what makes the
// glyphs underneath readable, and no theme has an opinion on it.
const sel = p.theme().sel_bg;
for (selection.quads) |quad| highlights.appendAssumeCapacity(pdf_impl.Highlight.init(
quad,
.{ sel[0], sel[1], sel[2], 0x78 },
.selection,
));
}
return highlights.items;
}
/// Move one normalized pan axis by a distance measured in DISPLAY pixels.
/// NativeGeometry supplies both the displayed and cropped extents, so this
/// remains exact for non-square cells and rounded page scaling.
fn panPdfPixels(
p: *Pardes,
pane: *Pane,
axis: PdfPanAxis,
direction: i8,
display_pixels: u32,
) PdfPanResult {
if (comptime !pdf_enabled) return .unavailable;
const geometry = p.pdfGeometry(pane) orelse return .unavailable;
const pv = &(pane.pdf orelse return .unavailable);
const source_full: u32 = @intCast(switch (axis) {
.horizontal => pv.iw,
.vertical => pv.ih,
});
const crop = switch (axis) {
.horizontal => geometry.src.w,
.vertical => geometry.src.h,
};
const source_at = switch (axis) {
.horizontal => geometry.src.x,
.vertical => geometry.src.y,
};
const displayed = @max(@as(u32, 1), switch (axis) {
.horizontal => geometry.dst.w,
.vertical => geometry.dst.h,
});
const overflow = source_full -| crop;
if (overflow == 0 or
(direction < 0 and source_at == 0) or
(direction > 0 and source_at >= overflow)) return .edge;
const source_step = @max(
@as(u64, 1),
(@as(u64, display_pixels) * @as(u64, crop) + displayed - 1) / displayed,
);
const normalized_step: u32 = @intCast(@min(
@as(u64, std.math.maxInt(u16)),
@max(
@as(u64, 1),
(source_step * std.math.maxInt(u16) + overflow - 1) / overflow,
),
));
const position = switch (axis) {
.horizontal => &pv.pan_x,
.vertical => &pv.pan_y,
};
if (direction > 0) {
position.* = @intCast(@min(
@as(u32, std.math.maxInt(u16)),
@as(u32, position.*) + normalized_step,
));
} else {
position.* -|= @intCast(normalized_step);
}
return .moved;
}
fn scaledPdfStep(base: u32, count: u32) u32 {
return @intCast(@min(
@as(u64, std.math.maxInt(u32)),
@as(u64, base) * @max(@as(u64, 1), count),
));
}
/// Move through the strip by exact display pixels. Page changes update
/// semantic search/selection state, but never evict unchanged page pixels.
fn scrollPdfDocument(p: *Pardes, pane: *Pane, delta_pixels: f64) bool {
if (comptime !pdf_enabled) return false;
if (!std.math.isFinite(delta_pixels) or delta_pixels == 0) return false;
const pv = &(pane.pdf orelse return false);
const viewport = p.ensurePdfLayout(pane, pv) orelse return false;
const max_scroll = @as(f64, @floatFromInt(pv.document_height -| viewport.pixel_h));
const next = std.math.clamp(pv.document_scroll_y + delta_pixels, 0, max_scroll);
if (next == pv.document_scroll_y) return false;
pv.document_scroll_y = next;
const active_page = pdfPageAtOffset(pv, next);
if (active_page != pv.page) p.activatePdfPage(pane, active_page, false);
return true;
}
fn pdfVerticalWheel(p: *Pardes, pane: *Pane, direction: i8) void {
if (comptime !pdf_enabled) return;
if (!p.native_images) {
p.stepPdfPage(pane, direction);
return;
}
const rows: u32 = @intCast(@max(1, config.wheel_rows));
const pixels = scaledPdfStep(p.cell_pixels.h, rows);
_ = p.scrollPdfDocument(pane, @as(f64, @floatFromInt(pixels)) * direction);
}
fn pdfHorizontalWheel(p: *Pardes, pane: *Pane, direction: i8) void {
if (comptime !pdf_enabled) return;
const pv = pane.pdf orelse return;
if (!p.native_images or pv.fit != .height) return;
const cols: u32 = @intCast(@max(1, config.wheel_cols));
_ = p.panPdfPixels(pane, .horizontal, direction, scaledPdfStep(p.cell_pixels.w, cols));
}
fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void {
if (comptime !pdf_enabled) return;
if (pane.pdf == null) return;
var state = paneNormalState(pane);
const parsed = normal_input.parse(&state, normalInput(key));
putPaneNormalState(pane, state);
switch (parsed) {
.pending, .ignored, .unbound => {},
.action => |semantic| p.executePdfNormalAction(pane, semantic),
}
}
/// PDF vertical actions use exact display pixels in the continuous native
/// strip. The cell, half-view and full-view bases are multiplied by the
/// parsed count. A non-native shell has no pixel strip and deliberately
/// falls back to counted page steps for all three.
fn movePdfVertical(p: *Pardes, pane: *Pane, direction: i8, kind: normal_input.Page, count: u32) void {
if (comptime !pdf_enabled) return;
if (!p.native_images) {
const pages: i64 = @intCast(@max(@as(u32, 1), count));
p.stepPdfPage(pane, if (direction > 0) pages else -pages);
return;
}
const viewport = p.pdfViewport(pane);
const base: u32 = switch (kind) {
.half_down, .half_up => if (viewport) |v| @max(@as(u32, 1), v.pixel_h / 2) else p.cell_pixels.h,
.down, .up => if (viewport) |v| v.pixel_h else p.cell_pixels.h,
};
const pixels = scaledPdfStep(base, count);
_ = p.scrollPdfDocument(pane, @as(f64, @floatFromInt(pixels)) * direction);
}
fn movePdfRows(p: *Pardes, pane: *Pane, direction: i8, count: u32) void {
if (comptime !pdf_enabled) return;
if (!p.native_images) {
const pages: i64 = @intCast(@max(@as(u32, 1), count));
return p.stepPdfPage(pane, if (direction > 0) pages else -pages);
}
const pixels = scaledPdfStep(p.cell_pixels.h, count);
_ = p.scrollPdfDocument(pane, @as(f64, @floatFromInt(pixels)) * direction);
}
fn pdfHorizontalEdge(p: *Pardes, pane: *Pane, end: bool) void {
if (comptime !pdf_enabled) return;
if (!p.native_images) return;
const geometry = p.pdfGeometry(pane) orelse return;
const pv = &(pane.pdf orelse return);
const full: u32 = @intCast(pv.iw);
if (full <= geometry.src.w) return;
pv.pan_x = if (end) std.math.maxInt(u16) else 0;
}
/// Deliberately incomplete PDF adapter. Unsupported edit/selection/text
/// actions have already consumed their parser state and are safe no-ops.
fn executePdfNormalAction(p: *Pardes, pane: *Pane, semantic: normal_input.Action) void {
if (comptime !pdf_enabled) return;
const pv = &(pane.pdf orelse return);
switch (semantic) {
.escape => {
pane.select = false;
return p.runBuiltin(.Toggleterm, p.active, "", null);
},
.move => |move| switch (move.motion) {
.down => p.movePdfRows(pane, 1, move.count),
.up => p.movePdfRows(pane, -1, move.count),
.left => if (p.native_images) {
_ = p.panPdfPixels(pane, .horizontal, -1, scaledPdfStep(p.cell_pixels.w, move.count));
},
.right => if (p.native_images) {
_ = p.panPdfPixels(pane, .horizontal, 1, scaledPdfStep(p.cell_pixels.w, move.count));
},
else => {},
},
.goto => |go| switch (go.target) {
.file_start => p.setPdfPage(pane, if (go.explicit_count) go.count -| 1 else 0),
.last_line => p.setPdfPage(pane, pv.page_count -| 1),
.line_start, .first_nonws => p.pdfHorizontalEdge(pane, false),
.line_end => p.pdfHorizontalEdge(pane, true),
.line_down => p.movePdfRows(pane, 1, go.count),
.line_up => p.movePdfRows(pane, -1, go.count),
else => {},
},
.line => |line| switch (line) {
.start, .first_nonws => p.pdfHorizontalEdge(pane, false),
.end => p.pdfHorizontalEdge(pane, true),
},
.goto_line => |go| if (go.explicit) p.setPdfPage(pane, go.count -| 1),
.page => |page| switch (page.kind) {
.half_down, .down => p.movePdfVertical(pane, 1, page.kind, page.count),
.half_up, .up => p.movePdfVertical(pane, -1, page.kind, page.count),
},
.view => |view| switch (view) {
.scroll_down => p.movePdfRows(pane, 1, 1),
.scroll_up => p.movePdfRows(pane, -1, 1),
else => {},
},
.leader => {
p.leader_on = true;
p.leader_n = 0;
},
.command_line => {
p.enterTagEdit(pane, -1);
if (pane.tag_edit) pane.mode = .normal;
},
.search => p.startSearch(pane, config.search_marker),
.search_step => |direction| {
_ = p.searchStep(p.active, if (direction == .forward) 1 else -1);
},
else => {},
}
}
/// stack a fresh doc pane at the top of the LEFT column (acme convention:
/// files left, terminals right), halving ONLY the old top pane's slot so
/// the rest of the column keeps its sizes; then evict a leftover pristine
/// shell. The placement of last resort — a first doc normally takes a
/// column of its own (placeDoc), and this only runs when the column bar
/// is full.
fn stackDocLeft(p: *Pardes, free: usize, nt: *Pane) void {
const lc = 0;
if (p.col_n[lc] > 0) if (p.panes[p.col_terms[lc][0]]) |top| {
p.snapColWeights(lc);
const h = p.rects[p.col_terms[lc][0]].h;
nt.vweight = @floatFromInt(@max(1, h / 2));
top.vweight = @floatFromInt(@max(1, h -| h / 2));
};
p.layoutInsert(lc, 0, free);
p.active = free;
p.evictLonePristineTty(lc, free);
}
// ---- the ONE dispatcher: look (right/Enter) and execute (middle/Tab) ----
/// Focus pane `id` and, for a nonzero 1-based `at.line`, put its modal
/// cursor there (`at.col` likewise, 0 = line start): files recenter the
/// view on it, terminals ride their scrollback to it. Both look targets
/// that name a live pane land here — a path a pane already holds, and
/// `@pN:LINE:COL`. A RANGED spot selects (selectSpan below).
pub fn focusPaneLine(p: *Pardes, id: usize, at: look.Spot) void {
if (id >= MAX_PANES) return;
const pane = p.panes[id] orelse return;
p.active = id;
if (hasPdf(pane)) {
if (comptime pdf_enabled) {
if (at.line > 0) p.setPdfPage(pane, at.line - 1);
const pv = &pane.pdf.?;
// PDF search result rows use Spot.col as a one-based MuPDF
// logical hit id, not a text column. Rearming reveal moves
// only fit/pan; the page raster already contains every hit.
if (at.col > 0 and pv.search_query.len > 0) {
pv.search_hit = at.col - 1;
pv.search_reveal_pending = true;
}
}
return;
}
if (at.line == 0) return;
if (pane.file) |*f| {
if (at.line > file_pane.nlines(p.gpa, f)) return;
const next = (at.line - 1) -| pane.rows / 2; // center, clamp at top
if (next != f.scroll) {
f.scroll = next;
f.syntax_dirty = true;
}
}
// land the modal cursor on the target line (and keep
// ensureCursorVisible agreeing with the recenter — a stale cursor
// would yank the view right back)
pane.cur_row = @intCast(at.line - 1);
pane.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0;
pane.cur_pinned = true;
if (at.end_line != 0) return p.selectSpan(pane, at);
pane.ensureCursorVisible();
}
/// Select the span a RANGED look word names (config.range_sep): the two
/// ends are block-cursor CELLS, so this is the same cellRange/setPaneRange
/// pair every motion writes back through — the cursor lands on the span's
/// last cell with the anchor on its first, which is where helix leaves you
/// after a search too.
///
/// EXPLICIT, so the acme chords act on it like a v/x selection: the whole
/// point of `n` selecting a hit is being able to chord the match straight
/// into the next command.
///
/// Everything clamps, because a range is a claim about a file that may
/// have changed underneath it: hxOff pins a row past the end to the last
/// line and a column past the end to that line's terminator, so a stale
/// row selects what is still there instead of crashing or highlighting
/// garbage. A whole-lines range (no end column) runs to the terminator by
/// asking for a column no line can have, which is helix's own `x`.
fn selectSpan(p: *Pardes, pane: *Pane, at: look.Spot) void {
const pl = p.paneCursorLines(pane) catch return;
const text = p.flatSurface(pane, pl) catch return;
// saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a
// 1-based zero is the same nothing an absent number is
const acol: i32 = @intCast(at.col -| 1);
const ecol: i32 = if (at.end_col > 0) @intCast(at.end_col - 1) else std.math.maxInt(i32);
const r = cellRange(text, @intCast(at.line -| 1), acol, @intCast(at.end_line -| 1), ecol);
setPaneRange(pane, pl, text, r, true);
}
/// focus the pane already loaded on `path` (exact match), if any: file
/// panes recenter on a :NN line like the look dedup always has, image
/// panes just focus. Returns false when no pane holds that path.
fn focusPaneByPath(p: *Pardes, path: []const u8, at: look.Spot) bool {
for (p.panes, 0..) |slot, i| {
const tt = slot orelse continue;
if (tt.image) |iv| if (std.mem.eql(u8, iv.path, path)) {
p.active = i;
return true;
};
if (comptime pdf_enabled) if (tt.pdf) |pv| if (std.mem.eql(u8, pv.path, path)) {
p.focusPaneLine(i, at);
return true;
};
const ff = if (tt.file) |*f| f else continue;
if (!std.mem.eql(u8, ff.path, path)) continue;
p.focusPaneLine(i, at);
return true;
}
return false;
}
fn revealPdfOutlineDestination(
p: *Pardes,
pane: *Pane,
destination: pdf_impl.OutlineInternalDestination,
) void {
if (comptime !pdf_enabled) return;
p.activatePdfPage(pane, destination.page, false);
const pv = &pane.pdf.?;
pv.scroll_to_page_pending = false;
pv.layout_anchor_pending = false;
pv.outline_reveal_pending = destination;
// Consume immediately when geometry already exists; otherwise drawPdf
// consumes the same pending value after the next layout transaction.
_ = p.ensurePdfLayout(pane, pv);
}
/// PdfSections alone gives Spot.col a second meaning: the one-based DFS
/// ordinal written into its generated leading token. It is checked before
/// ordinary PDF focus so search-result columns everywhere else retain
/// their existing logical-hit meaning.
fn lookPdfSection(p: *Pardes, output_id: usize, path: []const u8, at: look.Spot) bool {
if (comptime !pdf_enabled) return false;
const output = p.panes[output_id] orelse return false;
if (!isPdfSectionsOutput(output)) return false;
if (at.line == 0 or at.col == 0 or at.end_line != 0 or
!look.isPdfPath(path)) return false;
// Internal section rows use the basename so their titles remain
// visible. Resolve that token from +PdfSections' document directory
// before matching an open PDF or opening it again.
var joined_path: [4096]u8 = undefined;
const output_dir = paneDir(output);
const separator = if (std.mem.endsWith(u8, output_dir, "/")) "" else "/";
const target_path = if (std.fs.path.isAbsolute(path))
path
else
std.fmt.bufPrint(&joined_path, "{s}{s}{s}", .{ output_dir, separator, path }) catch return true;
var target_id: ?usize = null;
for (p.panes, 0..) |slot, i| {
const candidate = slot orelse continue;
if (candidate.pdf) |pv| if (std.mem.eql(u8, pv.path, target_path)) {
target_id = i;
break;
};
}
if (target_id == null) {
const free = p.freeSlot() orelse return true;
const fresh = p.openPdfView(free, target_path, 0) catch return true;
p.placeDoc(output_id, free, fresh);
p.computeGeom();
target_id = free;
}
const id = target_id.?;
const pane = p.panes[id] orelse return true;
const pv = &pane.pdf.?;
const outline = p.ensurePdfOutline(pv) orelse return true;
const destination = PdfSectionRows.resolve(outline.entries, at.col - 1) orelse return true;
switch (destination) {
.internal => |internal| p.revealPdfOutlineDestination(pane, internal),
.external => |uri| if (uri.len <= 256) p.emit(.{ .open_link = .from(uri) }),
.none => unreachable,
}
p.active = id;
return true;
}
/// LOOK — the Look builtin's body, and so what a right click, an Enter and
/// the word `Look` all end at. Resolve `txt` against the panes' directories
/// and open (or focus) whatever it names; a word that names nothing is a
/// search of the pane it came from, which is acme's button-3.
pub fn lookAt(p: *Pardes, id: usize, txt: []const u8) void {
const pane = p.panes[id] orelse return;
const trimmed = std.mem.trim(u8, txt, " \t\r\n");
// `` @`ls -la` `` names a COMMAND, not a path: run it, and land in the
// pane that answers — looking at a thing means being SHOWN it, and a
// command's output is what there is to be shown. Looking at a
// DIRECTORY has always been exactly this (below: focus a shell there
// and make it `ls`); this is that rule spelled generally.
if (config.commandWord(trimmed)) |cmd| {
if (p.execute(id, cmd)) |dst| p.active = dst;
return;
}
var realbuf: [4096]u8 = undefined;
// an already-loaded pane wins BEFORE any filesystem resolve: the
// web build has no fs (a look would otherwise be inert even for
// panes sitting in the session), and native gets the same dedup
// it always did, just without touching disk. Pane paths are
// canonical (realpath'd or dump-given), so match the word as-is
// here and joined onto each directory below.
const pl = look.parsePathLine(trimmed);
if (comptime pdf_enabled) if (p.lookPdfSection(id, pl.path, pl.at)) return;
if (pl.path.len > 0 and p.focusPaneByPath(pl.path, pl.at)) return;
// The word is resolved against the pane DIRECTORIES in access
// order: the pane the click came from FIRST — its answer is the
// one taken, so nothing that resolves today moves — then every
// other live pane, most recently focused first (the jump stack runs
// least-recent -> active, so it is that array backwards; the
// clicked pane is not always `active`, a right click does not
// focus). Only when ALL of them fail does the word fall through to
// the search below: a name you can read in one window is openable
// from any of them. Each attempt is a realpath + an open and
// shells share cwds constantly, so a seen-list holds every
// directory to one try; an absolute word — and `@pN`, which reads
// no directory at all — answers the same everywhere and stops
// after the first pass.
var found: look.Target = .none;
var seen: [MAX_PANES][]const u8 = undefined;
var nseen: usize = 0;
var n: usize = 0;
cand: while (n <= p.njumps) : (n += 1) {
const k: usize = if (n == 0) id else p.jumps[p.njumps - n].pane;
if (n > 0 and k == id) continue; // tried first, skip the rerun
const op = p.panes[k] orelse continue;
const dir = paneDir(op);
for (seen[0..nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand;
seen[nseen] = dir;
nseen += 1;
if (pl.path.len > 0 and pl.path[0] != '/') {
var joinbuf: [2048]u8 = undefined;
if (std.fmt.bufPrint(&joinbuf, "{s}/{s}", .{ dir, pl.path }) catch null) |j|
if (p.focusPaneByPath(j, pl.at)) return;
}
found = look.resolve(txt, dir, &realbuf);
if (found != .none or pl.path.len == 0 or pl.path[0] == '/') break;
}
switch (found) {
// acme button-3: a word that names no file/dir is a search of
// the pane it was clicked in — exactly what `/` runs, and then a
// step onto a hit, so a click GOES somewhere and clicking again
// goes to the next one. Paths (src/a/b.rs:100) still resolve above
// and open; only the non-file case falls through here. A shell
// searches its scrollback like anything else, EXCEPT in tty
// mode, where the click belongs to the program on the other
// end; an image pane has no text to search either way.
.none => {
const bmode = if (pane.tag_edit) pane.tag_mode else pane.mode;
if (pane.image != null or bmode == .tty) return;
// ...and then STEP it, which is the other half of button-3: a
// click does not merely LIST the hits, it goes to one — the
// one AFTER the word clicked, since runSearch armed the walk
// where the click put the cursor. Asking again is free: the
// same pattern refills its own list rather than opening a
// second, so clicking a word repeatedly walks its hits.
p.runSearch(id, trimmed, .text, .cursor);
const at = pane.search_row;
_ = p.searchStep(id, 1);
// past the last hit, back to the first: acme's search is a
// RING, and a step that could not move left the row where it
// was (searchStep clamps rather than wrapping, because n/N are
// also how `]d`/`[d` walk to the end of a list and stop).
if (at != null and pane.search_row == at) {
pane.search_row = null;
_ = p.searchStep(id, 1);
}
},
// `@p7:10:5`: pane 7, line 10, column 5 — how a search result
// points at a terminal or an output buffer, neither of which
// has a path.
.pane => |t| p.focusPaneLine(t.id, t.at),
.url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }),
.dir => |dir| {
// focus an existing terminal on this dir, else fork one below
for (p.panes, 0..) |slot, i| {
if (slot) |tt| if (tt.isTerminal() and std.mem.eql(u8, tt.cwdSlice(), dir)) {
p.active = i;
p.emitWrite(i, "ls\r");
return;
};
}
const free = p.freeSlot() orelse return;
const nt = p.newShell(free, dir) catch return;
nt.greet = true;
const src = p.splitParent(id);
const f = p.layoutFindTerm(src).?;
p.layoutInsert(f.col, f.idx + 1, free);
p.splitBelow(src, nt);
p.active = free;
},
.file => |target| {
if (comptime pdf_enabled) if (target.kind == .pdf) {
if (p.focusPaneByPath(target.path, target.at)) return;
const free = p.freeSlot() orelse return;
const nt = p.openPdfView(free, target.path, target.at.line) catch return;
p.placeDoc(id, free, nt);
return;
};
// focus an existing pane on this path (rescrolled), else open
if (p.focusPaneByPath(target.path, target.at)) return;
const free = p.freeSlot() orelse return;
const nt = file_pane.open(p, free, target.path, target.at.line) catch return;
if (target.at.col > 0) nt.cur_col = @intCast(target.at.col - 1);
p.placeDoc(id, free, nt);
// center the target line: the pane's real body height only
// exists after placement, so lay out now and pull the
// scroll up by half a body (line 0 opens stay at the top)
p.computeGeom();
nt.file.?.scroll -|= @max(1, p.rects[free].h -| BOX_H) / 2;
// ...and only THEN select a range, restoring that scroll:
// setPaneRange keeps its cursor visible, and a pane this fresh
// has no true geometry yet for it to judge against (pane.rows
// is only refreshed in sync), so the centering just computed is
// the answer and ensureCursorVisible's is not.
if (target.at.end_line != 0) {
const centered = nt.file.?.scroll;
p.selectSpan(nt, target.at);
nt.file.?.scroll = centered;
}
},
.image => |target| {
if (p.focusPaneByPath(target.path, .{})) return;
const free = p.freeSlot() orelse return;
const nt = p.openImageView(free, target.path) catch return;
p.placeDoc(id, free, nt);
},
}
}
/// how deep `execute` may re-enter itself. Nothing can reach this today:
/// every door back in strips at least one word (`Exec X` -> `X`) or one
/// pair of delimiters (`` @`X` `` -> `X`), so the command line strictly
/// shrinks and a cycle cannot close — executing the bare word `Exec` runs
/// out of argument immediately. The counter is here so that a syntax added
/// later which does NOT shrink (an alias, a macro) stops instead of hanging
/// the editor, and the ceiling is small because a human nesting eight deep
/// has made a different mistake.
const max_exec_depth = 8;
/// EXECUTE — the Exec builtin's body, and so what a middle click, a Tab
/// and the word `Exec` all end at. A builtin's NAME runs the builtin;
/// anything else is a command line typed at a shell. Returns the pane it
/// was typed into, which is what Look focuses and an execute deliberately
/// does not.
pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize {
const pane = p.panes[id] orelse return null;
const cmd = commandText(txt);
if (cmd.len == 0) return null;
if (p.executeBuiltinLine(id, cmd)) return null;
if (p.exec_depth >= max_exec_depth) return null;
p.exec_depth += 1;
defer p.exec_depth -= 1;
// Anything not in the builtin vocabulary is a command line typed at
// a shell. Startup config calls executeBuiltinLine directly and never
// reaches this fallback.
// A terminal runs in itself. Every document kind — real/output file,
// image, or PDF — runs in a terminal for its directory (an existing
// one when possible, otherwise a freshly forked shell). In particular,
// never emit a PTY write addressed to an image's no-PTY pane slot.
const dst = (if (pane.isTerminal()) id else p.ttyForDir(paneDir(pane))) orelse return null;
term_pane.padOutputBelowEdits(p, dst);
p.emitWrite(dst, cmd);
p.emitWrite(dst, "\r");
return dst;
}
/// Trim and unwrap clickable command-word notation once for every command
/// consumer, so startup lines and interactive Exec speak the same syntax.
fn commandText(txt: []const u8) []const u8 {
var cmd = std.mem.trim(u8, txt, " \t\r\n");
while (config.commandWord(cmd)) |inner| cmd = std.mem.trim(u8, inner, " \t\r\n");
return cmd;
}
/// Parse and dispatch exactly one builtin command. This is the canonical
/// builtin path used both by ordinary Exec and by startup configuration;
/// unlike execute(), it deliberately has no external-shell fallback.
/// False means blank, malformed, unknown, or recursion-limited.
pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool {
const cmd = commandText(txt);
if (cmd.len == 0 or p.exec_depth >= max_exec_depth) return false;
// The builtins that take an ARGUMENT match their name with a TAIL:
// `Restore <path>`, `Find <pat>`, `Grep <pat>`, `Rename <name>`,
// `WsSymbols <sym>`, `Theme <name>`, `Font <name>` (gui only), and the
// two verbs themselves — `Look <word>`, `Exec <cmd>`, which is what
// makes `` @`Look .` `` nest (the tail goes straight back through
// here). Every other name must match WHOLE, so `Kill foo` is a shell
// command and not Kill.
const sp = std.mem.indexOfAny(u8, cmd, " \t");
const bi: ?Builtin = std.meta.stringToEnum(Builtin, cmd) orelse blk: {
const head = std.meta.stringToEnum(Builtin, cmd[0 .. sp orelse break :blk null]) orelse break :blk null;
break :blk switch (head) {
.Restore, .Find, .Grep, .Rename, .WsSymbols, .Theme, .Look, .Exec => head,
// Font is a BRANCH and not another name in that prong for the
// reason output_pane.traits has the same shape: it is not in
// the enum at all off the gui, and a comptime-false `if` is
// the one form that is not analysed there.
else => {
if (platform == .gui) if (head == .Font) break :blk head;
break :blk null;
},
};
};
const b = bi orelse return false;
p.exec_depth += 1;
defer p.exec_depth -= 1;
const typed = if (sp) |s| std.mem.trim(u8, cmd[s + 1 ..], " \t") else "";
p.runBuiltin(b, id, cmd, if (typed.len > 0) typed else null);
return true;
}
fn applyStartupConfig(p: *Pardes) void {
var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n');
while (lines.next()) |line| _ = p.executeBuiltinLine(p.active, line);
}
/// Run a builtin on pane `id`. `txt` is the executed text (Restore reads
/// its path back out of it) and `arg` the builtin's ARGUMENT — the tail
/// after the name, which is why Grep and Find run straight away when there
/// is one instead of asking, and which for Look and Exec is the whole
/// operand. A gesture that points at a word (a click, an Enter) passes it
/// as `arg` with no `txt`: it named no builtin, config.look_cmd did. The
/// leader passes "" and null: a key path names a builtin, never an
/// argument. The topbar builtins are global; the pane-scoped ones (Save,
/// Del, Delcol, the image toggles, and the window group, which moves focus
/// relative to `id`) act on `id`. The null-pane check is the one guard
/// every builtin used to share, so it stays here rather than in each.
fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void {
if (!p.multiOnce()) return; // a builtin is per-keystroke, never per-cursor
const pane = p.panes[id] orelse return;
const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg };
inline for (comptime builtins.all(), 0..) |B, i| if (@intFromEnum(b) == i) return B.run(c);
}
/// place a fresh doc pane. An OUTPUT buffer (+Search/+Help) is NOT a
/// document: it is the result list belonging to the pane that asked for it,
/// so it never claims a column and is never anyone else's split parent — it
/// lands right below `from_id`, be that a shell, a file or another list,
/// and `from_id` alone pays the rows (several lists just stack there).
/// A real doc joins the docs: any doc already open is the split parent (the
/// source if it IS one, else the one most recently worked in) and the
/// newcomer lands right below it, so docs share a column. The FIRST doc of
/// the session instead gets a column of its own on the left (acme: files
/// left, shells right) — nothing is displaced, the other columns just
/// narrow. A full column bar, or a result list whose source died, stacks
/// into the leftmost.
pub fn placeDoc(p: *Pardes, from_id: usize, free: usize, nt: *Pane) void {
const doc = if (nt.file) |f| output_pane.fileTraits(f.output).doc else true; // an image is a doc
var src_id: ?usize = null;
if (p.panes[from_id]) |src| if (if (src.file) |f| output_pane.fileTraits(f.output).doc else src.image != null or hasPdf(src)) {
src_id = from_id;
};
// Opened from somewhere that is NOT a doc (a shell, a results list):
// the file joins the column it was last being READ in, which is the
// newest doc on the jump stack. The stack already IS that record — it
// is where the keyboard has been — so nothing new is remembered here;
// asking it is the whole change. What this replaces was the first doc
// in slot order, i.e. pane-id ALLOCATION order, so which column your
// file landed in depended on how the session had handed out ids rather
// than on where you were working.
//
// The answer wanted is the COLUMN, and it stays right once the pane
// itself is closed: trackJump compacts dead entries out, so the walk
// falls through to the next doc remembered in that same column. The
// serial test is the one trackJump uses — slots are reused, so an entry
// whose pane has been replaced names a pane that is gone, not the
// newcomer sitting in its slot (`free`, this very pane, among them).
if (doc and src_id == null) {
var n = p.njumps;
while (n > 0) : (n -= 1) {
const j = p.jumps[n - 1];
const pp = p.panes[j.pane] orelse continue;
if (pp.serial != j.serial) continue;
if (if (pp.file) |f| output_pane.fileTraits(f.output).doc else pp.image != null or hasPdf(pp)) {
src_id = j.pane;
break;
}
}
}
// A doc no jump remembers is still a doc: a restored session focuses
// one pane, not each, and the stack is finite. The rule that a second
// doc never claims a second column outranks knowing where you were, so
// the old slot-order scan stays as the fallback.
if (doc and src_id == null) for (p.panes, 0..) |sl, i| {
if (sl) |pp| if (i != free and (if (pp.file) |f| output_pane.fileTraits(f.output).doc else pp.image != null or hasPdf(pp))) {
src_id = i;
break;
};
};
// A result list belongs to its spawner: it lands directly BELOW it —
// on top of the lists already there — and its rows come out of the
// SPAWNER, never a bystander, so opening another list (or deleting
// one, see absorbVWeight) leaves every other pane's height untouched.
if (!doc) if (p.layoutFindTerm(from_id)) |sf| {
p.layoutInsert(sf.col, sf.idx + 1, free);
p.splitBelow(from_id, nt); // NOT splitParent: no bystander pays
p.active = free;
return;
};
if (src_id) |sid| {
const src = p.splitParent(sid);
const sf = p.layoutFindTerm(src).?;
p.layoutInsert(sf.col, sf.idx + 1, free);
p.splitBelow(src, nt);
p.active = free;
return;
}
if (doc and p.ncol < MAX_COLS) {
p.layoutInsertColumn(0, free);
p.active = free;
return;
}
p.stackDocLeft(free, nt);
}
// ---- dump / load (acme-style: `pardes -l state.zon` restores a session) ----
pub fn dumpState(p: *Pardes) !void {
const arena = p.scratch.allocator();
var slot_to_pane: [MAX_PANES]?usize = @splat(null);
var panes: std.ArrayList(dump.Pane) = .empty;
for (p.panes, 0..) |slot, id| {
const pane = slot orelse continue;
slot_to_pane[id] = panes.items.len;
const tag = try p.tagText(arena, pane);
const body = try p.bodyText(arena, pane);
const scroll: usize = @intCast(@max(0, pane.scroll()));
// BY POINTER: `origin_arg` is a slice into the File's own inline
// buffer, and a by-value capture would leave it pointing at a
// stack copy that dies before the ZON is written.
const dp: dump.Pane = if (pane.file) |*f| .{
.kind = .file,
.tag = tag,
.body = body,
.scroll = scroll,
.cols = pane.cols,
.rows = pane.rows,
.vweight = pane.vweight,
.file = .{
.path = f.path,
.content = f.content,
.content_b64 = try dump.encodeBytes(arena, f.content),
.origin = if (f.output) |o| output_pane.word(o.from) else "",
.origin_arg = if (f.output) |*o| o.arg() else "",
},
} else if (hasPdf(pane)) blk: {
if (comptime !pdf_enabled) unreachable;
const pv = pane.pdf.?;
const bytes = look.readFile(arena, pv.path) catch "";
// Keep the dump schema backwards-compatible: a raster-backed
// document rides the existing binary image record, while its
// `scroll` field is the zero-based PDF page. Restore inspects
// the extension and reconstructs the semantic PDF pane.
break :blk .{
.kind = .image,
.tag = tag,
.body = body,
.scroll = pv.page,
.cols = pane.cols,
.rows = pane.rows,
.vweight = pane.vweight,
.image = .{
.path = pv.path,
.bytes_b64 = if (bytes.len > 0) try dump.encodeBytes(arena, bytes) else "",
},
};
} else if (pane.image) |iv| blk: {
const bytes = look.readFile(arena, iv.path) catch "";
break :blk .{
.kind = .image,
.tag = tag,
.body = body,
.scroll = scroll,
.cols = pane.cols,
.rows = pane.rows,
.vweight = pane.vweight,
.image = .{
.path = iv.path,
.bytes_b64 = if (bytes.len > 0) try dump.encodeBytes(arena, bytes) else "",
},
};
} else blk: {
// the stream text: whole history, prompts hidden outside tty
// mode, the edit buffer standing in for the rows it covers
const full = try pane.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} });
var stream_text: std.ArrayList(u8) = .empty;
var lines = std.mem.splitAny(u8, full, "\n");
var prompts = pane.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null);
var row: i32 = 0;
var skip: i32 = 0;
while (lines.next()) |raw| : (row += 1) {
const is_prompt = if (pane.mode != .tty)
if (prompts.next()) |pin| pin.rowAndCell().row.semantic_prompt != .none else false
else
false;
if (skip > 0) {
skip -= 1;
continue;
}
if (row > 0) try stream_text.append(arena, '\n');
if (pane.mode != .tty) if (pane.ovl) |o| if (row == o.row) {
try stream_text.appendSlice(arena, o.text);
skip = o.rows - 1;
continue;
};
try stream_text.appendSlice(arena, if (is_prompt) "" else raw);
}
break :blk .{
.kind = .terminal,
.tag = tag,
.body = body,
.scroll = scroll,
.cols = pane.cols,
.rows = pane.rows,
.vweight = pane.vweight,
.terminal = .{
.cwd = try arena.dupe(u8, pane.cwdSlice()),
.stream = stream_text.items,
.stream_b64 = try dump.encodeBytes(arena, pane.tty_stream.items),
.cursor = .{
.col = pane.vt.screens.active.cursor.x,
.row = pane.vt.screens.active.cursor.y,
},
},
};
};
try panes.append(arena, dp);
}
var columns: std.ArrayList(dump.Column) = .empty;
for (0..p.ncol) |c| {
var ids: std.ArrayList(usize) = .empty;
for (0..p.col_n[c]) |k| {
if (slot_to_pane[p.col_terms[c][k]]) |compact| try ids.append(arena, compact);
}
if (ids.items.len > 0)
try columns.append(arena, .{ .weight = p.col_weight[c], .panes = ids.items });
}
const state: dump.State = .{
.screen = .{ .cols = p.screen_w, .rows = p.screen_h },
.active = slot_to_pane[p.active] orelse 0,
.topbar = config.topbar_str,
.theme = p.theme().name,
.columns = columns.items,
.panes = panes.items,
};
try dump.validate(state);
var out: std.Io.Writer.Allocating = .init(p.gpa);
errdefer out.deinit();
try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
if (p.dump_out) |d| p.gpa.free(d);
p.dump_out = try out.toOwnedSlice();
p.emit(.write_dump);
}
/// Initialize from another instance's dump: panes reconstructed (terminals
/// by replaying their raw VT streams into fresh emulators), no spawns —
/// loaded terminals are dead replays, scrollable and selectable.
pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8) !*Pardes {
const p = try gpa.create(Pardes);
p.* = .{ .gpa = gpa, .opts = opts, .screen_w = opts.cols, .screen_h = opts.rows, .scratch = .init(gpa) };
errdefer p.deinit();
const st = try dump.readZon(gpa, zon_bytes, "load");
defer dump.free(gpa, st);
for (themes, 0..) |t, i| {
if (std.mem.eql(u8, t.name, st.theme)) p.theme_idx = i;
}
for (st.panes, 0..) |src, i| {
if (i >= MAX_PANES) break;
switch (src.kind) {
.terminal => {
const t = src.terminal.?;
const pane = try gpa.create(Pane);
pane.* = .{
.vt = try ghostty_vt.Terminal.init(gpa, .{
.cols = @max(1, src.cols),
.rows = @max(1, src.rows),
.max_scrollback = 16 * 1024 * 1024,
}),
.stream = undefined,
.gpa = gpa,
.cols = @max(1, src.cols),
.rows = @max(1, src.rows),
};
pane.stream = pane.vt.vtStream();
pane.stream.handler.effects.write_pty = term_pane.ptyReport;
pane.stream.handler.effects.device_attributes = term_pane.ptyDeviceAttrs;
p.panes[i] = pane;
if (t.stream_b64.len > 0) {
const bytes = try dump.decodeBytes(p.scratch.allocator(), t.stream_b64);
pane.tty_stream.appendSlice(gpa, bytes) catch {};
pane.stream.nextSlice(bytes);
pane.vt.screens.active.scroll(.active);
if (src.scroll > 0) pane.vt.screens.active.scroll(.{ .delta_row = -@as(isize, @intCast(src.scroll)) });
}
p.setCwd(i, t.cwd);
if (std.mem.startsWith(u8, src.tag, "TTY ")) pane.mode = .tty;
p.restoreTail(pane, src.tag);
},
.file => {
const f = src.file.?;
const content: []u8 = if (f.content_b64.len > 0)
try dump.decodeBytes(gpa, f.content_b64)
else
try gpa.dupe(u8, f.content);
errdefer gpa.free(content);
const path = try gpa.dupe(u8, f.path);
errdefer gpa.free(path);
const pane = try p.newDocPane(i);
// an unknown origin word is a dump from another build, not
// a reason to refuse the load: it comes back as a file
const out: ?output_pane.Output = if (output_pane.fromWord(f.origin)) |o| blk: {
var ov: output_pane.Output = .{ .from = o };
output_pane.setArg(&ov, f.origin_arg);
break :blk ov;
} else null;
pane.file = .{ .path = path, .content = content, .output = out, .scroll = src.scroll };
pane.cur_pinned = true;
pane.cur_row = @intCast(src.scroll);
pane.cols = @max(1, src.cols);
pane.rows = @max(1, src.rows);
// a restored file pane is watched like an opened one. Note
// its content is the DUMP's, which may already differ from
// disk; the shell stamps the watch from what it has, so the
// first external write reconciles the pane to disk and the
// dump's version lands one `u` away — which is the same
// bargain as any other external update.
if (out == null) p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true } });
p.restoreTail(pane, src.tag);
},
.image => restore_image: {
const im = src.image.?;
const raw: []u8 = if (im.bytes_b64.len > 0)
dump.decodeBytes(gpa, im.bytes_b64) catch &.{}
else
&.{};
if (comptime pdf_enabled) if (look.isPdfPath(im.path)) {
if (p.openPdfView(i, im.path, src.scroll + 1) catch null) |pane| {
if (raw.len > 0) gpa.free(raw);
pane.cols = @max(1, src.cols);
pane.rows = @max(1, src.rows);
break :restore_image;
}
// If the source path is unavailable, retain its bytes
// as an ordinary file rather than dropping the pane.
const path = try gpa.dupe(u8, im.path);
errdefer gpa.free(path);
const content = if (raw.len > 0) raw else try gpa.dupe(u8, "");
errdefer if (content.len > 0) gpa.free(content);
const pane = try p.newDocPane(i);
pane.file = .{ .path = path, .content = content };
pane.cur_pinned = true;
pane.cols = @max(1, src.cols);
pane.rows = @max(1, src.rows);
p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true } });
break :restore_image;
};
const path = try gpa.dupe(u8, im.path);
errdefer gpa.free(path);
const pane = try p.newDocPane(i);
pane.image = .{ .path = path, .raw = raw };
pane.cols = @max(1, src.cols);
pane.rows = @max(1, src.rows);
},
}
p.panes[i].?.vweight = src.vweight;
}
p.ncol = @min(st.columns.len, MAX_COLS);
for (st.columns[0..p.ncol], 0..) |col, c| {
p.col_weight[c] = col.weight;
p.col_n[c] = @min(col.panes.len, MAX_PANES);
for (col.panes[0..p.col_n[c]], 0..) |pid, k| p.col_terms[c][k] = pid;
}
p.active = @min(st.active, MAX_PANES - 1);
p.sync();
p.applyStartupConfig();
p.finishThemeInitialization();
p.sync();
return p;
}
/// Restore a custom tag tail from a saved tag: whatever follows the live
/// prefix, unless it is this build's default or either exact legacy
/// default from before New appeared in every pane. Legacy defaults upgrade
/// to the live default; genuinely edited tails remain byte-for-byte owned.
fn restoreTail(p: *Pardes, pane: *Pane, saved_tag: []const u8) void {
const pfx = p.tagPrefix(pane) catch return;
if (!std.mem.startsWith(u8, saved_tag, pfx)) return;
const rest = saved_tag[pfx.len..];
const legacy = if (pane.file) |f|
if (output_pane.fileTraits(f.output).saves) legacy_file_pane_tail else legacy_pane_tail
else
legacy_pane_tail;
if (std.mem.eql(u8, rest, curTail(pane)) or std.mem.eql(u8, rest, legacy)) return;
pane.tag_tail.appendSlice(p.gpa, rest) catch return;
pane.tag_init = true;
}
fn removePane(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
p.absorbVWeight(id);
p.layoutRemove(id);
p.deinitPane(pane);
p.panes[id] = null;
if (p.active == id) p.active = p.prevFocus(id) orelse {
p.quit = true;
p.emit(.quit);
return;
};
}
/// where focus falls when the active pane closes: the most recently
/// focused pane still alive (else any live one). Null = nothing left.
/// Walks the jump stack newest-first, so it answers exactly what it always
/// did — a pane's newest entry sits where the old MRU put the pane.
pub fn prevFocus(p: *Pardes, closing: usize) ?usize {
var i = p.njumps;
while (i > 0) {
i -= 1;
const id = p.jumps[i].pane;
if (id != closing and p.panes[id] != null) return id;
}
for (p.panes, 0..) |slot, k| {
if (slot != null and k != closing) return k;
}
return null;
}
/// THE PUSH RULE, and the only place it is written down.
///
/// A location is worth remembering when you cannot see it any more: focus
/// ended this update in a DIFFERENT pane, or more than a bodyful of rows
/// away in the same one. Anything closer is the cursor strolling, and the
/// current entry just follows it — so h/j/k/w/b never grow the list, while
/// a goto-line, a search hit, a goto-definition and every focus change do.
/// (Vim's rule is a hand-kept list of "jump commands"; this one asks the
/// question those commands are a proxy for, and needs no list.)
///
/// It is read HERE, once per update, and nowhere else: what a call site
/// does transiently is invisible, which is what keeps n/N over a results
/// buffer — which focuses each hit and comes straight back — from pushing
/// two entries per keystroke. That transparency is the whole reason the
/// rule lives in sync() rather than at the sites that move focus, which is
/// where the heuristics used to be scattered.
fn trackJump(p: *Pardes) void {
// dead entries first, in one compacting pass. A slot is reused, so the
// test is the SERIAL: an entry whose pane has been replaced names a
// pane that no longer exists, not the newcomer sitting in its slot.
var w: usize = 0;
var cur: usize = 0;
for (p.jumps[0..p.njumps], 0..) |j, i| {
if (i == p.jcur) cur = w; // survives -> lands at w; dies -> the next one does
const pane = p.panes[j.pane] orelse continue;
if (pane.serial != j.serial) continue;
p.jumps[w] = j;
w += 1;
}
p.njumps = w;
p.jcur = @min(cur, w -| 1);
const pane = p.panes[p.active] orelse return;
// An UNPINNED cursor belongs to the program on the other end of the
// pty, not to you, so such a pane is remembered as a place and not as
// a spot: line 0 is the "no line" focusPaneLine already understands,
// and going back there focuses the shell without dragging its view up
// to scrollback row 0. It also has no line to be FAR from, which is
// what keeps the first keypress in a shell (which pins the cursor
// wherever the prompt is) from reading as a jump.
const now: Loc = .{
.pane = @intCast(p.active),
.serial = pane.serial,
.line = if (pane.pdfPage()) |page| @intCast(page + 1) else if (pane.cur_pinned) @intCast(@max(0, pane.cur_row) + 1) else 0,
.col = if (pane.pdfPage() != null) 0 else if (pane.cur_pinned) @intCast(@max(0, pane.cur_col) + 1) else 0,
};
if (p.njumps > 0) {
const at = &p.jumps[p.jcur];
const body = @max(1, p.rects[p.active].h -| BOX_H);
const far = at.line != 0 and now.line != 0 and
@max(now.line, at.line) - @min(now.line, at.line) > body;
if (at.pane == now.pane and !far) {
at.* = now; // same visit; the entry IS where you are
return;
}
}
// a new jump made from the middle of the list drops everything ahead of
// it, the way vim's does: the future you did not take is not history.
if (p.njumps > 0) p.njumps = p.jcur + 1;
if (p.njumps == MAX_JUMPS) {
std.mem.copyForwards(Loc, p.jumps[0 .. MAX_JUMPS - 1], p.jumps[1..]);
p.njumps -= 1;
}
p.jumps[p.njumps] = now;
p.jcur = p.njumps;
p.njumps += 1;
}
/// Ctrl-o / Ctrl-i (the Back and Forward builtins): move the CURSOR into
/// the stack and go to what it names. Nothing is pushed and nothing is
/// dropped — walking history is not making it — and trackJump agrees,
/// because after the move the live spot IS `jumps[jcur]` again.
pub fn jumpBy(p: *Pardes, delta: i32) void {
const next = @as(i64, @intCast(p.jcur)) + delta;
if (p.njumps == 0 or next < 0 or next >= p.njumps) return;
p.jcur = @intCast(next);
const j = p.jumps[p.jcur];
p.focusPaneLine(j.pane, .{ .line = j.line, .col = j.col });
}
/// Recompute geometry, push grid-size changes to each emulator + pty, fire
/// deferred greetings. The mirror of the prototype's loop epilogue.
fn sync(p: *Pardes) void {
p.computeGeom();
p.trackJump();
for (&p.panes, 0..) |*slot, id| {
const pane = slot.* orelse continue;
if (pane.reply_len > 0) {
var off: u16 = 0;
while (off < pane.reply_len) {
const n = @min(pane.reply_len - off, 64);
p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(pane.reply[off .. off + n]) } });
off += n;
}
pane.reply_len = 0;
}
const r = p.rects[id];
const cols = @max(1, r.w -| config.GUTTER);
const rows = @max(1, r.h -| BOX_H); // the tag steals the top row
// a pane shrunk to just its tag keeps its last real grid: no
// pty/vt reflow while the body is hidden, so re-enlarging brings
// it back exactly as it was
if ((cols != pane.cols or rows != pane.rows) and r.h > BOX_H) {
// doc panes have no pty/emulator grid to reflow; just record
// the size so bodyText renders the right number of rows
if (pane.isTerminal()) {
pane.vt.resize(p.gpa, cols, rows) catch {};
p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } });
}
pane.cols = cols;
pane.rows = rows;
}
// greet a fresh shell with `ls` once it has its real size (after
// the first winsize) AND has drawn its first prompt (the pty has
// produced output — bash sourced the rc and readline owns echo, so
// the greeting echoes on an OSC 133-marked row and hides cleanly;
// earlier, the kernel would echo it onto an unmarked row).
if (pane.greet and pane.isTerminal() and p.resize_count > 0 and pane.tty_stream.items.len > 0) {
p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = pane.cols, .rows = pane.rows } });
p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from("ls\r") } });
pane.greet = false;
}
}
}
fn computeGeom(p: *Pardes) void {
if (p.ncol == 0) return;
var wsum: f32 = 0;
for (0..p.ncol) |c| wsum += p.col_weight[c];
if (wsum <= 0) wsum = 1;
var x: u16 = 0;
for (0..p.ncol) |c| {
const last = c + 1 == p.ncol;
const fw = @as(f32, @floatFromInt(p.screen_w)) * p.col_weight[c] / wsum;
const wroom = p.screen_w -| x; // same clamp as the rows below
const cw: u16 = if (last) wroom else @min(wroom, @max(1, @as(u16, @intFromFloat(@round(fw)))));
p.col_x[c] = x;
p.col_w[c] = cw;
var vsum: f32 = 0;
for (0..p.col_n[c]) |k| {
if (p.panes[p.col_terms[c][k]]) |pane| vsum += pane.vweight;
}
if (vsum <= 0) vsum = 1;
var y: u16 = TOPBAR_H;
const avail_h = p.screen_h -| TOPBAR_H;
for (0..p.col_n[c]) |k| {
const id = p.col_terms[c][k];
const pane = p.panes[id] orelse continue;
const lastk = k + 1 == p.col_n[c];
const fh = @as(f32, @floatFromInt(avail_h)) * pane.vweight / vsum;
// every pane wants at least one row, so a column with more
// panes than the window has rows would walk `y` off the bottom
// and hand renderPane a rect outside the surface (assert, then
// panic — shrink a window with a few stacked panes). Clamp to
// what is left: the panes past the edge get h = 0 and render
// nothing until the window grows back.
const room = p.screen_h -| y;
const ch: u16 = if (lastk) room else @min(room, @max(1, @as(u16, @intFromFloat(@round(fh)))));
p.rects[id] = .{ .x = x, .y = y, .w = cw, .h = ch };
y +|= ch;
}
x +|= cw;
}
}
pub fn theme(p: *const Pardes) *const Theme {
return &themes[p.theme_idx];
}
/// Displayed colors for anchored UI chrome. Unlike `theme()`, this may be
/// between themes while a live transition is active.
pub fn chromeTheme(p: *const Pardes) *const ChromeTheme {
return &p.chrome_animation.displayed;
}
pub fn themeAnimationActive(p: *const Pardes) bool {
return p.chrome_animation.isActive();
}
fn finishThemeInitialization(p: *Pardes) void {
p.chrome_animation.snap(ChromeTheme.fromTheme(p.theme()));
p.animate_theme_changes = true;
}
/// The sole live-session theme mutation path. Target colors change now;
/// anchored chrome retargets from its currently displayed palette. Only
/// PDFs whose pixels depend on target theme colors are marked stale, once;
/// untinted source rasters remain byte-for-byte resident.
pub fn setThemeIndex(p: *Pardes, index: usize) void {
if (index >= themes.len or index == p.theme_idx) return;
const target_chrome = ChromeTheme.fromTheme(&themes[index]);
if (p.animate_theme_changes)
p.chrome_animation.retarget(target_chrome)
else
p.chrome_animation.snap(target_chrome);
p.theme_idx = index;
if (comptime pdf_enabled) for (p.panes) |slot| {
const pane = slot orelse continue;
const pv = &(pane.pdf orelse continue);
if (pv.tint != .disabled) p.invalidateAllPdfRasters(pv);
};
}
// ---- render: build the canonical surface ----
pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface {
file_pane.refreshHighlights(p);
const s = &p.surface;
const ncells = @as(usize, p.screen_w) * p.screen_h;
if (s.cells.len != ncells) {
p.gpa.free(s.cells);
s.cells = try p.gpa.alloc(Cell, ncells);
}
s.cols = p.screen_w;
s.rows = p.screen_h;
s.cursor = null;
s.nimages = 0;
const chrome = p.chromeTheme();
// gaps between panes read as chrome (scrollbar track), not raw default
s.fill(0, 0, s.cols, s.rows, .{ .bg = .{ .rgb = chrome.scroll_track } });
for (&p.panes, 0..) |*slot, id| {
const pane = slot.* orelse continue;
try p.renderPane(arena, pane, p.rects[id], id == p.active);
}
// ---- the transient message row: a pane's LAST row, left-aligned ----
//
// An OVERLAY, not geometry: no rect moves, no pane shrinks, and a pane
// with neither a message nor an armed prompt is not touched at all.
// Drawn after every pane's body so it lands OVER whatever that row was
// showing, and painted in the tag bar's own colours — it is the
// tagline's twin at the other end of the pane, and reading as chrome is
// what keeps it from being mistaken for content. Out here rather than
// at the end of renderPane because renderPane returns early for a
// native PDF page and for an image, and a `/` on a PDF is a real search
// whose prompt has to be visible like any other.
//
// Exactly two things can occupy the row and an ARMED PROMPT beats a
// MESSAGE, because they are not the same kind of thing: a message is a
// report of what already happened and the next keystroke wipes it, a
// prompt is what that keystroke is being typed into and it lives until
// Enter or Esc.
//
// ponytail: the row is draw-only. A click on it lands wherever the body
// under it says (tag clicks map to tag_col on the TAG row), so a prompt
// that moved down here cannot be clicked into or swept the way one on
// the tagline could — the keyboard still edits it in full. Upgrade path
// is a hit test here that maps a press on this row to tag_col + the
// marker offset, i.e. the tag row's own mapping with a constant added.
for (&p.panes, 0..) |*slot, id| {
const pane = slot.* orelse continue;
const r = p.rects[id];
// no body row (a one-row pane, or one squeezed out entirely): the
// tag row is not ours to overwrite, so the message just waits
if (r.w <= config.GUTTER or r.h <= BOX_H) continue;
// the same one input model renderPane cut off the tagline; only one
// of the two can ever be armed (a body key arms one, exitTagEdit
// clears both)
const prompt_at: ?u16 = if (pane.search_edit) pane.search_at else if (pane.pipe_edit) pane.pipe_at else null;
const text = if (prompt_at) |at|
pane.tag_tail.items[@min(at, pane.tag_tail.items.len)..]
else
pane.msg[0..pane.msg_len];
if (text.len == 0) continue;
const tx = r.x + config.GUTTER;
const tw = r.w - config.GUTTER;
const row = r.y + r.h - 1;
// the WHOLE row, the way the tagline fills its own before printing:
// a message is a section and not a stamp, and print writes only the
// cells it needs — so without the fill the body row shows through
// to the right of a short message and reads as one garbled line.
s.fill(tx, row, tw, 1, .{ .bg = .{ .rgb = chrome.tag_bg } });
_ = s.print(tx, row, tw, text, .{ .fg = .{ .rgb = chrome.tag_fg }, .bg = .{ .rgb = chrome.tag_bg } });
// ...and the cursor follows the text it edits. tag_col is a
// rendered-tag column, so the prompt's own column is it minus where
// the marker starts; a cursor LEFT of that is still over the part
// of the tag that stayed on the tagline, and the tag cursor
// renderPane already placed there is the right one.
if (id != p.active) continue;
const at = prompt_at orelse continue;
const prompt0 = (p.tagPrefix(pane) catch continue).len + at;
const col = @as(usize, pane.tag_col);
if (col >= prompt0 and col - prompt0 < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(col - prompt0)), .y = row, .bar = pane.mode == .insert };
}
// global tagbar: full width, top row
s.fill(0, 0, s.cols, TOPBAR_H, .{ .bg = .{ .rgb = chrome.tag_bg } });
var tb_buf: [1200]u8 = undefined;
_ = s.print(0, 0, s.cols, p.topbar(&tb_buf), .{ .fg = .{ .rgb = chrome.tag_fg }, .bg = .{ .rgb = chrome.tag_bg } });
// the topbar's cursor, if it has the keyboard. AFTER the pane loop on
// purpose: there is exactly one Surface cursor and the bar's must beat
// the active pane's. Always a block — the bar has no insert mode.
if (p.topbar_col) |c| if (c < s.cols) {
s.cursor = .{ .x = c, .y = 0, .bar = false };
};
// resize-handle hint / drag previews: a dash overlay that keeps the
// underlying colors (border drags + hover), or the move indicator. A
// drag holds the coordinates of the last mouse event, so a resize
// mid-drag (tiling WM, font-size change) can leave them off the new
// surface — every arm below checks before it draws.
switch (p.drag) {
.border_v => |d| {
if (d.cur_x < s.cols) {
var row: u16 = TOPBAR_H;
while (row < s.rows) : (row += 1) s.overlayDash(d.cur_x, row, "╎");
}
// a corner lights BOTH splits, which is the whole tell that you
// grabbed the crossing and not an edge. The horizontal half
// stops at the vertical preview rather than at the column's
// current right edge, so the two dashes stay joined at the cell
// under the mouse and together show the shape being committed.
if (d.corner_idx != null and d.cur_y < s.rows) {
var col = p.col_x[d.left_col];
while (col <= d.cur_x and col < s.cols) : (col += 1) s.overlayDash(col, d.cur_y, "╌");
}
},
.border_h => |d| if (d.cur_y < s.rows) {
var col = p.col_x[d.col];
while (col < p.col_x[d.col] + p.col_w[d.col]) : (col += 1) s.overlayDash(col, d.cur_y, "╌");
},
.move => |d| if (d.cur_x < s.cols) {
if (p.movePlacement(d.id, d.cur_x, d.cur_y)) |placement| {
var col: u16 = p.col_x[placement.preview_col];
while (col < p.col_x[placement.preview_col] + p.col_w[placement.preview_col]) : (col += 1) {
s.set(col, placement.row, "╌", .{ .fg = .{ .rgb = chrome.lineno } });
}
s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } });
}
},
.none, .select, .tag => {
// hover hints on a pane's own trailing edge
var c: usize = 0;
while (c + 1 < p.ncol) : (c += 1) {
if (p.hover_col == p.col_x[c] + p.col_w[c] -| 1) {
var row: u16 = TOPBAR_H;
while (row < s.rows) : (row += 1) s.overlayDash(p.hover_col, row, "╎");
}
}
for (0..p.ncol) |cc| {
if (p.hover_col < p.col_x[cc] or p.hover_col >= p.col_x[cc] + p.col_w[cc]) continue;
for (0..p.col_n[cc] -| 1) |k| {
const r = p.rects[p.col_terms[cc][k]];
if (p.hover_row == r.y + r.h -| 1) {
var col = p.col_x[cc];
while (col < p.col_x[cc] + p.col_w[cc]) : (col += 1) s.overlayDash(col, p.hover_row, "╌");
}
}
}
},
}
// debug overlay: a small stats box drawn last, top-right ("Debug")
if (p.show_debug) if (p.panes[p.active]) |at| {
var nlive: usize = 0;
for (p.panes) |slot| {
if (slot != null) nlive += 1;
}
var sb_off: usize = undefined;
var sb_total: usize = undefined;
if (at.file) |*f| {
sb_off = f.scroll;
sb_total = file_pane.nlines(p.gpa, f);
} else if (at.pdfPage()) |page| {
sb_off = page;
sb_total = if (comptime pdf_enabled) at.pdf.?.page_count else 0;
} else {
const sb = at.vt.screens.active.pages.scrollbar();
sb_off = sb.offset;
sb_total = sb.total;
}
var ov_buf: [192]u8 = undefined;
const text = std.fmt.bufPrint(
&ov_buf,
"pardes resizes={d}\nterms {d} cols {d}\nactive #{d} {d}x{d}\nscroll {d}/{d}\npinch {d:6.4}\ntscroll {d:7.4}",
.{ p.resize_count, nlive, p.ncol, p.active, at.cols, at.rows, sb_off, sb_total, p.ov_pinch_scale, p.ov_touch_scroll_delta },
) catch "";
const ow: u16 = 30;
const oh: u16 = 8;
const ox: u16 = if (s.cols > ow) s.cols - ow else 0;
if (ox + ow <= s.cols and TOPBAR_H + oh <= s.rows) {
// vaxis single_rounded border ring, default style
s.set(ox, TOPBAR_H, "╭", .{});
s.set(ox + ow - 1, TOPBAR_H, "╮", .{});
s.set(ox, TOPBAR_H + oh - 1, "╰", .{});
s.set(ox + ow - 1, TOPBAR_H + oh - 1, "╯", .{});
var bx = ox + 1;
while (bx < ox + ow - 1) : (bx += 1) {
s.set(bx, TOPBAR_H, "─", .{});
s.set(bx, TOPBAR_H + oh - 1, "─", .{});
}
var by = TOPBAR_H + 1;
while (by < TOPBAR_H + oh - 1) : (by += 1) {
s.set(ox, by, "│", .{});
s.set(ox + ow - 1, by, "│", .{});
}
s.fill(ox + 1, TOPBAR_H + 1, ow - 2, oh - 2, .{ .bg = .{ .rgb = chrome.scroll_track } });
var lines = std.mem.splitScalar(u8, text, '\n');
var ly: u16 = TOPBAR_H + 1;
while (lines.next()) |line| : (ly += 1) {
if (ly >= TOPBAR_H + oh - 1) break;
_ = s.print(ox + 1, ly, ow - 2, line, .{ .fg = .{ .rgb = chrome.tag_fg } });
}
}
};
return s;
}
fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, active: bool) !void {
const tz = tracy.zone(@src(), "renderPane");
defer tz.end();
if (r.w <= config.GUTTER or r.h == 0) return;
const s = &p.surface;
const th = p.theme();
const chrome = p.chromeTheme();
const tx = r.x + config.GUTTER; // text area (tag + body), right of the gutter
const tw = r.w - config.GUTTER;
// the pane's own background, for everything that has to read as "no
// chrome here": the body text, and the blank right half of the
// scrollbar's second column. `.default` means the host terminal's own
// background, which is what a themeless dark pane wants.
const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default;
// ...and the same background as a colour to do arithmetic on, which the
// dimmed selections below need. A theme with a null bg cannot say what
// the host's own cell looks like, so its tag bar stands in — the
// substitution pdfTintColors already makes.
const page_rgb = th.bg orelse th.tag_bg;
// text area resets to terminal-default cells (vaxis clear semantics);
// light themes paint the page over it.
s.clearRect(tx, r.y, tw, r.h);
if (th.bg) |bg| s.fill(tx, r.y, tw, r.h, .{ .bg = .{ .rgb = bg } });
// the layout box: the pane's MODE, one character, in the gutter cells
// of the tag row. Same box you drag a pane by — the whole GUTTER is
// still painted and the `.move` press hit-test in handleMouse is
// untouched — it just carries the one piece of state that used to cost
// four columns of every tagline.
// The glyph goes in column 0, directly above the scrollbar's ink
// column below it, so a pane's chrome reads as one line down its left
// edge; column 1 stays plain colour, and that blank half is what keeps
// the thing reading as a BOX rather than as a letter someone dropped
// in the gutter.
//
// The mode shown is the BODY's. A tag edit hijacks pane.mode to insert
// (tags are always insert; the real one is parked in tag_mode), and a
// badge that flipped every time you clicked a tagline would be
// reporting the tag's mode on the pane's box. Reading tag_mode also
// makes the parked value VISIBLE: a terminal being tag-edited still
// shows `$`, which is exactly the invariant ttyclick.snap exists for.
//
// The ink is picked off the box's own brightness instead of being
// named in the theme, because box/box_dim come from a generated
// theme's cursor and selection colours — light on a light theme — and
// a fixed white would vanish there. Rec.601-ish integer weights.
// ponytail: two colours, black or white, chosen at a fixed threshold.
// Upgrade to the theme's own fg/bg pair when a theme turns up whose
// box wants a tint rather than a contrast.
const box_bg = if (active) chrome.box else chrome.box_dim;
const box_lum = (@as(u16, box_bg[0]) * 3 + @as(u16, box_bg[1]) * 6 + @as(u16, box_bg[2])) / 10;
const box_ink: [3]u8 = if (box_lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff };
const box_style: CellStyle = .{ .fg = .{ .rgb = box_ink }, .bg = .{ .rgb = box_bg } };
s.fill(r.x, r.y, config.GUTTER, BOX_H, box_style);
const box_mode = if (pane.tag_edit) pane.tag_mode else pane.mode;
s.set(r.x, r.y, switch (box_mode) {
.normal => config.tag_normal,
.insert => config.tag_insert,
.tty => config.tag_tty,
}, box_style);
// tag: live prefix (cwd/path) + editable tail, on a dim bar
const tag_style: CellStyle = .{ .fg = .{ .rgb = chrome.tag_fg }, .bg = .{ .rgb = chrome.tag_bg } };
s.fill(tx, r.y, tw, BOX_H, .{ .bg = .{ .rgb = chrome.tag_bg } });
const tag = try p.tagText(arena, pane);
// An armed input — `/`, Find, Grep, Rename, WsSymbols, Select/Split,
// `|` — is still TYPED INTO the tag tail: same buffer, same offsets,
// same one-line modal editor, same Enter and same Esc. Only where it is
// DRAWN moved. It is cut off the tagline here and printed on the pane's
// message row instead (see render), so the builtins in the tail stay
// readable while you type instead of being pushed off the right edge by
// a long pattern.
//
// search_at/pipe_at are TAIL offsets and tag_col is a rendered-tag
// column, so the cut is the offset plus the prefix the tail is missing
// — which is what tag.len - tail.len is, without formatting the prefix
// a second time.
const prompt_at: ?u16 = if (pane.search_edit) pane.search_at else if (pane.pipe_edit) pane.pipe_at else null;
const tag_cut = if (prompt_at) |at|
@min(tag.len, tag.len - @min(tag.len, pane.tag_tail.items.len) + at)
else
tag.len;
_ = s.print(tx, r.y, tw, tag[0..tag_cut], tag_style);
// pending SPC leader path, on the ACTIVE pane's tag at its RIGHT edge:
// the same rule as the `/` input — state you can see, nothing that
// disappears — but right-aligned, so it never collides with the
// builtins in the tail. Printed AFTER the tag, so a tag long enough to
// reach it loses its last columns instead: what you are about to press
// beats the path, which is still readable in the prefix.
if (active and p.leader_on) {
var ibuf: [16]u8 = @splat(' ');
@memcpy(ibuf[1..4], "SPC");
var iw: usize = 4;
for (p.leader_keys[0..p.leader_n]) |ch| {
ibuf[iw + 1] = ch;
iw += 2;
}
const w: u16 = @intCast(iw);
if (w < tw) _ = s.print(tx + tw - w, r.y, w, ibuf[0..iw], tag_style);
}
// tag char selection highlight (helix v/x, or a tagline sweep),
// inclusive [lo, hi] — rendered-tag columns, so no conversion.
//
// Every selection on screen paints in the LIVE theme (`th`) and not in
// `chrome`: a highlight is not attached to any geometry, it appears
// under the range you just swept, so it has to arrive with the theme
// the way syntax colours do rather than slide in over the chrome
// animation's frames.
if (pane.tag_edit and pane.tag_sel) {
const b = tagSelBounds(pane);
var col: usize = b.lo;
const end: usize = b.hi;
while (col <= end and col < tw) : (col += 1) {
const cell = s.at(tx + @as(u16, @intCast(col)), r.y);
cell.default = false;
cell.style.bg = .{ .rgb = th.sel_bg };
cell.style.fg = .{ .rgb = th.sel_fg };
}
}
// cursor while editing the tag: a rendered-tag column, verbatim
if (active and pane.tag_edit) {
// bar while typing, block for `:` normal mode (same rule as a body)
if (pane.tag_col < tw) s.cursor = .{ .x = tx + pane.tag_col, .y = r.y, .bar = pane.mode == .insert };
}
// A native PDF page uses the same backend-neutral pixel attachment as
// an image. Without native pixels it deliberately falls through: its
// extracted text projection becomes an ordinary readable body.
if (comptime pdf_enabled) {
if (hasPdf(pane) and p.native_images and p.drawPdf(pane, r, tx, tw)) {
s.fill(r.x, r.y + BOX_H, 1, r.h -| BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } });
s.fill(r.x + 1, r.y + BOX_H, 1, r.h -| BOX_H, .{ .bg = pane_bg });
if (r.h > BOX_H) {
const pv = &pane.pdf.?;
const track_h: usize = r.h - BOX_H;
const viewport = p.pdfViewport(pane).?;
const total = @max(@as(u64, 1), pv.document_height);
const len = @max(
@as(usize, 1),
@as(usize, @intCast(@min(
@as(u64, track_h),
@as(u64, track_h) * viewport.pixel_h / total,
))),
);
const offset: u64 = @intFromFloat(@floor(pv.document_scroll_y));
const pos: usize = @intCast(@min(
@as(u64, track_h -| 1),
@as(u64, track_h) * offset / total,
));
var sy = pos;
while (sy < track_h and sy < pos + len) : (sy += 1)
s.fill(r.x, r.y + BOX_H + @as(u16, @intCast(sy)), 1, 1, .{ .bg = .{ .rgb = chrome.scroll_thumb } });
}
return;
}
}
// image pane: the picture fills the body — petscii glyph art into the
// cells, or a pixel attachment the shell places (kitty). Plain
// thumbless gutter so it reads like any other pane.
if (pane.image != null) {
p.drawImage(pane, r, tx, tw);
// thumbless, but the same one column as the real scrollbar below —
// that is the whole point of drawing it
s.fill(r.x, r.y + BOX_H, 1, r.h -| BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } });
s.fill(r.x + 1, r.y + BOX_H, 1, r.h -| BOX_H, .{ .bg = pane_bg });
return;
}
// body: emulator rows, prompt rows hidden outside tty mode
const body_h = if (r.h > BOX_H) r.h - BOX_H else 0;
const body_style: CellStyle = .{
.fg = if (th.fg) |c| .{ .rgb = c } else .default,
.bg = pane_bg,
};
const tz_body = tracy.zone(@src(), "bodyText");
const body = try p.bodyText(arena, pane);
tz_body.end();
var it = std.mem.splitScalar(u8, body, '\n');
var i: u16 = 0;
while (it.next()) |line| : (i += 1) {
if (i >= body_h) break;
_ = s.print(tx, r.y + BOX_H + i, tw, line, body_style);
}
// the two file-only passes and the terminal-only one: each is the
// whole reason its pane kind renders differently at all, so each lives
// with its kind. Order is load-bearing — gutter, then syntax over the
// content, then the emulator's own colors — and the selection/cursor
// passes below still win over all three.
if (pane.file) |*f| {
file_pane.drawGutter(p, pane, r, tx, tw, body_h, active);
if (p.colors_on) file_pane.recolorSyntax(p, pane, f, r, tx, tw, body_h);
}
const off = pane.scroll();
if (p.colors_on and pane.isTerminal()) term_pane.recolorAnsi(p, pane, r, tx, tw, body_h, off);
// mouse selections (pane-local coords), one pass per button — later
// buttons win on overlap. A left .done stays highlighted after release;
// middle/right .done are transient (they fire their action on release).
//
// Which button drew a sweep is worth seeing, so each gets the theme's
// selection tinted toward one of the theme's own syntax accents: three
// colours that are visibly not each other on a dark theme and on a
// light one, without asking a theme to name three more. A QUARTER of
// the accent, which is the mix of a mix — at a half, an accent as
// bright as the theme's text lands on top of sel_fg and the selected
// text stops being readable on a couple of dozen generated themes.
// `num` gives way to `comment` when a theme paints numbers and strings
// alike — the shipped helix theme does, 24 of the generated ones do —
// because two buttons landing on one colour is the whole thing this
// avoids.
// ponytail: 20 of the 228 themes colour two of these three scopes the
// same anyway and still collapse two buttons. Upgrade path is to walk
// the theme for a third colour far enough from the other two, rather
// than naming the scopes here.
const accent2 = if (std.mem.eql(u8, &th.num, &th.str)) th.comment else th.num;
const sel_btn = [3][3]u8{
mix(th.sel_bg, mix(th.sel_bg, th.kw)),
mix(th.sel_bg, mix(th.sel_bg, th.str)),
mix(th.sel_bg, mix(th.sel_bg, accent2)),
};
for (pane.sel, 0..) |sl, b| {
if (sl.state == .none) continue;
if (sl.state == .done and b != 0) continue;
const r0 = @min(sl.r0, sl.r1);
const r1 = @max(sl.r0, sl.r1);
const c0 = @max(0, @min(sl.c0, sl.c1));
const c1 = @max(0, @max(sl.c0, sl.c1));
var row: u16 = 0;
while (row < r.h) : (row += 1) {
if (@as(i32, row) < r0 or @as(i32, row) > r1) continue;
var col: i32 = if (pane.file != null) @max(c0, @as(i32, config.PREFIX_W)) else c0;
while (col <= c1 and col < tw) : (col += 1) {
const cell = s.at(tx + @as(u16, @intCast(col)), r.y + row);
cell.default = false;
cell.style.bg = .{ .rgb = sel_btn[b] };
cell.style.fg = .{ .rgb = th.sel_fg };
}
}
}
// modal line selection (helix `x`): whole body rows, normal mode only
if (pane.mode == .normal and pane.msel.active) {
const lo = @min(pane.msel.r0, pane.msel.r1);
const hi = @max(pane.msel.r0, pane.msel.r1);
var row: u16 = BOX_H; // never paint the tag row
while (row < r.h) : (row += 1) {
// walked by SCREEN row and asked what LINE each one shows,
// because a wrapped line is several rows. wrapAt degenerates to
// `off + row` when nothing wrapped, which is what this was.
const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line;
if (ar < lo or ar > hi) continue;
var col: u16 = if (pane.file != null) config.PREFIX_W else 0;
while (col < tw) : (col += 1) {
const cell = s.at(tx + col, r.y + row);
cell.default = false;
cell.style.bg = .{ .rgb = th.sel_bg };
cell.style.fg = .{ .rgb = th.sel_fg };
}
}
}
// modal char selection (helix `v`): stream-shaped anchor..head
// highlight. The EXTRA cursors are the same shape drawn dimmer, and
// each of them also paints its own cursor cell bright: there is one
// hardware cursor and the primary owns it, so a secondary cursor has
// to be a cell colour or it is invisible.
// The extra cursors show in INSERT mode too — that is exactly when you
// need to see where your typing is landing — while the primary's
// selection highlight stays normal-mode-only, as it always was.
// ...and an armed `s`/`S` shows the primary WHATEVER shape it is, even
// though the pane is in insert mode for the tag and even when the match
// is a single cell: the hardware cursor is off in the tag, so a preview
// that leans on it shows every match except the one you are on.
const preview = selRegexArmed(pane) != null;
const show_prim = (pane.mode == .normal and pane.vsel.active) or preview;
const show_extra = pane.mode != .tty and pane.nsel > 0;
if (show_prim or show_extra) {
const vpfx: i32 = if (pane.file != null) config.PREFIX_W else 0;
var si: usize = 0;
while (si <= pane.nsel) : (si += 1) {
const primary = si == pane.nsel;
if (if (primary) !show_prim else !show_extra) continue;
const sr = if (primary) SelRange{
.row = pane.cur_row,
.col = pane.cur_col,
.arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row,
.acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col,
} else pane.sels[si];
const bnd = cellBounds(sr);
// an extra cursor is the selection colour turned down: the
// highlight pulled halfway back to the page, so the primary is
// the one that reads as "here" at a glance. On a light theme
// that dims toward white rather than toward black, which is the
// same statement. The INK stays put — helix's two selection
// styles differ in their background too, and dimming both ends
// walks the text and its cell toward each other until neither
// is readable on the themes whose selection is already close to
// the page.
const bg = if (primary) th.sel_bg else mix(th.sel_bg, page_rgb);
// ...and this walks SCREEN rows too, asking the map which line
// and which byte column of it each one shows. Unwrapped that is
// `off + vr` / `hscroll`, i.e. the arithmetic this was, and it
// is also the cheaper loop: a linewise selection over a whole
// file used to iterate once per LINE to reject all but a
// screenful of them.
var vr: i32 = 0;
while (vr + @as(i32, BOX_H) < @as(i32, r.h)) : (vr += 1) {
const w = pane.wrapAt(vr);
if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue;
const prow = vr + @as(i32, BOX_H);
const cstart: i32 = if (w.line == bnd.lo_row) bnd.lo_col - w.at + vpfx else vpfx;
const cend: i32 = if (w.line == bnd.hi_row) bnd.hi_col - w.at + vpfx else @as(i32, tw) - 1;
var col: i32 = @max(cstart, vpfx);
while (col <= cend and col < tw) : (col += 1) {
const cell = s.at(tx + @as(u16, @intCast(col)), r.y + @as(u16, @intCast(prow)));
cell.default = false;
cell.style.bg = .{ .rgb = bg };
cell.style.fg = .{ .rgb = th.sel_fg };
}
}
if (primary and !preview) continue; // the hardware cursor IS the primary's
const cw = pane.wrapRow(sr.row, sr.col);
const crow = cw.row + @as(i32, BOX_H);
const ccol = sr.col - cw.at + vpfx;
if (crow >= BOX_H and crow < @as(i32, r.h) and ccol >= vpfx and ccol < tw) {
const cell = s.at(tx + @as(u16, @intCast(ccol)), r.y + @as(u16, @intCast(crow)));
cell.default = false;
cell.style.bg = .{ .rgb = th.sel_fg };
cell.style.fg = .{ .rgb = th.sel_bg };
}
}
}
// cursor: tracks the shell cursor until pinned by a click or a key
// (the tag cursor above wins while the tag is focused)
if (active and !pane.tag_edit) {
const cur = pane.vt.screens.active.cursor;
if (pane.mode != .tty) {
const goff: i32 = @intCast(pane.vt.screens.active.pages.scrollbar().offset);
const crow = if (pane.cur_pinned) pane.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff);
const ccol = if (pane.cur_pinned) pane.cur_col else @as(i32, @intCast(cur.x));
// which ROW of a wrapped line the cursor is on, and which byte
// column that row starts at — `off`/`hscroll` when nothing
// wrapped, so this is the same two lines it always was
const cwp = pane.wrapRow(crow, ccol);
const prow = cwp.row + @as(i32, BOX_H);
// files: cur_col is content-relative, add the lineno prefix
const cx = if (pane.file != null)
@as(i32, config.PREFIX_W) + ccol - cwp.at
else
ccol;
if (prow >= BOX_H and cx >= 0 and prow < r.h and cx < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = r.y + @as(u16, @intCast(prow)), .bar = pane.mode == .insert };
} else if (cur.y + BOX_H < r.h and cur.x < tw) {
s.cursor = .{ .x = tx + cur.x, .y = r.y + cur.y + BOX_H, .bar = pane.mode == .insert };
}
}
// gutter below the tag row: scrollbar track + thumb. (The move box on
// the tag row itself is drawn up with the tag, since it now carries
// the mode and belongs with the rest of that row.)
//
// The bar is ONE column: column 1 is the track/thumb, column 2 is the
// pane's own background. That second fill is not optional — render()
// pre-fills the whole surface with scroll_track so the gaps between
// panes read as chrome, so a column left unpainted here keeps the
// track colour and the bar looks two wide again.
//
// The move box above stays the full GUTTER even though only half of it
// has ink in it. It is a target you drag, not a gauge you read, and its
// whole width is the affordance — the step where the box ends and the
// narrower bar begins is the one place on screen that says those are
// two different pieces of chrome.
//
// Nothing here touches layout or hit-testing: the gutter is still
// config.GUTTER columns and the click handlers still scroll on any of
// them, so the blank column is still live. Only the ink narrowed.
if (r.h > BOX_H) {
s.fill(r.x, r.y + BOX_H, 1, r.h - BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } });
s.fill(r.x + 1, r.y + BOX_H, 1, r.h - BOX_H, .{ .bg = pane_bg });
const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{
.total = file_pane.nlines(p.gpa, f),
.offset = f.scroll,
.len = pane.rows,
} else if (pane.pdfPage()) |page| .{
.total = if (comptime pdf_enabled) pane.pdf.?.page_count else 1,
.offset = page,
.len = 1,
} else blk: {
const gsb = pane.vt.screens.active.pages.scrollbar();
break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len };
};
const track_h: usize = r.h - BOX_H;
const total = if (sb.total == 0) 1 else sb.total;
const len = @max(1, (track_h * @max(1, sb.len)) / total);
const pos = (track_h * sb.offset) / total;
var sy: usize = pos;
while (sy < track_h and sy < pos + len) : (sy += 1) {
s.fill(r.x, r.y + BOX_H + @as(u16, @intCast(sy)), 1, 1, .{ .bg = .{ .rgb = chrome.scroll_thumb } });
}
}
}
fn appendImagePlace(p: *Pardes, place: ImagePlace) bool {
const s = &p.surface;
if (s.nimages == s.images.len) {
const old_len = s.images.len;
const new_len = @max(@as(usize, 4), std.math.mul(usize, @max(old_len, 1), 2) catch return false);
const grown = if (old_len == 0)
p.gpa.alloc(?ImagePlace, new_len) catch return false
else
p.gpa.realloc(s.images, new_len) catch return false;
@memset(grown[old_len..], null);
s.images = grown;
}
s.images[s.nimages] = place;
s.nimages += 1;
return true;
}
fn pdfVisibleContains(visible: PdfVisiblePages, page: usize) bool {
return page >= visible.first and page - visible.first < visible.len;
}
fn reconcilePdfRasters(
p: *Pardes,
pv: *PdfView,
request: pdf_impl.RenderRequest,
highlights: []const PdfHighlight,
visible: PdfVisiblePages,
) void {
if (comptime !pdf_enabled) return;
const tint_key = p.pdfTintKey(pv);
// Remove first: owned RGBA never accumulates with document length,
// and backends see stale keys disappear in this same frame.
var index: usize = 0;
while (index < pv.rasters.items.len) {
if (pdfVisibleContains(visible, pv.rasters.items[index].page)) {
index += 1;
continue;
}
p.releasePdfRaster(&pv.rasters.items[index]);
_ = pv.rasters.swapRemove(index);
}
var page = visible.first;
const end = visible.first + visible.len;
while (page < end) : (page += 1) {
var raster = pdfRasterForPage(pv, page);
if (raster == null) {
pv.rasters.append(p.gpa, .{ .valid = true, .page = page }) catch continue;
raster = &pv.rasters.items[pv.rasters.items.len - 1];
}
const slot = raster.?;
const decorated = page == pv.page and highlights.len > 0;
if (!slot.tried or !slot.request_valid or !slot.request.eql(request) or
slot.decorated != decorated or slot.tint_key == null or
!slot.tint_key.?.eql(tint_key))
{
slot.tried = true;
slot.request = request;
slot.request_valid = true;
const rendered = render: {
const fresh = if (decorated)
pv.document.renderWithHighlightsAt(p.gpa, page, request, highlights) catch break :render null
else
pv.document.renderAt(p.gpa, page, request) catch break :render null;
break :render fresh;
};
if (rendered) |fresh| {
pdf_impl.tintRgba(fresh.rgba, tint_key.mode, tint_key.colors) catch {
p.gpa.free(fresh.rgba);
continue;
};
if (slot.rgba.len > 0) p.gpa.free(slot.rgba);
slot.rgba = fresh.rgba;
slot.iw = fresh.width;
slot.ih = fresh.height;
slot.decorated = decorated;
slot.tint_key = tint_key;
pv.next_raster_revision +%= 1;
if (pv.next_raster_revision == 0) pv.next_raster_revision = 1;
slot.revision = pv.next_raster_revision;
}
}
if (page == pv.page and slot.rgba.len > 0) syncPdfRasterAliases(pv, slot);
}
}
/// Attach every page intersecting the document viewport. Raster entries
/// are released as soon as their page leaves that exact visible set;
/// scrolling a retained page changes geometry only.
fn drawPdf(p: *Pardes, pane: *Pane, r: Rect, tx: u16, tw: u16) bool {
if (comptime !pdf_enabled) return false;
const pv = &(pane.pdf orelse return false);
if (r.h <= BOX_H) return false;
const viewport = p.ensurePdfLayout(pane, pv) orelse return false;
const request = p.pdfRenderRequest(pane) orelse return false;
p.resolvePdfSearch(pv);
const highlights = p.pdfHighlights(pv) catch &.{};
var visible = pdfVisiblePages(pv, viewport);
p.reconcilePdfRasters(pv, request, highlights, visible);
p.rearmPdfRevealForViewport(pane, pv);
p.revealPdfSearch(pane, pv);
// Reveal can move within the current page; placements below use its
// final document coordinate, but unchanged raster pixels are reused.
visible = pdfVisiblePages(pv, viewport);
p.reconcilePdfRasters(pv, request, highlights, visible);
const id: u8 = @intCast(for (p.panes, 0..) |slot, i| {
if (slot == pane) break i;
} else 0);
var placed_any = false;
var page = visible.first;
const visible_end = visible.first + visible.len;
while (page < visible_end) : (page += 1) {
const slot = pdfRasterForPage(pv, page) orelse continue;
if (slot.rgba.len == 0) continue;
const placed = pdfPlacedGeometry(pv, slot, viewport, page) orelse continue;
if (!p.appendImagePlace(.{
.pane = id,
.serial = pane.serial,
.native = .{
.revision = slot.revision,
.page = @intCast(page),
.fit = switch (pv.fit) {
.width => .width,
.height => .height,
},
.pan_x = pv.pan_x,
.geometry = placed.geometry,
.pixel_offset_y = placed.pixel_offset_y,
},
.x = tx,
.y = r.y + BOX_H,
.w = tw,
.h = r.h - BOX_H,
.rgba = slot.rgba,
.iw = slot.iw,
.ih = slot.ih,
})) break;
placed_any = true;
}
return placed_any;
}
/// Image pane body: decode once (path via look, or dump-loaded raw bytes),
/// rebuild the petscii grid when the size/toggles changed, then either
/// blit the glyph art into cells or attach the pixels for the shell.
fn drawImage(p: *Pardes, pane: *Pane, r: Rect, tx: u16, tw: u16) void {
const iv = &pane.image.?;
const s = &p.surface;
if (!iv.tried) {
iv.tried = true;
const bytes: []const u8 = if (iv.raw.len > 0) iv.raw else (look.readFile(p.scratch.allocator(), iv.path) catch "");
if (image.decode(p.gpa, bytes)) |d| {
iv.rgba = d.rgba;
iv.iw = d.w;
iv.ih = d.h;
}
}
if (iv.rgba.len == 0 or r.h <= BOX_H) return;
const body_cols = tw;
const body_rows = r.h - BOX_H;
const use_petscii = iv.petscii or !p.native_images;
if (!use_petscii) {
if (!p.appendImagePlace(.{
.pane = @intCast(for (p.panes, 0..) |slot, i| {
if (slot == pane) break i;
} else 0),
.serial = pane.serial,
.x = tx,
.y = r.y + BOX_H,
.w = body_cols,
.h = body_rows,
.rgba = iv.rgba,
.iw = iv.iw,
.ih = iv.ih,
})) return;
return;
}
// (re)build the cached glyph grid if the size or toggles changed
if (iv.grid.len == 0 or iv.grid_w != body_cols or iv.grid_h != body_rows or
iv.grid_mode != iv.pmode or iv.grid_ascii != iv.ascii)
{
if (iv.grid.len > 0) p.gpa.free(iv.grid);
const pal = switch (iv.pmode) {
.commodore => image.petscii.commodore,
.terminal => image.ansiPalette(),
};
const g = image.petscii.render(p.gpa, iv.rgba, iv.iw, iv.ih, body_cols, body_rows, pal, iv.ascii) catch image.petscii.Grid{ .cells = &.{}, .gw = 0, .gh = 0 };
iv.grid = g.cells;
iv.gw = g.gw;
iv.gh = g.gh;
iv.grid_w = body_cols;
iv.grid_h = body_rows;
iv.grid_mode = iv.pmode;
iv.grid_ascii = iv.ascii;
}
if (iv.grid.len == 0) return;
const offx = if (body_cols > iv.gw) (@as(usize, body_cols) - iv.gw) / 2 else 0;
const offy = if (body_rows > iv.gh) (@as(usize, body_rows) - iv.gh) / 2 else 0;
var cy: usize = 0;
while (cy < iv.gh) : (cy += 1) {
var cx: usize = 0;
while (cx < iv.gw) : (cx += 1) {
const c = &iv.grid[cy * iv.gw + cx];
const fg: Color = switch (iv.pmode) {
.commodore => .{ .rgb = image.petscii.commodore[c.fg] },
.terminal => .{ .index = c.fg },
};
const bg: Color = switch (iv.pmode) {
.commodore => .{ .rgb = image.petscii.commodore[c.bg] },
.terminal => .{ .index = c.bg },
};
const sx = tx + @as(u16, @intCast(offx + cx));
const sy = r.y + BOX_H + @as(u16, @intCast(offy + cy));
if (sx < s.cols and sy < s.rows)
s.set(sx, sy, c.glyph[0..c.glen], .{ .fg = fg, .bg = bg });
}
}
}
/// The pane body as text. Image: blank rows (the picture draws over it).
/// File: line-numbered content from f.scroll.
/// Terminal: viewport rows, padded to the grid height, prompt rows blanked
/// outside tty mode (OSC 133), the edit buffer standing in for the shell
/// rows it covers — which is where a buffer holding more lines than those
/// rows pushes the output below it down the screen.
fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
if (pane.image != null) {
const buf = try arena.alloc(u8, pane.rows -| 1);
@memset(buf, '\n');
return buf;
}
if (hasPdf(pane)) {
const text = try p.ensurePdfText(pane);
const scroll = if (comptime pdf_enabled) pane.pdf.?.text_scroll else 0;
var out: std.ArrayList(u8) = .empty;
var lines = std.mem.splitScalar(u8, text, '\n');
var row: usize = 0;
var wrote: usize = 0;
while (lines.next()) |line| : (row += 1) {
if (row < scroll) continue;
if (wrote >= pane.rows -| BOX_H) break;
if (wrote > 0) try out.append(arena, '\n');
try out.appendSlice(arena, line);
wrote += 1;
}
return out.items;
}
if (pane.file) |*f| return file_pane.bodyText(arena, pane, f, p.wrap_on);
return term_pane.bodyText(arena, pane);
}
};
|