elisprs 0.1.20

Emacs Lisp as a fusevm frontend: a reader and compiler to fusevm::Chunk on an ElispHost object heap, with no bespoke VM or JIT
Documentation
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
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
//! The elisp prelude: the large `[DERIVED]` surface (per the research
//! inventory) written in elisp on top of the Rust primitives. This is how the
//! port gets breadth without hand-coding a thousand subrs — exactly how Emacs
//! bootstraps `subr.el`.
//!
//! Loaded once per host (see `lib::load_prelude`), form by form, best-effort.
//! Everything here uses only primitives or earlier prelude definitions, and
//! every macro is defined before its first use.

pub const PRELUDE: &str = r#"
;; declare: a no-op at runtime (specs are advisory; defun/lambda ignore them).
;; Defined first so that every later definition may carry one.
(defmacro declare (&rest _specs) nil)
;;; backquote.el. The reader makes `X, ,X and ,@X into (\` X), (\, X) and
;;; (\,@ X), as Emacs's does; these macros expand them through
;;; `backquote-process' (src/backquote.rs). Defined first because every later
;;; macro in this prelude is written with backquote.
(defun backquote-list*-function (first &rest list)
  (if list
      (let* ((rest list) (newlist (cons first nil)) (last newlist))
        (while (cdr rest)
          (setcdr last (cons (car rest) nil))
          (setq last (cdr last)
                rest (cdr rest)))
        (setcdr last (car rest))
        newlist)
    first))
;; backquote.el reverses with `nreverse', which this prelude defines later;
;; the list is freshly consed, so `reverse' is indistinguishable.
(defmacro backquote-list*-macro (first &rest list)
  (setq list (reverse (cons first list))
        first (car list)
        list (cdr list))
  (if list
      (let* ((second (car list))
             (rest (cdr list))
             (newlist (list 'cons second first)))
        (while rest
          (setq newlist (list 'cons (car rest) newlist)
                rest (cdr rest)))
        newlist)
    first))
(fset 'backquote-list* (symbol-function 'backquote-list*-macro))
(defconst backquote-backquote-symbol '\`)
(defconst backquote-unquote-symbol '\,)
(defconst backquote-splice-symbol '\,@)
(defmacro backquote (structure)
  (cdr (backquote-process structure)))
(fset '\` (symbol-function 'backquote))

;;; The c[ad]+r family (caar .. cddddr) is Rust subrs: src/builtins.rs `cxr`.

;; Regexp matching folds case unless this is let-bound to nil (Emacs default t).
(defvar case-fold-search t)
;; subr.el's default SEPARATORS for `split-string'. Space, formfeed, tab,
;; newline, carriage return, vertical tab -- ASCII only, deliberately not
;; "whitespace" in the Unicode sense. The Rust subr carries the same literal
;; (`SPLIT_STRING_DEFAULT_SEPARATORS' in src/builtins.rs); this defvar exists so
;; Lisp can read and rebind it, as subr.el's does.
(defvar split-string-default-separators "[ \f\t\n\r\v]+")

;;; ---- build/system identity (C-level vars from emacs.c, verified against
;;; ---- GNU Emacs 30.2) ----
;; `emacs-version' is a C variable (Vemacs_version). We track the emulated
;; Emacs release the prelude is faithful to.
(defconst emacs-version "30.2")
;; `emacs-major-version'/`emacs-minor-version' are derived in lisp/version.el
;; exactly like this; kept here because version.el is not preloaded.
(defconst emacs-major-version
  (progn (string-match "^[0-9]+" emacs-version)
         (string-to-number (match-string 0 emacs-version))))
(defconst emacs-minor-version
  (progn (string-match "^[0-9]+\\.\\([0-9]+\\)" emacs-version)
         (string-to-number (match-string 1 emacs-version))))
;; `emacs-build-system'/`emacs-build-time'/`emacs-build-number' are defined in
;; lisp/version.el exactly like this (minus the Android build branches, which
;; never apply here); kept here because version.el is not preloaded. Because
;; `emacs-build-system' is non-nil, `emacs-build-time' is a `current-time'
;; timestamp, matching a normally-dumped `emacs -Q --batch'.
;;
;; version.el evaluates that `(current-time)' while the binary is being DUMPED,
;; so the value is a constant of the build and every run of one Emacs reports
;; the same list. elisprs has no dump step, so `--build-time--' supplies the
;; corresponding fixed point (the executable's mtime); calling `current-time'
;; here instead gave a different answer on every invocation.
(defconst emacs-build-system (system-name))
(defconst emacs-build-time (if emacs-build-system (--build-time--)))
(defconst emacs-build-number 1)
;; `system-type' (Vsystem_type) is platform-derived; the Rust primitive maps the
;; running OS to Emacs's symbol (darwin/gnu-linux/berkeley-unix/windows-nt).
(defvar system-type (--system-type--))
;; No GUI and non-interactive batch execution, matching `emacs -Q --batch'.
(defvar window-system nil)
(defvar noninteractive t)
;; `temporary-file-directory' is defined below, right after
;; `file-name-as-directory', which its initializer depends on.

;;; ---- numeric helpers ----
;; Fixnum bounds match GNU Emacs on a 64-bit build (62-bit tagged integers).
(defconst most-positive-fixnum 2305843009213693951)
(defconst most-negative-fixnum -2305843009213693952)
(defconst float-pi 3.141592653589793)
(defconst float-e 2.718281828459045)
(defconst pi 3.141592653589793)
;; `abs` is a primitive subr (keeps int/float type; (abs -0.0) => 0.0).
;; NaN propagates: any NaN arg makes the result NaN (a NaN never wins `>`/`<`,
;; so once it lands in the accumulator no later value can displace it).
;; `mod` is a primitive subr (handles float operands + divisor-sign semantics).
(defun /= (a b) (not (= a b)))
(defun plusp (x) (> x 0))
(defun minusp (x) (< x 0))
(defun cl-plusp (x) (> x 0))
(defun cl-minusp (x) (< x 0))
;; zerop is a byte-compiled defsubst from subr.el in Emacs -- NOT a C subr
;; ((subrp (symbol-function 'zerop)) => nil) -- so a wrong argument count is
;; caught by exec_byte_code and signalled as ((MANDATORY . NONREST) NARGS):
;; (wrong-number-of-arguments (1 . 1) 2), never as #<subr zerop>. Take &rest
;; and reproduce that exact shape, like cl-evenp/cl-oddp below; the body is
;; subr.el's (= 0 number), whose own `=' supplies number-or-marker-p errors.
;; This defun shadows the native subr registered in builtins.rs.
(defun zerop (&rest args)
  (unless (= (length args) 1)
    (signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
  (= 0 (car args)))
(defun evenp (x) (zerop (% x 2)))
(defun oddp (x) (not (zerop (% x 2))))
;; natnump is a native subr (builtins.rs): it is a C subr in Emacs, so its
;; error objects must carry `#<subr natnump>`, not a closure.
(defun wholenump (x) (natnump x))

;;; ---- list construction / access ----
;; `nthcdr' is a Rust subr (src/builtins.rs `nthcdr_fn'), ported from fns.c
;; `Fnthcdr'. The elisp definition it replaces counted N down in a `while' loop,
;; which neither accepted a bignum N nor terminated on a circular LIST —
;; (nthcdr 4611686018427387903 CYCLE) spun forever where Emacs answers in
;; constant time via Brent's tortoise plus a modulo reduction.
(defun last (l &optional n)
  ;; The last N cons cells of L (default 1): (last '(1 2 3) 2) => (2 3).
  ;; Guard on consp so an improper tail stops the walk instead of erroring:
  ;; (last '(1 2 . 3)) => (2 . 3).
  (cond
   ;; A non-list has no cons cells to take: Emacs returns it unchanged --
   ;; (last t) and (last t 0) are both t.
   ((not (consp l)) l)
   ;; subr.el: `(nthcdr (1- (safe-length list)) list)'. Walking `cdr' until
   ;; it stops being a cons never terminated on a circular list; `safe-length'
   ;; does, so `(last CYCLE)' answers the same cell Emacs does.
   ((null n) (nthcdr (1- (safe-length l)) l))
   ;; `safe-length', not `length': an improper list has no `length' (it signals
   ;; `wrong-type-argument listp TAIL'), so `(last (cons "z" 1.5) 7)' errored
   ;; where Emacs answers the whole improper list, `("z" . 1.5)'. The two agree
   ;; on every proper list.
   (t (nthcdr (max 0 (- (safe-length l) n)) l))))
(defun number-sequence (from &optional to inc)
  ;; With only FROM, or FROM=TO, the sequence is (FROM); INC defaults to 1.
  (if (or (null to) (= from to))
      (list from)
    (setq inc (or inc 1))
    ;; A zero increment would loop forever; Emacs signals instead.
    (when (= inc 0) (error "The increment can not be zero"))
    (let ((r nil))
      (if (< inc 0)
          (while (>= from to) (setq r (cons from r)) (setq from (+ from inc)))
        (while (<= from to) (setq r (cons from r)) (setq from (+ from inc))))
      (reverse r))))
(defun safe-length (l)
  ;; Length of a possibly circular or dotted list, never erroring or looping
  ;; forever.  Faithful to Emacs 30.2's FOR_EACH_TAIL_SAFE (Brent's teleporting
  ;; tortoise/hare, lisp.h): the tortoise jumps to the current tail after
  ;; 2, 4, 8, ... steps and a cycle is reported when the tail meets it, so a
  ;; circular list returns an integer >= the number of distinct cells -- a
  ;; 3-cycle => 5, exactly as Emacs.  (safe-length '(1 2 . 3)) => 2.
  (let ((tail l) (tortoise l) (interval 2) (q 2) (len 0) (done nil))
    (while (and (consp tail) (not done))
      (setq len (1+ len) tail (cdr tail))
      (if (not (consp tail))
          (setq done t)
        (setq q (1- q))
        (if (> q 0)
            (when (eq tail tortoise) (setq done t))
          (setq interval (* interval 2) q interval tortoise tail))))
    len))
;; fns.c `length_internal': LEN is the C `int' parameter, so a fixnum LENGTH
;; is truncated to 32 bits on the way in. Walking a list that is no longer
;; than LEN conses returns what is left of LEN; reaching zero returns -1. A
;; LEN of #xffff or more walks with FOR_EACH_TAIL, which signals on a cycle.
(defun length--internal (sequence len)
  (setq len (logand len #xffffffff))
  (when (>= len #x80000000) (setq len (- len #x100000000)))
  (when (>= len #xffff)
    ;; `length' signals `(circular-list SEQUENCE)' as FOR_EACH_TAIL does.
    (condition-case nil (length sequence) (wrong-type-argument nil)))
  (catch 'length--done
    (while (consp sequence)
      (when (<= (setq len (1- len)) 0) (throw 'length--done -1))
      (setq sequence (cdr sequence)))
    len))
(defun length< (sequence length)
  (unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
  (if (consp sequence)
      (not (= (length--internal sequence length) -1))
    (< (length sequence) length)))
(defun length> (sequence length)
  (unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
  (if (consp sequence)
      (= (length--internal sequence (1+ length)) -1)
    (> (length sequence) length)))
(defun length= (sequence length)
  (unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
  (cond ((< length 0) nil)
        ((consp sequence) (= (length--internal sequence (1+ length)) 1))
        (t (= (length sequence) length))))
(defun car-safe (x) (if (consp x) (car x) nil))
(defun cdr-safe (x) (if (consp x) (cdr x) nil))
(defun caar-safe (x) (if (consp x) (car x) nil))

;;; ---- membership / search ----
;; `memq'/`memql'/`member'/`assq'/`assoc'/`rassq'/`rassoc'/`mapconcat' are C
;; subrs in fns.c, and are Rust subrs here (see `builtins::TailWalk'). They were
;; prelude `defun's, whose bare `while (consp l)' walk had no cycle check and so
;; ran forever on a circular list where Emacs signals `circular-list'.
(defun assoc-string (key alist &optional case-fold)
  ;; First ALIST element equal to KEY as a string (elements may be strings or
  ;; (STRING . VALUE) conses); CASE-FOLD ignores case.  A matched element may
  ;; itself be nil (e.g. key nil over (... nil)), so track a separate DONE
  ;; flag like C `Fassoc_string' returning ELT directly -- looping on
  ;; (not r) spins forever when r is set to nil.
  (let ((k (if (symbolp key) (symbol-name key) key)) (r nil) (done nil))
    (while (and (consp alist) (not done))
      (let* ((el (car alist))
             (raw (if (consp el) (car el) el))
             (s (if (symbolp raw) (symbol-name raw) raw)))
        (if (and (stringp s)
                 (if case-fold (string-equal-ignore-case k s) (string= k s)))
            (setq r el done t)
          (setq alist (cdr alist)))))
    r))
(defun alist-get (k al &optional default _remove testfn)
  ;; Value associated with K in alist AL (DEFAULT if absent); TESTFN overrides eq.
  (let ((p (if testfn (assoc k al testfn) (assq k al))))
    (if p (cdr p) default)))
(defun plist-get (pl k &optional predicate)
  ;; Fplist_get walks with FOR_EACH_TAIL_SAFE and never signals: it breaks as
  ;; soon as the cdr is not a cons -- BEFORE testing the key -- so an improper
  ;; or odd plist just answers nil: (plist-get '(1 . 2) 1) => nil,
  ;; (plist-get '(1) 1) => nil, (plist-get 5 1) => nil.
  (let ((test (or predicate #'eq)) (r nil))
    (while (and (consp pl) (consp (cdr pl)))
      (if (funcall test (car pl) k) (progn (setq r (cadr pl)) (setq pl nil))
        (setq pl (cddr pl))))
    r))
(defun plist-member (pl k &optional predicate)
  ;; Fplist_member tests the key FIRST, then steps by two, breaking mid-step
  ;; when the odd-position cdr is not a cons; CHECK_TYPE at the end names the
  ;; WHOLE plist under `plistp': (plist-member '(1 . 2) 1) => (1 . 2), but
  ;; (plist-member '(1 . 2) 2) => (wrong-type-argument plistp (1 . 2)) and
  ;; (plist-member 5 1) => (wrong-type-argument plistp 5).
  (let ((test (or predicate #'eq)) (tail pl) (r nil) (done nil))
    (while (and (not done) (consp tail))
      (if (funcall test (car tail) k) (setq r tail done t)
        (progn (setq tail (cdr tail))
               (if (consp tail) (setq tail (cdr tail)) (setq done t)))))
    (unless (or r (null tail))
      (signal 'wrong-type-argument (list 'plistp pl)))
    r))

;;; ---- higher-order / sequence ----
;; seq-* accept any sequence; coerce list/vector/string to a list to iterate.
(defun seq-reduce (f l init) (setq l (append l nil)) (while l (setq init (funcall f init (car l))) (setq l (cdr l))) init)
(defun seq-map (f l) (mapcar f l))
(defun seq-each (f l) (mapc f l))
(defun seq-filter (pred l)
  (setq l (append l nil))
  (let ((r nil)) (while l (if (funcall pred (car l)) (setq r (cons (car l) r))) (setq l (cdr l))) (reverse r)))
(defun seq-remove (pred l) (seq-filter (lambda (e) (not (funcall pred e))) l))
(defun seq-find (pred l &optional default)
  (setq l (append l nil))
  (let ((res default)) (while l (if (funcall pred (car l)) (progn (setq res (car l)) (setq l nil)) (setq l (cdr l)))) res))
(defun seq-some (pred l) (setq l (append l nil)) (let ((r nil)) (while (and l (not r)) (setq r (funcall pred (car l))) (setq l (cdr l))) r))
(defun seq-every-p (pred l) (setq l (append l nil)) (let ((r t)) (while (and l r) (setq r (funcall pred (car l))) (setq l (cdr l))) r))
(defun seq-count (pred l) (setq l (append l nil)) (let ((n 0)) (while l (if (funcall pred (car l)) (setq n (1+ n))) (setq l (cdr l))) n))
(defun seq-empty-p (l) (= 0 (length l)))
(defun seq-length (l) (length l))
;; seq.el: `seq-copy' is `copy-sequence' and `seq-random-elt' indexes a random
;; position, refusing an empty sequence with seq.el's own message.
(defun seq-copy (sequence) (copy-sequence sequence))
(defun seq-random-elt (sequence)
  (if (seq-empty-p sequence)
      (error "Sequence cannot be empty")
    (seq-elt sequence (random (seq-length sequence)))))
;; `seq-elt' is `(cl-defgeneric seq-elt (sequence n) (elt sequence n))' in
;; seq.el and Emacs ships seq.elc, so the body that actually runs is the
;; byte-compiled one -- and the byte compiler emits the `Belt' opcode for
;; `(elt SEQ N)' rather than a call to `Felt'.  `Belt' does NOT delegate to
;; `Felt' for a cons with a small non-negative index: it walks the cdrs inline
;; and reports the TAIL it choked on, where `Felt' -> `Fnthcdr' reports the
;; original list (bytecode.c:1578-1599 vs fns.c:1755-1866 on emacs-30):
;;
;;   (elt     (cons "" 'sym) 2)  =>  (wrong-type-argument listp ("" . sym))
;;   (seq-elt (cons "" 'sym) 2)  =>  (wrong-type-argument listp sym)
;;
;; The fast path is guarded by `RANGED_FIXNUMP (0, v2, SMALL_LIST_LEN_MAX)' --
;; SMALL_LIST_LEN_MAX is 127 (lisp.h) -- so a negative, bignum or >127 index
;; falls through to `elt' exactly as the opcode falls through to `Felt', and so
;; does every non-cons sequence.  A cons walk that lands on nil answers nil.
(defun seq-elt (l n)
  (if (and (consp l) (integerp n) (>= n 0) (<= n 127))
      (let ((tail l) (k n))
        (while (and (> k 0) (consp tail))
          (setq tail (cdr tail))
          (setq k (1- k)))
        (cond ((consp tail) (car tail))
              ((null tail) nil)
              (t (signal 'wrong-type-argument (list 'listp tail)))))
    (elt l n)))
(defun seq-do (f l) (mapc f l))
(defun seqp (object) (sequencep object))
(defun seq-contains-p (seq elt &optional testfn)
  (let ((test (or testfn #'equal)) (l (append seq nil)) (r nil))
    (while (and l (not r)) (when (funcall test elt (car l)) (setq r t)) (setq l (cdr l)))
    r))
(defun seq-reverse (l) (reverse l))

;;; ---- set-ish list ops ----
(defun remove (elt seq)
  ;; subr.el: (delete elt (if (nlistp seq) seq (copy-sequence seq))) -- a
  ;; dotted list dies inside `copy-sequence' naming the TAIL, and a
  ;; non-sequence inside `delete' naming itself under `sequencep'.
  (delete elt (if (nlistp seq) seq (copy-sequence seq))))
(defun remq (elt list)
  ;; subr.el: cdr past `eq' matches at the head (a non-cons LIST signals
  ;; `listp' via `car'), then copy -- (delq ELT (copy-sequence LIST)) -- only
  ;; when a match remains. `memq' names the WHOLE (post-skip) list on a dotted
  ;; tail; `copy-sequence' names the TAIL.
  (while (and (eq elt (car list)) (setq list (cdr list))))
  (if (memq elt list)
      (delq elt (copy-sequence list))
    list))
;; `Fstring_to_multibyte': a unibyte string is converted into a fresh multibyte
;; one without the original's properties; a multibyte one is returned as is.
;; Strings carry no unibyte flag here, so an all-ASCII one stands for unibyte.
(defun string-to-multibyte (s)
  (if (and (stringp s) (string-match-p "\\`[[:ascii:]]*\\'" s))
      (substring-no-properties s)
    s))
(defun string-as-multibyte (s) s)
(defun string-to-unibyte (s &rest _) s)
(defun string-as-unibyte (s) s)
(defun multibyte-string-p (s)
  ;; Approximate Emacs: a string is "multibyte" if it has any non-ASCII char.
  (let ((l (and (stringp s) (string-to-list s))) (r nil))
    (while (and l (not r)) (when (>= (car l) 128) (setq r t)) (setq l (cdr l)))
    r))
;; delete/delq remove matching elements destructively (splicing cons cells) for
;; lists; delete filters vectors/strings into a fresh copy.
(defun delete (elt seq)
  ;; Fdelete: vectors and strings filter into a fresh copy; a cons/nil walks
  ;; like Fdelq with `equal', where CHECK_LIST_END names SEQ as rebound by any
  ;; head removals -- (delete "a" '("a" . [1 2])) => (wrong-type-argument
  ;; listp [1 2]) but with "b" the data is the whole dotted list. Anything
  ;; else is not a sequence at all.
  (cond
   ((vectorp seq)
    (vconcat (seq-filter (lambda (e) (not (equal e elt))) (append seq nil))))
   ((stringp seq)
    (concat (seq-filter (lambda (e) (not (equal e elt))) (append seq nil))))
   ((not (listp seq)) (signal 'wrong-type-argument (list 'sequencep seq)))
   (t
    (let ((tail seq) (prev nil))
      (while (consp tail)
        (if (equal elt (car tail))
            (if (null prev) (setq seq (cdr tail)) (setcdr prev (cdr tail)))
          (setq prev tail))
        (setq tail (cdr tail)))
      (unless (null tail)
        (signal 'wrong-type-argument (list 'listp seq)))
      seq))))
(defun delq (elt list)
  ;; Fdelq: the same walk with `eq'; CHECK_LIST_END names LIST as rebound by
  ;; head removals, so (delq 'a (cons 'a 5)) => (wrong-type-argument listp 5)
  ;; while (delq 'x (cons 'a 5)) names the whole (a . 5).
  (let ((tail list) (prev nil))
    (while (consp tail)
      (if (eq elt (car tail))
          (if (null prev) (setq list (cdr tail)) (setcdr prev (cdr tail)))
        (setq prev tail))
      (setq tail (cdr tail)))
    (unless (null tail)
      (signal 'wrong-type-argument (list 'listp list)))
    list))
(defun delete-dups (l)
  ;; Destructively remove `equal' duplicates, keeping the first occurrence.
  ;; subr.el sizes a hash table with (length list) FIRST, which is what makes a
  ;; non-list signal sequencep and a dotted list signal listp on its tail:
  ;; (delete-dups 'sym) => (wrong-type-argument sequencep sym).
  (length l)
  (let ((tail l))
    (while tail
      (setcdr tail (delete (car tail) (cdr tail)))
      (setq tail (cdr tail))))
  l)
(defun nconc (&rest args)
  ;; Faithful Fnconc: nil arguments are skipped; every argument but the last
  ;; must be a cons (CHECK_CONS => `consp', not `listp': (nconc 0 '(1)) =>
  ;; wrong-type-argument consp 0); each argument's cons spine is walked to its
  ;; LAST CONS -- a dotted tail is simply overwritten, never an error, so
  ;; (nconc '(1) '(2 . 3) '(4)) => (1 2 4) -- and spliced onto the next
  ;; argument. The last argument is never validated and becomes the final cdr.
  (let ((val nil))
    (while args
      (let ((tem (car args)))
        (when tem
          (when (null val) (setq val tem))
          (when (cdr args)
            (unless (consp tem)
              (signal 'wrong-type-argument (list 'consp tem)))
            (let ((tail tem))
              (while (consp (cdr tail)) (setq tail (cdr tail)))
              (setcdr tail (cadr args))
              ;; Fnconc: when the NEXT arg is nil, substitute the tail cons we
              ;; just spliced so the following iteration keeps extending it.
              (when (null (cadr args)) (setcar (cdr args) tail))))))
      (setq args (cdr args)))
    val))
(defun rassq-delete-all (value alist)
  ;; Faithful subr.el port (destructive): drop leading matches by advancing
  ;; ALIST, then setcdr out interior ones. `(car alist)' on a non-list is what
  ;; signals: (rassq-delete-all "x" -1) => (wrong-type-argument listp -1).
  (while (and (consp (car alist)) (eq (cdr (car alist)) value))
    (setq alist (cdr alist)))
  (let ((tail alist) tail-cdr)
    (while (setq tail-cdr (cdr tail))
      (if (and (consp (car tail-cdr)) (eq (cdr (car tail-cdr)) value))
          (setcdr tail (cdr tail-cdr))
        (setq tail tail-cdr))))
  alist)

;;; ---- cl-lib niceties ----
(defun cl-first (l) (car l))
(defun cl-second (l) (cadr l))
(defun cl-third (l) (caddr l))
(defun cl-rest (l) (cdr l))

;; data.c `Finteractive_form' and eval.c `Fcommandp'.  A macro's function cell
;; is `(macro . FN)' in Emacs, a cons whose car is not `lambda', so neither
;; treats one as a command.  A primitive's `intspec' is recorded by
;; `--set-subr-intspec' below.  Not modelled: loading an autoload to read its
;; form, and the OClosure `oclosure-interactive-form' delegation.
(defun interactive-form (cmd)
  (let ((fun (indirect-function cmd)) (found nil) (spec nil))
    (when fun
      (setq fun cmd)
      (while (and (not found) (symbolp fun))
        (let ((tmp (get fun 'interactive-form)))
          (if tmp
              (setq found t spec tmp)
            (setq fun (symbol-function fun)))))
      (cond
       (found spec)
       ((subrp fun)
        (let ((spec (--subr-intspec fun)))
          (and spec (list 'interactive spec))))
       ((and (closurep fun) (> (length fun) 5))
        (let ((form (aref fun 5)))
          (list 'interactive (if (vectorp form) (aref form 0) form))))
       ((eq (car-safe fun) 'lambda)
        (let ((spec (assq 'interactive (cdr (cdr fun)))))
          (if (null (cdr (cdr spec)))
              spec
            (list 'interactive (car (cdr spec))))))))))
(defun commandp (function &optional for-call-interactively)
  (let ((fun (indirect-function function)))
    (cond
     ((null fun) nil)
     ((subrp fun) (and (--subr-intspec fun) t))
     ((closurep fun) (> (length fun) 5))
     ((or (stringp fun) (vectorp fun)) (null for-call-interactively))
     ((not (consp fun)) nil)
     ((eq (car fun) 'autoload)
      (if (car (cdr (cdr (cdr fun)))) t
        (setq fun function)
        (while (symbolp fun)
          (when (get fun 'interactive-form)
            (error "Found an 'interactive-form' property!"))
          (setq fun (symbol-function fun)))
        nil))
     ((eq (car fun) 'lambda)
      (and (assq 'interactive (cdr-safe (cdr fun))) t))
     (t nil))))
;; The primitives that are commands, with their DEFUN intspecs (Emacs 31.1;
;; `search-forward-regexp' / `search-backward-regexp' share the `re-search-*'
;; subr objects).
(--set-subr-intspec 'backward-char "^p")
(--set-subr-intspec 'beginning-of-line "^p")
(--set-subr-intspec 'copy-file "fCopy file: \nGCopy %s to file: \np\nP")
(--set-subr-intspec 'delete-char "p\nP")
(--set-subr-intspec 'delete-region "r")
(--set-subr-intspec 'end-of-line "^p")
(--set-subr-intspec 'erase-buffer "*")
(--set-subr-intspec 'forward-char "^p")
(--set-subr-intspec 'forward-line "^p")
(--set-subr-intspec 'forward-word "^p")
(--set-subr-intspec 'goto-char '(goto-char--read-natnum-interactive "Go to char: "))
(--set-subr-intspec 'indent-to "NIndent to column: ")
(--set-subr-intspec 'insert-char '(list (read-char-by-name "Insert character (Unicode name or hex): ") (prefix-numeric-value current-prefix-arg) t))
(--set-subr-intspec 'kill-buffer "bKill buffer: ")
(--set-subr-intspec 'kill-local-variable "vKill Local Variable: ")
(--set-subr-intspec 'make-local-variable "vMake Local Variable: ")
(--set-subr-intspec 'make-variable-buffer-local "vMake Variable Buffer Local: ")
(--set-subr-intspec 'move-to-column "NMove to column: ")
(--set-subr-intspec 'narrow-to-region "r")
(--set-subr-intspec 're-search-backward "sRE search backward: ")
(--set-subr-intspec 're-search-forward "sRE search: ")
(--set-subr-intspec 'rename-buffer '(list (read-string "Rename buffer (to new name): " nil 'buffer-name-history (buffer-name (current-buffer))) current-prefix-arg))
(--set-subr-intspec 'rename-file "fRename file: \nGRename %s to file: \np")
(--set-subr-intspec 'search-backward "MSearch backward: ")
(--set-subr-intspec 'search-forward "MSearch: ")
(--set-subr-intspec 'widen "")
(--set-subr-intspec 'write-region "r\nFWrite region to file: \ni\ni\ni\np")
(defun plistp (l)
  (let ((n 0)) (while (consp l) (setq n (1+ n)) (setq l (cdr l))) (and (null l) (= 0 (% n 2)))))
;; Port of cl-some/cl-every from cl-extra.el: with extra SEQs (or a non-list
;; SEQ) map PRED over the sequences in parallel, stopping at the shortest.
(defun cl-some (pred seq &rest rest)
  (if (or rest (nlistp seq))
      (catch 'cl-some
        (apply (function cl-map) nil
               (lambda (&rest x)
                 (let ((res (apply pred x)))
                   (if res (throw 'cl-some res))))
               seq rest)
        nil)
    (let ((x nil))
      (while (and seq (not (setq x (funcall pred (car seq))))) (setq seq (cdr seq)))
      x)))
(defun cl-every (pred seq &rest rest)
  (if (or rest (nlistp seq))
      (catch 'cl-every
        (apply (function cl-map) nil
               (lambda (&rest x) (or (apply pred x) (throw 'cl-every nil)))
               seq rest)
        t)
    (while (and seq (funcall pred (car seq))) (setq seq (cdr seq)))
    (null seq)))
(defun cl-notany (pred seq &rest rest) (not (apply (function cl-some) pred seq rest)))
(defun cl-notevery (pred seq &rest rest) (not (apply (function cl-every) pred seq rest)))
(defun cl-copy-list (list)
  (if (consp list)
      (let ((res nil))
        (while (consp list) (setq res (cons (car list) res) list (cdr list)))
        (prog1 (nreverse res) (setcdr res list)))
    (car list)))
(defun cl-revappend (l tail) (append (reverse l) tail))
(defun cl-nreconc (l tail) (nconc (nreverse l) tail))
(defmacro cl-nth-value (n form) (list 'nth n form))
(defun cl-subst (new old tree &rest keys)
  ;; With no keywords, substitute OLD (matched by `eql') throughout TREE. When
  ;; :test/:test-not/:key are given, defer to `cl-sublis' exactly like Emacs, so
  ;; the predicate is applied to every node — conses included.
  (if keys
      (apply 'cl-sublis (list (cons old new)) tree keys)
    (cond ((eql tree old) new)
          ((consp tree) (cons (cl-subst new old (car tree)) (cl-subst new old (cdr tree))))
          (t tree))))
;; NOTE: `push'/`dolist' are defined later in this file, so these helpers use
;; explicit `while'/`setq'/`cons' loops to stay valid at load time.
;; cl-extra.el's `cl-maplist' / `cl-mapl' / `cl-mapcon' / `cl-mapc', verbatim
;; but for `push'/`pop' (not yet defined here). With several LISTs they step
;; every list at once and stop at the first that runs out.
(defun cl-maplist (func list &rest rest)
  (if rest
      (let ((res nil) (args (cons list (copy-sequence rest))) p)
        (while (not (memq nil args))
          (setq res (cons (apply func args) res))
          (setq p args)
          (while p (setcar p (cdr (car p))) (setq p (cdr p))))
        (nreverse res))
    (let ((res nil))
      (while list
        (setq res (cons (funcall func list) res))
        (setq list (cdr list)))
      (nreverse res))))
(defun cl-mapl (func list &rest rest)
  (if rest
      (let ((args (cons list (copy-sequence rest))) p)
        (while (not (memq nil args))
          (apply func args)
          (setq p args)
          (while p (setcar p (cdr (car p))) (setq p (cdr p)))))
    (let ((p list))
      (while p (funcall func p) (setq p (cdr p)))))
  list)
(defun cl-mapcon (func list &rest rest)
  (apply (function nconc) (apply (function cl-maplist) func list rest)))
;; `cl-mapc' returns SEQ, not the results. Two lists step together in lisp; any
;; other shape goes through `cl-mapcar', which already handles mixed sequence
;; types (cl--mapcar-many without the accumulator).
(defun cl-mapc (func seq &rest rest)
  (if rest
      (if (or (cdr rest) (nlistp seq) (nlistp (car rest)))
          (progn (apply (function cl-mapcar) func seq rest) seq)
        (let ((x seq) (y (car rest)))
          (while (and x y)
            (funcall func (car x) (car y))
            (setq x (cdr x) y (cdr y)))
          seq))
    (mapc func seq)))
;; cl-lib.el aliases and one-liners (`defalias' is defined further down, and
;; is `fset' here).
(fset (quote cl-copy-seq) (function copy-sequence))
(fset (quote cl-svref) (function aref))
(fset (quote cl-multiple-value-call) (function apply))
(defun cl-multiple-value-list (expression) expression)
(defun cl-multiple-value-apply (function expression) (apply function expression))
;; cl-extra.el: the property is read through `cl-getf' so DEF is honoured;
;; setf on it is `put' (its gv-setter declaration).
(defun cl-get (sym tag &optional def) (cl-getf (symbol-plist sym) tag def))
;; cl-lib.el's `cl-adjoin', verbatim. The two fast paths are not an
;; optimization detail — they are the contract, because `memq'/`member' walk the
;; list themselves: with no keys and a non-numeric ITEM the walk is `memq', so
;; `(cl-adjoin "" t)' is `(wrong-type-argument listp t)' where a `seq-some'
;; paraphrase reported `sequencep'.
(defun cl-adjoin (cl-item cl-list &rest cl-keys)
  (cond ((or (equal cl-keys '(:test eq))
             (and (null cl-keys) (not (numberp cl-item))))
         (if (memq cl-item cl-list) cl-list (cons cl-item cl-list)))
        ((or (equal cl-keys '(:test equal)) (null cl-keys))
         (if (member cl-item cl-list) cl-list (cons cl-item cl-list)))
        (t (apply 'cl--adjoin cl-item cl-list cl-keys))))

;;; ---- misc functions ----
(defun ignore (&rest _args) nil)
(defun always (&rest _args) t)
;; `default-value'/`set-default' are C primitives (builtins.rs) that read/write
;; the global (default) value cell, bypassing any buffer-local binding.
(defmacro setq-default (&rest args)
  (let ((forms nil))
    (while args
      (setq forms (cons (list 'set-default (list 'quote (car args)) (cadr args)) forms))
      (setq args (cddr args)))
    (cons 'progn (nreverse forms))))
;; Printer limits: special so `(let ((print-length N)) …)` binds them dynamically
;; where the Rust printer can read them.
(defvar print-length nil)
(defvar print-level nil)
(defvar print-escape-newlines nil)
(defvar print-escape-control-characters nil)
(defvar print-escape-multibyte nil)
(defvar print-integers-as-characters nil)
(defvar print-quoted t)
(defvar float-output-format nil)
;; Without this `defvar' a `(let ((print-circle t)) …)' binds a LEXICAL `print-circle'
;; that the Rust printer — which reads the symbol's dynamic value cell — never sees,
;; so shared structure printed unlabelled and a circular list had nothing to stop it.
(defvar print-circle nil)
;; print.c `print-gensym': non-nil prints an uninterned symbol as `#:NAME'.
(defvar print-gensym nil)
;; lread.c `read-circle': nil makes `#N=' and `#N#' invalid syntax; special so
;; that a `let' of it reaches the reader.
(defvar read-circle t)
;; print.c `standard-output': where a print primitive given a nil PRINTCHARFUN
;; sends its output. t is stdout in batch; a buffer, marker or function is
;; honoured exactly as when passed as PRINTCHARFUN.
(defvar standard-output t)
(defvar gensym-counter 0)
;; subr.el: PREFIX is spliced with %s, so a symbol prefix works too.
(defun gensym (&optional prefix)
  (let ((num (prog1 gensym-counter
               (setq gensym-counter (1+ gensym-counter)))))
    (make-symbol (format "%s%d" (or prefix "g") num))))
;; `keywordp' is a subr (see `builtins::install'): the test is not the spelling
;; but whether the symbol is the one the standard obarray holds, which only the
;; host can answer.

;;; ---- control macros ----
(defmacro prog2 (a b &rest body) (declare (indent 2) (debug t)) (list (quote progn) a (cons (quote prog1) (cons b body))))
;; ---- read-modify-write places (push/pop/incf/decf/cl-callf) ----
;;
;; Every one of these mentions PLACE at least twice: once to read it, once to
;; write it. Substituting the place FORM at each mention re-evaluates its
;; subforms, which Emacs never does — gv.el binds them with `gv-letplace' before
;; building either half. The divergence is a wrong *number of side effects*:
;;
;;   (let ((n 0) (l (list 1 2))) (cl-incf (car (progn (setq n (1+ n)) l))) n)
;;     => 1 in Emacs, was 2 here
;;   (let ((n 0) (l (list 1 2 3))) (pop (cdr (progn (setq n (1+ n)) l))) n)
;;     => 1 in Emacs, was 3 here (`pop' mentions the place three times)
;;
;; `setf--place-once' rebuilds PLACE over temporaries, and every macro below
;; goes through it — one implementation of the rule, not five.
(defun setf--copyable-p (x)
  ;; `macroexp-copyable-p', inlined because these macros are defined long before
  ;; macroexp.el is: a symbol or a constant costs nothing to duplicate; anything
  ;; else (a call) must be bound.
  (not (and (consp x) (not (memq (car x) (quote (quote function)))))))
(defun setf--bind1 (form)
  ;; (BINDINGS . REF) for one subform: no binding at all when it is copyable.
  (if (setf--copyable-p form) (cons nil form)
    (let ((tmp (make-symbol "v"))) (cons (list (list tmp form)) tmp))))
(defun setf--place-once (place)
  ;; (BINDINGS . PLACE') where PLACE' names each of PLACE's subforms once.
  ;;
  ;; A *symbol* subform is deliberately left as itself, exactly as gv.el does:
  ;; re-reading a variable has no side effect, and some setters assign to the
  ;; subform itself — `(setf (nthcdr 0 l) v)' is `(setq l v)' — which a
  ;; temporary would silently redirect away from the caller's variable.
  (if (not (consp place)) (cons nil place)
    (let ((binds nil) (args nil) (rest (cdr place)) (b nil))
      (while rest
        (setq b (setf--bind1 (car rest)))
        (setq binds (append binds (car b)))
        (setq args (cons (cdr b) args))
        (setq rest (cdr rest)))
      (cons binds (cons (car place) (nreverse args))))))
(defun setf--rmw (place newval)
  ;; Code setting PLACE to (funcall NEWVAL GETTER), evaluating PLACE's subforms
  ;; exactly once. NEWVAL is a function of the getter form.
  (if (symbolp place)
      (list (quote setq) place (funcall newval place))
    (let* ((b (setf--place-once place)) (p (cdr b)))
      (list (quote let*) (car b) (list (quote setf) p (funcall newval p))))))
(defmacro incf (place &rest amt)
  (setf--rmw place (lambda (g) (list (quote +) g (if amt (car amt) 1)))))
(defmacro decf (place &rest amt)
  (setf--rmw place (lambda (g) (list (quote -) g (if amt (car amt) 1)))))
;; push: cons X onto PLACE. A plain variable uses setq; a generalized place
;; (e.g. (cdr l), (nth 1 l), (gethash k h)) goes through setf. X is bound first,
;; so it is evaluated before the place's subforms — subr.el's `macroexp-let2' on
;; NEWELT wraps the `gv-letplace' the same way round.
(defmacro push (x place)
  (if (symbolp place)
      (list (quote setq) place (list (quote cons) x place))
    (let* ((xb (setf--bind1 x))
           (b (setf--place-once place))
           (p (cdr b)))
      (list (quote let*) (append (car xb) (car b))
            (list (quote setf) p (list (quote cons) (cdr xb) p))))))
;; setf: assign to a generalized place. Supports a plain variable and the
;; common cons/sequence/hash/symbol places; multiple place/value pairs expand
;; left-to-right.
(defmacro setf (&rest pairs)
  (if (null pairs)
      nil
    (let ((place (car pairs)) (val (cadr pairs)) (rest (cddr pairs)))
      (let ((exp
             (if (consp place)
                 (let ((head (car place)) (args (cdr place)))
                   (cond
                    ((eq head 'car) `(setcar ,(car args) ,val))
                    ((eq head 'cdr) `(setcdr ,(car args) ,val))
                    ((eq head 'caar) `(setcar (car ,(car args)) ,val))
                    ((eq head 'cadr) `(setcar (cdr ,(car args)) ,val))
                    ((eq head 'cddr) `(setcdr (cdr ,(car args)) ,val))
                    ((eq head 'nth) `(setcar (nthcdr ,(car args) ,(cadr args)) ,val))
                    ((eq head 'nthcdr) `(setcdr (nthcdr (1- ,(car args)) ,(cadr args)) ,val))
                    ((eq head 'elt)
                     `(if (listp ,(car args))
                          (setcar (nthcdr ,(cadr args) ,(car args)) ,val)
                        (aset ,(car args) ,(cadr args) ,val)))
                    ((eq head 'aref) `(aset ,(car args) ,(cadr args) ,val))
                    ((eq head 'gethash) `(puthash ,(car args) ,val ,(cadr args)))
                    ((eq head 'symbol-value) `(set ,(car args) ,val))
                    ((eq head 'alist-get) `(setcdr (assq ,(car args) ,(cadr args)) ,val))
                    (t (signal 'gv-invalid-place (list place)))))
               `(setq ,place ,val))))
        (if rest `(progn ,exp (setf ,@rest)) exp)))))
;; subr.el: `(car-safe (prog1 PLACE (setq PLACE (cdr PLACE))))'. The `car-safe'
;; is load-bearing, not decoration — `(pop x)' on a non-list yields nil in Emacs
;; instead of signalling `wrong-type-argument', which is what a plain `car' does.
(defmacro pop (place)
  (if (symbolp place)
      (list (quote car-safe)
            (list (quote prog1) place (list (quote setq) place (list (quote cdr) place))))
    (let* ((b (setf--place-once place)) (p (cdr b)))
      (list (quote let*) (car b)
            (list (quote car-safe)
                  (list (quote prog1) p (list (quote setf) p (list (quote cdr) p))))))))
(defmacro dolist (spec &rest body)
  (declare (indent 1) (debug ((symbolp form &optional form) body)))
  ;; (dolist (VAR LIST [RESULT]) BODY...) — RESULT is the value of the form; nil
  ;; if omitted.
  ;;
  ;; subr.el binds VAR with a `let' INSIDE the loop, so each iteration gets a
  ;; FRESH binding. That is observable under lexical binding: a closure made in
  ;; the body captures that iteration's value, so
  ;;   (let (r) (dolist (x '(1 2 3) r) (push (lambda () x) r)) (mapcar #'funcall r))
  ;; is (3 2 1) in Emacs. Hoisting VAR into the enclosing `let' and `setq'ing it
  ;; per iteration — what this used to do — gives every closure the same cell, so
  ;; the same form answered (nil nil nil).
  ;;
  ;; The tail variable is uninterned (`make-symbol') exactly as in subr.el, so a
  ;; body that itself mentions a variable named `tail' is not captured by it.
  (let ((var (car spec)) (lst (cadr spec)) (result (cddr spec))
        (tail (make-symbol "tail")))
    `(let ((,tail ,lst))
       (while ,tail
         (let ((,var (car ,tail)))
           ,@body
           (setq ,tail (cdr ,tail))))
       ,@result)))
(defmacro dotimes (spec &rest body)
  (declare (indent 1) (debug dolist))
  ;; (dotimes (VAR COUNT [RESULT]) BODY...) — RESULT (with VAR bound to COUNT) is
  ;; the value of the form; nil if omitted.
  ;;
  ;; Same shape as `dolist', and for the same reason: subr.el runs the body inside
  ;; `(let ((VAR counter)) …)', so each iteration gets a FRESH binding and the
  ;; counter it steps is a separate uninterned variable. Hoisting VAR into the
  ;; enclosing `let' and `setq'ing it gave every closure made in the body the same
  ;; cell, so
  ;;   (let (fs) (dotimes (i 3) (push (lambda () i) fs)) (mapcar #'funcall (nreverse fs)))
  ;; answered (3 3 3) instead of Emacs's (0 1 2) — and it leaked the *post-loop*
  ;; value, not even the last iteration's.
  (let ((var (car spec)) (cnt (cadr spec)) (result (cddr spec))
        (upper (make-symbol "upper-bound")) (counter (make-symbol "counter")))
    `(let ((,upper ,cnt) (,counter 0))
       (while (< ,counter ,upper)
         (let ((,var ,counter)) ,@body)
         (setq ,counter (1+ ,counter)))
       ,@(if result `((let ((,var ,counter)) ,@result))))))

;;; ---- error handling ----
(defmacro ignore-errors (&rest body) (declare (debug t) (indent 0)) `(condition-case nil (progn ,@body) (error nil)))
(defmacro ignore-error (condition &rest body) (declare (debug t) (indent 1)) `(condition-case nil (progn ,@body) (,condition nil)))
(defmacro with-suppressed-warnings (_warnings &rest body) (declare (debug (sexp body)) (indent 1)) `(progn ,@body))
(defmacro with-no-warnings (&rest body) (declare (indent 0)) `(progn ,@body))
;; declare-function (subr.el:31): a pure byte-compiler hint that FN is defined
;; in FILE; `byte-compile-macroexpand-declare-function' does the real work.  In
;; the interpreter it expands to nil (matching `emacs -Q --batch').
(defmacro declare-function (_fn _file &rest _args)
  "Tell the byte-compiler that function FN is defined, in FILE.
Optional ARGLIST specifies FN's arguments.  Does nothing in the
interpreter; expands to nil."
  (declare (advertised-calling-convention
	    (fn file &optional arglist fileonly) nil))
  nil)
;; byte-run.el (31.1): in interpreted code both macros run BODY when they are
;; EXPANDED -- eager macroexpansion is the "compile time" -- and leave the value
;; behind as a constant. So the body sees no lexical binding of the code around
;; it, runs once however often the expansion is evaluated, and anything it
;; defines (a compiler macro, a defvar) is in place for the rest of the form.
(defvar macroexp--dynvars nil)
(defmacro eval-when-compile (&rest body)
  (declare (debug (&rest def-form)) (indent 0))
  (list 'quote (eval (cons 'progn body) lexical-binding)))
(defmacro eval-and-compile (&rest body)
  (declare (debug (&rest def-form)) (indent 0))
  (list 'quote (eval (cons 'progn body)
                     (when lexical-binding (or macroexp--dynvars t)))))
(defmacro cl-eval-when (situations &rest body)
  ;; Run BODY when a runtime situation (eval/load/:execute/:load-toplevel) applies.
  (if (or (memq 'eval situations) (memq 'load situations)
          (memq :execute situations) (memq :load-toplevel situations))
      (cons 'progn body)
    nil))
;; elisprs has no byte compiler, but the closures the prelude defines stand for
;; Lisp that Emacs ships byte-compiled: they answer these predicates as such,
;; and a closure the user wrote is interpreted.
(defun byte-code-function-p (object)
  "Return t if OBJECT is a byte-compiled function object."
  (elisprs--prelude-closure-p object))
(defun interpreted-function-p (object)
  "Return non-nil if OBJECT is an interpreted function."
  (and (closurep object) (not (elisprs--prelude-closure-p object))))
(defun compiled-function-p (object)
  "Return non-nil if OBJECT is a function that is compiled."
  (or (and (subrp object) t) (elisprs--prelude-closure-p object)))
;; Bound by `macroexpand-all' while it walks a form; libraries (e.g. rx) read it
;; to thread local macro environments.  Defaults to nil outside expansion.
(defvar macroexpand-all-environment nil)
;; macroexp-compiling-p (macroexp.el:141): non-nil only when expanding for the
;; byte-compiler.  elisprs interprets, so `macroexpand-all-environment' never
;; carries the compiler's declare-function cons — this returns nil.
(defun macroexp-compiling-p ()
  "Return non-nil if we're macroexpanding for the compiler."
  (member '(declare-function . byte-compile-macroexpand-declare-function)
          macroexpand-all-environment))
;; cl-lib global declarations (cl-lib.el:252 / cl-macs.el:2645-2686).  Real
;; init files reach these via `(cl-declaim (optimize (speed 3) (safety 0)))'
;; near the top of eieio-core, ede, auth-source, etc.  Faithful port: the
;; `optimize'/`special'/`inline'/`warn' specs all target byte-compiler state
;; that elisprs (an interpreter) never consults, so `cl--do-proclaim' records
;; the optimize levels and otherwise no-ops.
(defvar cl--proclaims-deferred nil)
(defvar cl--proclaim-history t)
(defvar cl--optimize-safety)
(defvar cl--optimize-speed)
(defun cl--do-proclaim (spec hist)
  (and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
  (cond ((eq (car-safe spec) 'special)
	 (if (boundp 'byte-compile-bound-variables)
	     (setq byte-compile-bound-variables
		   (append (cdr spec) byte-compile-bound-variables))))

	((eq (car-safe spec) 'inline)
	 (while (setq spec (cdr spec))
	   (or (memq (get (car spec) 'byte-optimizer)
		     '(nil byte-compile-inline-expand))
	       (error "%s already has a byte-optimizer, can't make it inline"
		      (car spec)))
	   (put (car spec) 'byte-optimizer #'byte-compile-inline-expand)))

	((eq (car-safe spec) 'notinline)
	 (while (setq spec (cdr spec))
	   (if (eq (get (car spec) 'byte-optimizer)
		   #'byte-compile-inline-expand)
	       (put (car spec) 'byte-optimizer nil))))

	((eq (car-safe spec) 'optimize)
	 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
			    '((0 nil) (1 t) (2 t) (3 t))))
	       (safety (assq (nth 1 (assq 'safety (cdr spec)))
			     '((0 t) (1 nil) (2 nil) (3 nil)))))
	   (if speed (setq cl--optimize-speed (car speed)
			   byte-optimize (nth 1 speed)))
	   (if safety (setq cl--optimize-safety (car safety)
			    byte-compile-delete-errors (nth 1 safety)))))

	((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
	 (while (setq spec (cdr spec))
	   (if (consp (car spec))
               (if (eq (cadar spec) 0)
                   (byte-compile-disable-warning (caar spec))
                 (byte-compile-enable-warning (caar spec)))))))
  nil)
(defun cl-proclaim (spec)
  "Record a global declaration specified by SPEC."
  (if (fboundp 'cl--do-proclaim) (cl--do-proclaim spec t)
    (push spec cl--proclaims-deferred))
  nil)
(defmacro cl-declaim (&rest specs)
  "Like `cl-proclaim', but takes any number of unevaluated, unquoted arguments.
Puts `(cl-eval-when (compile load eval) ...)' around the declarations
so that they are registered at compile-time as well as run-time."
  (let ((body (mapcar (lambda (x) `(cl-proclaim ',x)) specs)))
    (if (macroexp-compiling-p) `(cl-eval-when (compile load eval) ,@body)
      `(progn ,@body))))
;; A form that evaluates to V (self-quoting literals as-is, else (quote V)).
(defun macroexp-quote (v)
  (if (and (not (consp v)) (or (not (symbolp v)) (null v) (eq v t) (keywordp v)))
      v
    (list 'quote v)))
;; macroexp const-ness predicates (macroexp.el:682).  Used by cl-macs/cl-generic
;; to decide when a subform may be duplicated or optimized away.
(defvar byte-compile-const-variables nil)
(defun macroexp--const-symbol-p (symbol &optional any-value)
  "Non-nil if SYMBOL is constant.
If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
symbol itself."
  (or (memq symbol '(nil t))
      (keywordp symbol)
      (if any-value
          (or (memq symbol byte-compile-const-variables)
              (and (boundp symbol)
                   (condition-case nil
                       (progn (set symbol (symbol-value symbol)) nil)
                     (setting-constant t)))))))
(defun macroexp-const-p (exp)
  "Return non-nil if EXP will always evaluate to the same value."
  (cond ((consp exp) (or (eq (car exp) 'quote)
                         (and (eq (car exp) 'function)
                              (symbolp (cadr exp)))))
        ((symbolp exp) (macroexp--const-symbol-p exp))
        (t t)))
(defun macroexp-copyable-p (exp)
  "Return non-nil if EXP can be copied without extra cost."
  (or (symbolp exp) (macroexp-const-p exp)))
;; defsubst: define an inline function.  In the interpreter this is exactly a
;; `defun'; the `byte-optimizer' property is what the byte-compiler consults to
;; inline calls (byte-run.el:481).  elisprs has no byte-compiler, so the
;; property is set for faithfulness but never acted upon.
(defmacro defsubst (name arglist &rest body)
  "Define an inline function.  The syntax is just like that of `defun'."
  (declare (debug defun) (doc-string 3) (indent 2))
  `(prog1
       (defun ,name ,arglist ,@body)
     (put ',name 'byte-optimizer 'byte-compile-inline-expand)))
;; purecopy: copy an object into pure space.  elisprs has no pure space, so this
;; returns its argument unchanged — observably equal to Emacs's result.
(defun purecopy (object)
  "Return a copy of OBJECT (identity — elisprs has no pure space)."
  object)
;; autoloadp / autoload: mark a symbol to load its defining file on first call
;; (subr.el `autoloadp'; C `Fautoload').  elisprs installs the autoload object
;; faithfully; the on-call load trigger is the autoload subsystem (not wired).
(defun autoloadp (object)
  "Non-nil if OBJECT is an autoload."
  (eq 'autoload (car-safe object)))
(defun autoload-do-load (fundef &optional funname macro-only)
  "If FUNDEF is an autoload form, load its file and return the new definition.
FUNNAME names the function being autoloaded; it must be defined by the file."
  (if (or (not (autoloadp fundef))
          (and (eq macro-only (quote macro))
               (not (memq (nth 4 fundef) (quote (t macro))))))
      fundef
    (let ((data (match-data)))
      (unwind-protect (load (car (cdr fundef)) nil t nil t)
        (set-match-data data)))
    (if (null funname)
        nil
      (let ((fun (indirect-function funname)))
        (if (equal fun fundef)
            (error "Autoloading file %s failed to define function %s"
                   (car (cdr fundef)) (symbol-name funname))
          fun)))))
(defun autoload (function file &optional docstring interactive type)
  "Define FUNCTION to autoload from FILE.
Does nothing if FUNCTION is already defined as something other than an
autoload.  Returns FUNCTION when it installs the autoload, else nil."
  (if (and (fboundp function)
           (not (autoloadp (symbol-function function))))
      nil
    (fset function (list 'autoload file docstring interactive type))
    function))
;; Advertised calling convention (byte-run.el:498).  Records the SIGNATURE a
;; function advertises to the byte-compiler; cl-generic's `cl-generic-define-method'
;; preserves a generic's advertised signature across redefinition.
(defvar advertised-signature-table (make-hash-table :test 'eq :weakness 'key))
(defun set-advertised-calling-convention (function signature _when)
  "Set the advertised SIGNATURE of FUNCTION."
  (puthash (indirect-function function) signature
           advertised-signature-table))
(defun get-advertised-calling-convention (function)
  "Get the advertised SIGNATURE of FUNCTION.
Return t if there isn't any."
  (gethash function advertised-signature-table t))
;; make-obsolete family (byte-run.el).  These only record properties the
;; byte-compiler reads to emit warnings; in the interpreter they are inert but
;; ported so obsolete declarations in real libraries load cleanly.
(defun byte-run--constant-obsolete-warning (obsolete-name)
  (if (memq obsolete-name '(nil t))
      (error "Can't make `%s' obsolete; did you forget a quote mark?"
             obsolete-name)))
(defun make-obsolete (obsolete-name current-name when)
  "Make the byte-compiler warn that function OBSOLETE-NAME is obsolete."
  (byte-run--constant-obsolete-warning obsolete-name)
  (put obsolete-name 'byte-obsolete-info
       (purecopy (list current-name nil when)))
  obsolete-name)
(defun make-obsolete-variable (obsolete-name current-name when &optional access-type)
  "Make the byte-compiler warn that OBSOLETE-NAME is obsolete."
  (byte-run--constant-obsolete-warning obsolete-name)
  (put obsolete-name 'byte-obsolete-variable
       (purecopy (list current-name access-type when)))
  obsolete-name)
(defmacro define-obsolete-function-alias (obsolete-name current-name when &optional docstring)
  "Set OBSOLETE-NAME's function definition to CURRENT-NAME and mark it obsolete."
  (declare (doc-string 4) (indent defun))
  `(progn
     (defalias ,obsolete-name ,current-name ,docstring)
     (make-obsolete ,obsolete-name ,current-name ,when)))
(defmacro define-obsolete-variable-alias (obsolete-name current-name when &optional docstring)
  "Make OBSOLETE-NAME a variable alias for CURRENT-NAME and mark it obsolete.
Uses `defvaralias' and `make-obsolete-variable' (byte-run.el)."
  (declare (doc-string 4) (indent defun))
  `(progn
     (defvaralias ,obsolete-name ,current-name ,docstring)
     ;; See Bug#4706.
     (dolist (prop '(saved-value saved-variable-comment))
       (and (get ,obsolete-name prop)
            (null (get ,current-name prop))
            (put ,current-name prop (get ,obsolete-name prop))))
     (make-obsolete-variable ,obsolete-name ,current-name ,when)))
;; eval-after-load (subr.el): register FORM to run after FILE loads; run now if
;; FILE (a feature symbol) is already provided.  The string-file regexp path and
;; the fire-on-future-load path are the after-load subsystem (not wired); the
;; feature-symbol registration path used by real libraries is faithful.
(defvar after-load-alist nil)
(defun eval-after-load (file form)
  "Arrange that if FILE is loaded, FORM will be run immediately afterwards."
  (declare (indent 1))
  (let* ((elt (assoc file after-load-alist))
         (func (if (functionp form) form (eval (list 'lambda nil form) t))))
    (unless elt
      (setq elt (list file))
      (push elt after-load-alist))
    (when (and (symbolp file) (featurep file))
      (funcall func))))
(defmacro with-eval-after-load (file &rest body)
  "Execute BODY after FILE is loaded (see `eval-after-load')."
  (declare (indent 1) (debug (form def-body)))
  (list 'eval-after-load file (list 'quote (cons 'progn body))))
;; def-edebug-elem-spec (subr.el): record an Edebug spec element as a property.
;; Edebug is advisory in elisprs, but real libraries register specs at load time.
(defun def-edebug-elem-spec (name spec)
  "Define a new Edebug spec element NAME as shorthand for SPEC."
  (declare (indent 1))
  (when (string-match "\\`[&:]" (symbol-name name))
    (error "Edebug spec name cannot start with '&' or ':'"))
  (unless (consp spec)
    (error "Edebug spec has to be a list: %S" spec))
  (put name 'edebug-elem-spec spec))
;; Declaration handler alists (byte-run.el).  Declared nil here (before the
;; handler functions exist) and populated further below; the host's defun/defmacro
;; expander consults them via `elisprs--expand-defun-declarations' to process
;; `(declare ...)' specs with runtime effect (gv-setter, obsolete, indent, …).
(defvar defun-declarations-alist nil)
(defvar macro-declarations-alist nil)
(defmacro defvar-local (var val &optional doc)
  (declare (debug defvar) (doc-string 3) (indent defun))
  `(progn (defvar ,var ,val ,doc) (make-variable-buffer-local ',var)))
(defmacro with-demoted-errors (fmt &rest body) (declare (debug t) (indent 1)) `(condition-case --err-- (progn ,@body) (error (message ,fmt --err--) nil)))

;; macroexp.el: `macroexp-progn'.  Defined this early because `setq-local' below
;; expands through it, and `setq-local' is used by functions defined long before
;; the rest of macroexp.el is.
(defun macroexp-progn (forms) (if (cdr forms) (cons 'progn forms) (car forms)))

;; subr.el (Emacs 31.1), verbatim.  A macro must be defined before the first
;; function body that uses it is compiled, or the use compiles as a call.
(defmacro setq-local (&rest pairs)
  "Make each VARIABLE local to current buffer and set it to corresponding VALUE.

The arguments are variable/value pairs.  For each VARIABLE in a pair,
make VARIABLE buffer-local in the current buffer and assign to it the
corresponding VALUE of the pair.  The VARIABLEs are literal symbols
and should not be quoted.

The VALUE of the Nth pair is not computed until after the VARIABLE
of the (N-1)th pair is set; thus, each VALUE can use the new VALUEs
of VARIABLEs set by earlier pairs.

The return value of the `setq-local' form is the VALUE of the last
pair.

In some corner cases you may need to resort to
`set-buffer-local-toplevel-value' instead, which see.

\(fn [VARIABLE VALUE]...)"
  (declare (debug setq))
  (unless (evenp (length pairs))
    (signal 'wrong-number-of-arguments (list 'setq-local (length pairs))))
  (let ((expr nil))
    (while pairs
      (unless (symbolp (car pairs))
        (error "Attempting to set a non-symbol: %s" (car pairs)))
      ;; Can't use backquote here, it's too early in the bootstrap.
      (setq expr
            (cons
             (list 'setq (car pairs)
                   (list 'prog1
                    (car (cdr pairs))
                    (list 'make-local-variable (list 'quote (car pairs)))))
             expr))
      (setq pairs (cdr (cdr pairs))))
    (macroexp-progn (nreverse expr))))

(defmacro save-match-data (&rest body)
  "Execute the BODY forms, restoring the global value of the match data.
The value returned is the value of the last form in BODY.
NOTE: The convention in Elisp is that any function, except for a few
exceptions like car/assoc/+/goto-char, can clobber the match data,
so `save-match-data' should normally be used to save *your* match data
rather than your caller's match data."
  ;; It is better not to use backquote here,
  ;; because that makes a bootstrapping problem
  ;; if you need to recompile all the Lisp files using interpreted code.
  (declare (indent 0) (debug t))
  (let ((saved-match-data (make-symbol "saved-match-data")))
    (list 'let
	  (list (list saved-match-data '(match-data)))
	  (list 'unwind-protect
	        (cons 'progn body)
	        (list 'set-match-data saved-match-data t)))))

;;; ====================================================================
;;; Standard library — subr / subr-x / seq / cl-lib written in elisp on
;;; top of the primitives, the way Emacs bootstraps. (Buffer/marker ops,
;;; floats→int, and function-cell introspection need host primitives and
;;; are not included.)
;;; ====================================================================

;;; ---- predicates ----
(defun booleanp (x) (if (or (eq x t) (eq x nil)) t nil))
(defun characterp (x) (and (integerp x) (>= x 0) (<= x #x3FFFFF)))
(defun sequencep (x) (or (listp x) (vectorp x) (stringp x) (char-table-p x) (bool-vector-p x)))
(defun arrayp (x) (or (vectorp x) (stringp x) (char-table-p x) (bool-vector-p x)))
(defun string-or-null-p (x) (or (null x) (stringp x)))
;; nlistp is a native subr (builtins.rs): a C subr in Emacs, same identity
;; requirement as natnump.
;; ROT13: rotate ASCII letters by 13, leaving everything else unchanged.
(defun rot13-string (string)
  (mapconcat (lambda (c)
               (char-to-string
                (cond ((and (>= c ?a) (<= c ?z)) (+ ?a (% (+ (- c ?a) 13) 26)))
                      ((and (>= c ?A) (<= c ?Z)) (+ ?A (% (+ (- c ?A) 13) 26)))
                      (t c))))
             (append string nil) ""))
;; elisprs has no symbols-with-position, so a symbol is always "bare".
(defun symbol-with-pos-p (_x) nil)
(defun bare-symbol (sym) sym)
(defun xor (a b) (cond ((not a) b) ((not b) a) (t nil)))
(defun proper-list-p (x)
  ;; Length if X is a proper (nil-terminated, acyclic) list, else nil. Floyd
  ;; cycle detection so a circular list returns nil instead of looping.
  (let ((slow x) (fast x) (n 0))
    (catch 'proper-list-p--done
      (while t
        (unless (consp fast) (throw 'proper-list-p--done (if (null fast) n nil)))
        (setq fast (cdr fast) n (1+ n))
        (unless (consp fast) (throw 'proper-list-p--done (if (null fast) n nil)))
        (setq fast (cdr fast) n (1+ n) slow (cdr slow))
        (when (eq fast slow) (throw 'proper-list-p--done nil))))))

;;; ---- numbers ----
;; `expt` is a primitive subr (integer power; float for fractional/negative exp).
(defun gcd (a b)
  (setq a (abs a)) (setq b (abs b))
  (while (> b 0) (let ((tmp b)) (setq b (% a b)) (setq a tmp)))
  a)
(defun lcm (a b) (if (or (= a 0) (= b 0)) 0 (/ (abs (* a b)) (gcd a b))))
(defun isqrt (n) (let ((r 0)) (while (<= (* (1+ r) (1+ r)) n) (setq r (1+ r))) r))
(defun cl-signum (x) (cond ((> x 0) 1) ((< x 0) -1) (t 0)))
;; cl-evenp/cl-oddp are byte-compiled in Emacs, where a wrong argument count is
;; caught by exec_byte_code and signalled as ((MANDATORY . NONREST) NARGS) —
;; (wrong-number-of-arguments (1 . 1) 2) — never as the function object. Take
;; &rest and reproduce that exact error shape; the interpreter's own arity
;; check would name this interpreted closure instead.
(defun cl-evenp (&rest args)
  (unless (= (length args) 1)
    (signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
  (let ((n (car args)))
    (unless (integerp n) (signal 'wrong-type-argument (list 'integer-or-marker-p n)))
    (= (% n 2) 0)))
(defun cl-oddp (&rest args)
  (unless (= (length args) 1)
    (signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
  (let ((n (car args)))
    (unless (integerp n) (signal 'wrong-type-argument (list 'integer-or-marker-p n)))
    (/= (% n 2) 0)))
;; Two-value division: each returns (QUOTIENT REMAINDER) where the remainder is
;; X - QUOTIENT*Y, matching the single-value floor/ceiling/truncate/round builtins.
;; cl-extra.el's two-value division family, ported verbatim. The exact
;; expressions matter, not just the values: which argument each one touches
;; first is what names the offender in a `wrong-type-argument'. `cl-truncate'
;; tests `(>= y 0)' before dividing, so `(cl-rem 1.0e+INF '(1 2))' is
;; `(wrong-type-argument number-or-marker-p (1 2))' and never the `integerp'
;; that a division-first implementation reaches.
;;
;; They also accept FLOATS, because they are the remainder half of `cl-floor' /
;; `cl-truncate': `(cl-rem 7.5 2)' is 1.5 and `(cl-mod -7.5 2)' is 0.5. Routing
;; them through `mod'/`%' — integer-only in elisp — signalled
;; `wrong-type-argument integer-or-marker-p 7.5' on every float.
(defun cl-floor (x &optional y)
  (let ((q (floor x y)))
    (list q (- x (if y (* y q) q)))))
(defun cl-ceiling (x &optional y)
  (let ((res (cl-floor x y)))
    (if (= (car (cdr res)) 0) res
      (list (1+ (car res)) (- (car (cdr res)) (or y 1))))))
(defun cl-truncate (x &optional y)
  (if (eq (>= x 0) (or (null y) (>= y 0)))
      (cl-floor x y) (cl-ceiling x y)))
(defun cl-round (x &optional y)
  (if y
      (if (and (integerp x) (integerp y))
          (let* ((hy (/ y 2))
                 (res (cl-floor (+ x hy) y)))
            (if (and (= (car (cdr res)) 0)
                     (= (+ hy hy) y)
                     (/= (% (car res) 2) 0))
                (list (1- (car res)) hy)
              (list (car res) (- (car (cdr res)) hy))))
        (let ((q (round (/ x y))))
          (list q (- x (* q y)))))
    (if (integerp x) (list x 0)
      (let ((q (round x)))
        (list q (- x q))))))
(defun cl-mod (x y) (nth 1 (cl-floor x y)))
(defun cl-rem (x y) (nth 1 (cl-truncate x y)))
;; The Euclid loops, verbatim. `(% a (setq a b))' reads the OLD `a' and then
;; rebinds it in the same expression, which is why `(cl-lcm "" 65535)' reports
;; `integer-or-marker-p ""' from `%' — an `abs'-first paraphrase reported
;; `number-or-marker-p' instead. `(/= b 0)' likewise tests B before touching A,
;; so `(cl-gcd 100 'car)' names `car' under `number-or-marker-p'.
(defun cl-gcd (&rest args)
  (let ((a (or (pop args) 0)))
    (dolist (b args)
      (while (/= b 0)
        (setq b (% a (setq a b)))))
    (abs a)))
(defun cl-lcm (&rest args)
  (if (memq 0 args)
      0
    (let ((a (or (pop args) 1)))
      (dolist (b args)
        (setq a (* (/ a (cl-gcd a b)) b)))
      (abs a))))
;; cl-extra.el `cl-coerce'.
(defun cl-coerce (x type)
  (cond ((eq type 'list) (if (listp x) x (append x nil)))
        ((eq type 'vector) (if (vectorp x) x (vconcat x)))
        ((eq type 'bool-vector)
         (if (bool-vector-p x) x (apply #'bool-vector (cl-coerce x 'list))))
        ((eq type 'string) (if (stringp x) x (concat x)))
        ((eq type 'array) (if (arrayp x) x (vconcat x)))
        ((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
        ((and (eq type 'character) (symbolp x))
         (cl-coerce (symbol-name x) type))
        ((eq type 'float) (float x))
        ((cl-typep x type) x)
        (t (error "Can't coerce %s to type %s" x type))))
(defvar cl--gensym-counter 0)
;; cl-macs.el: a string PREFIX replaces "G", an integer PREFIX is the number
;; itself (the counter is left alone), anything else is ignored.
(defun cl-gensym (&optional prefix)
  (let ((pfix (if (stringp prefix) prefix "G"))
        (num (if (integerp prefix) prefix
               (prog1 cl--gensym-counter
                 (setq cl--gensym-counter (1+ cl--gensym-counter))))))
    (make-symbol (format "%s%d" pfix num))))
(defvar cl--gentemp-counter 0)
;; cl-macs.el: an INTERNED symbol whose name no existing symbol has.
(defun cl-gentemp (&optional prefix)
  (let ((pfix (if (stringp prefix) prefix "T"))
        name)
    (while (intern-soft (setq name (format "%s%d" pfix cl--gentemp-counter)))
      (setq cl--gentemp-counter (1+ cl--gentemp-counter)))
    (intern name)))
(defun cl-digit-char-p (char &optional radix)
  (let ((r (or radix 10))
        (v (cond ((and (>= char ?0) (<= char ?9)) (- char ?0))
                 ((and (>= char ?a) (<= char ?z)) (+ 10 (- char ?a)))
                 ((and (>= char ?A) (<= char ?Z)) (+ 10 (- char ?A)))
                 (t nil))))
    (if (and v (< v r)) v nil)))
(defun cl-isqrt (n)
  (if (< n 2) n
    (let ((x n) (y (/ (+ n 1) 2)))
      (while (< y x) (setq x y y (/ (+ x (/ n x)) 2)))
      x)))
;; `string-to-number` is a primitive subr (floats, scientific notation, BASE arg).

;;; ---- key sequences (kbd) ----
;; Control-fold a character: letters/@A-Z[\]^_ map to 0–31, ? to 127, else the
;; control bit (2^26) is set.
(defun kbd--ctrl (c)
  (cond ((and (>= c ?a) (<= c ?z)) (- c 96))
        ((eq c ??) 127)
        ((and (>= c ?@) (<= c ?_)) (- c ?@))
        (t (logior c (ash 1 26)))))
;; Apply modifier flags to a character code (returns an int, possibly with
;; meta/shift/hyper/super/alt bits set).
(defun kbd--char (c ctrl meta shift hyper super alt)
  (when ctrl (setq c (kbd--ctrl c)))
  (when shift (setq c (logior c (ash 1 25))))
  (when hyper (setq c (logior c (ash 1 24))))
  (when super (setq c (logior c (ash 1 23))))
  (when alt (setq c (logior c (ash 1 22))))
  (when meta (setq c (logior c (ash 1 27))))
  c)
;; Build a function-key symbol, prefixing modifiers in Emacs's canonical
;; A-C-H-M-S-s order.
(defun kbd--sym (name ctrl meta shift hyper super alt)
  (when super (setq name (concat "s-" name)))
  (when shift (setq name (concat "S-" name)))
  (when meta (setq name (concat "M-" name)))
  (when hyper (setq name (concat "H-" name)))
  (when ctrl (setq name (concat "C-" name)))
  (when alt (setq name (concat "A-" name)))
  (intern name))
;; Parse one whitespace-delimited key token into a list of key codes/symbols.
(defun kbd--token (tok)
  (let ((ctrl nil) (meta nil) (shift nil) (hyper nil) (super nil) (alt nil)
        (i 0) (n (length tok)) (hadmod nil))
    (while (and (< (1+ i) n) (eq (aref tok (1+ i)) ?-) (memq (aref tok i) '(?C ?M ?S ?H ?s ?A)))
      (setq hadmod t)
      (let ((m (aref tok i)))
        (cond ((eq m ?C) (setq ctrl t)) ((eq m ?M) (setq meta t)) ((eq m ?S) (setq shift t))
              ((eq m ?H) (setq hyper t)) ((eq m ?s) (setq super t)) ((eq m ?A) (setq alt t))))
      (setq i (+ i 2)))
    (let* ((rest (substring tok i)) (rn (length rest))
           (named (cond ((string= rest "RET") 13) ((string= rest "TAB") 9) ((string= rest "SPC") 32)
                        ((string= rest "ESC") 27) ((string= rest "DEL") 127) ((string= rest "LFD") 10)
                        ((string= rest "NUL") 0) (t nil)))
           (anglesym (and (> rn 1) (eq (aref rest 0) ?<) (eq (aref rest (1- rn)) ?>))))
      (cond
       (anglesym (list (kbd--sym (substring rest 1 (1- rn)) ctrl meta shift hyper super alt)))
       (named (list (kbd--char named ctrl meta shift hyper super alt)))
       ;; A plain multi-character token is a sequence of single-character keys.
       ((and (not hadmod) (> rn 1)) (append rest nil))
       ((= rn 1) (list (kbd--char (aref rest 0) ctrl meta shift hyper super alt)))
       (t (list (kbd--sym rest ctrl meta shift hyper super alt)))))))
(defun kbd (keys)
  "Parse a key-description string into a key sequence (string or vector)."
  (let ((codes nil))
    (dolist (tok (split-string keys " " t))
      (setq codes (append codes (kbd--token tok))))
    (if (cl-every (lambda (c) (and (integerp c) (>= c 0) (<= c 127))) codes)
        (apply #'string codes)
      (vconcat codes))))

;;; ---- strings (ASCII) ----
;; Emacs's string comparators accept symbols too, using their print names.
(defun string--name (x) (if (symbolp x) (symbol-name x) x))
(defun string= (a b)
  ;; Emacs accepts a string or a symbol on either side and signals `stringp' on
  ;; anything else -- it does not quietly answer nil for, say, a float.
  (unless (or (stringp a) (symbolp a)) (signal 'wrong-type-argument (list 'stringp a)))
  (unless (or (stringp b) (symbolp b)) (signal 'wrong-type-argument (list 'stringp b)))
  (equal (string--name a) (string--name b)))
(defun string-equal (a b) (string= a b))
(defun string< (a b)
  ;; Like `string=': a string or a symbol on either side, `stringp' on anything
  ;; else — the first argument is checked first, so (string< 97 "a") names 97.
  (unless (or (stringp a) (symbolp a)) (signal 'wrong-type-argument (list 'stringp a)))
  (unless (or (stringp b) (symbolp b)) (signal 'wrong-type-argument (list 'stringp b)))
  (let ((la (string-to-list (string--name a))) (lb (string-to-list (string--name b)))
        (res nil) (done nil))
    (while (not done)
      (cond ((null la) (setq res (not (null lb))) (setq done t))
            ((null lb) (setq res nil) (setq done t))
            ((< (car la) (car lb)) (setq res t) (setq done t))
            ((> (car la) (car lb)) (setq res nil) (setq done t))
            (t (setq la (cdr la)) (setq lb (cdr lb)))))
    res))
(defun string-lessp (a b) (string< a b))
(defun string-greaterp (a b) (string< b a))
(defun string> (a b) (string< b a))
;; Collation: no locale support, so this is ordinary string order (with optional
;; case folding), matching the C-locale default.
(defun string-collate-lessp (s1 s2 &optional _locale ignore-case)
  (if ignore-case (string-lessp (downcase s1) (downcase s2)) (string-lessp s1 s2)))
(defun string-collate-equalp (s1 s2 &optional _locale ignore-case)
  (if ignore-case (string-equal (downcase s1) (downcase s2)) (string-equal s1 s2)))
;; doc.c `Ftext_quoting_style': `grave' and `straight' are taken as given; nil
;; and anything else are `curve' (startup sets `internal--text-quoting-flag' and
;; curved quotes are always displayable here).
(defvar text-quoting-style nil)
(defun text-quoting-style ()
  (cond ((eq text-quoting-style 'grave) 'grave)
        ((eq text-quoting-style 'straight) 'straight)
        (t 'curve)))
(defun string-reverse (s) (reverse s))
;; `upcase` / `downcase` are primitive subrs (accept a string or a character).
(defun char-or-string--check (s)
  (unless (or (stringp s) (integerp s))
    (signal 'wrong-type-argument (list 'char-or-string-p s)))
  s)
(defun capitalize (s)
  "Convert argument to capitalized form and return that.
This means that each word's first character is converted to either
title case or upper case, and the rest to lower case.
The argument may be a character or string.  The result has the same type."
  (char-or-string--check s)
  ;; A character argument cannot grow, so it takes the one-to-one path:
  ;; `(capitalize ?ß)' is ẞ, while `(capitalize "ß")' is "Ss".
  (if (integerp s) (--char-titlecase-1-- s) (--casify-capitalize-- s nil)))
(defun string-trim-left (s &optional regexp)
  ;; Strip a leading match of REGEXP (default whitespace).
  (let ((re (concat "\\`\\(?:" (or regexp "[ \t\n\r]+") "\\)")))
    (if (string-match re s) (substring s (match-end 0)) s)))
(defun string-trim-right (s &optional regexp)
  ;; Strip a trailing match of REGEXP (default whitespace).
  (let ((re (concat "\\(?:" (or regexp "[ \t\n\r]+") "\\)\\'")))
    (if (string-match re s) (substring s 0 (match-beginning 0)) s)))
(defun string-trim (s &optional trim-left trim-right)
  ;; subr-x: (string-trim-left (string-trim-right STRING TRIM-RIGHT) TRIM-LEFT)
  ;; -- the RIGHT trim runs first, so with two bad regexps the right one's
  ;; compile error wins: (string-trim "" "\\(" "[") => (invalid-regexp
  ;; "Unmatched [ or [^").
  (string-trim-left (string-trim-right s trim-right) trim-left))
;; Port of subr.el's Lisp definition (Emacs 31.1): `match-data--translate'
;; aims the match data at the matched substring. Re-matching REGEXP against the
;; substring lost the context a match can depend on -- `\\B' matched between
;; "a" and "b" fails on the one-character substring. Everything observable
;; falls out of the original:
;; `(length string)` rejects a non-sequence up front (`sequencep`), a nil
;; STRING flows through to `(substring nil 0 0)` (`arrayp nil`), REGEXP is only
;; type-checked/compiled when the loop runs (l > 0), REP may be a function and
;; is not looked at until a match happens, and `(< start l)` stops the
;; empty-regexp loop from appending one more replacement at end-of-string —
;; (replace-regexp-in-string "" "t" "-4.5") => "t-t4t.t5".
(defun replace-regexp-in-string (regexp rep string &optional fixedcase literal subexp start)
  (let ((l (length string))
        (start (or start 0))
        matches str mb me)
    (save-match-data
      (while (and (< start l) (string-match regexp string start))
        (setq mb (match-beginning 0)
              me (match-end 0))
        ;; If we matched the empty string, make sure we advance by one char
        (when (= me mb) (setq me (min l (1+ mb))))
        ;; Generate a replacement for the matched substring.
        ;; Operate on only the substring to minimize string consing.
        ;; Translate the match data so that it applies to the matched substring.
        (match-data--translate (- mb))
        (setq str (substring string mb me))
        (setq matches
              (cons (replace-match (if (stringp rep)
                                       rep
                                     (funcall rep (match-string 0 str)))
                                   fixedcase literal str subexp)
                    (cons (substring string start mb) ; unmatched prefix
                          matches)))
        (setq start me))
      ;; Reconstruct a string from the pieces.
      (setq matches (cons (substring string start l) matches)) ; leftover
      (apply #'concat (nreverse matches)))))
(defun string-blank-p (s) (string-match-p "\\`[ \t\n\r]*\\'" s))
(defun string-clean-whitespace (s)
  ;; Collapse internal whitespace runs to a single space and trim the ends.
  (string-trim (replace-regexp-in-string "[ \t\n\r]+" " " s)))
(defun string-truncate-left (string length)
  ;; If STRING is longer than LENGTH, keep the rightmost characters and prepend
  ;; "..." (so the result may exceed the original when LENGTH is <= 3).
  (let ((strlen (length string)))
    (if (<= strlen length)
        string
      (setq length (max 0 (- length 3)))
      (concat "..." (substring string (min (1- strlen)
                                           (max 0 (- strlen length))))))))
;; Verbatim subr-x: all argument rejection falls out of `string-prefix-p' /
;; `string-suffix-p' (whose `length' calls signal `sequencep'), so
;; (string-remove-prefix "..." nil) is nil when the prefix cannot fit.
(defun string-remove-prefix (prefix s)
  (if (string-prefix-p prefix s) (substring s (length prefix)) s))
(defun string-remove-suffix (suffix s)
  (if (string-suffix-p suffix s) (substring s 0 (- (length s) (length suffix))) s))

;;; ---- lists ----
(defun butlast (lst &optional n)
  ;; All but the last N elements of LST (default 1): (butlast '(1 2 3) 2) => (1).
  (setq n (or n 1))
  ;; subr.el: N <= 0 returns LST itself, UNVALIDATED -- (butlast 0 0) => 0.
  (if (<= n 0) lst
    (let ((keep (min (length lst) (- (length lst) n))) (r nil) (i 0))
      (while (< i keep) (setq r (cons (nth i lst) r)) (setq i (1+ i)))
      (reverse r))))
(defun nbutlast (lst &optional n)
  ;; Destructively drop the last N (default 1) elements.
  (let ((n (or n 1)) (len (length lst)))
    (cond ((<= len n) nil)
          ((<= n 0) lst)
          (t (setcdr (nthcdr (- len n 1) lst) nil) lst))))
(defun take (n lst)
  ;; fns.c Ftake: N must be an integer — a float or a symbol signals `integerp`,
  ;; not the `number-or-marker-p` a comparison would give.
  (unless (integerp n) (signal (quote wrong-type-argument) (list (quote integerp) n)))
  (let ((out nil))
    (while (and (> n 0) lst) (setq out (cons (car lst) out)) (setq lst (cdr lst)) (setq n (1- n)))
    (reverse out)))
(defun ntake (n lst) (take n lst))
(defun flatten-tree (tree)
  (cond ((null tree) nil)
        ((consp tree) (append (flatten-tree (car tree)) (flatten-tree (cdr tree))))
        (t (list tree))))
(defun flatten-list (tree) (flatten-tree tree))
(defun copy-tree (tree &optional vectors-and-records)
  "Make a copy of TREE.
If TREE is a cons cell, this recursively copies both its car and its cdr.
With VECTORS-AND-RECORDS non-nil, traverse and copy vectors and records too."
  ;; Ported from subr.el:877. The iterative cdr walk (rather than a plain
  ;; `(cons (copy-tree (car …)) (copy-tree (cdr …)))' recursion) is what keeps a
  ;; long list from recursing once per element, and it is the only shape that
  ;; copies a DOTTED tail correctly under VECTORS-AND-RECORDS.
  (if (consp tree)
      (let (result)
        (while (consp tree)
          (let ((newcar (car tree)))
            (if (or (consp (car tree))
                    (and vectors-and-records
                         (or (vectorp (car tree)) (recordp (car tree)))))
                (setq newcar (copy-tree (car tree) vectors-and-records)))
            (push newcar result))
          (setq tree (cdr tree)))
        (nconc (nreverse result)
               (if (and vectors-and-records (or (vectorp tree) (recordp tree)))
                   (copy-tree tree vectors-and-records)
                 tree)))
    (if (and vectors-and-records (or (vectorp tree) (recordp tree)))
        (let ((i (length (setq tree (copy-sequence tree)))))
          (while (>= (setq i (1- i)) 0)
            (aset tree i (copy-tree (aref tree i) vectors-and-records)))
          tree)
      tree)))
(defun copy-sequence (seq)
  (cond ((listp seq) (append seq nil))
        ;; A string and a vector copy into FRESH objects. Returning SEQ itself
        ;; was a silent wrong answer twice over: `(eq seq (copy-sequence seq))'
        ;; answered t where Emacs answers nil, and — worse — `aset' on the
        ;; "copy" wrote through to the original, so `copy-tree'/`cl-copy-list'
        ;; and every caller that copies before mutating shared one object.
        ;; Emacs's `copy-sequence' does); `vconcat' copies a vector's slots.
        ((stringp seq) (elisprs--copy-string seq))
        ((vectorp seq) (vconcat seq))
        ;; A record is copied slot-for-slot into a fresh record (slot 0, the type,
        ;; is reproduced): `(copy-sequence rec)' preserves record-ness, so it is the
        ;; copier a cl-defstruct `copy-NAME' uses.
        ((recordp seq)
         (let ((n (length seq)) (i 0) (args nil))
           (while (< i n) (setq args (cons (aref seq i) args) i (1+ i)))
           (apply #'record (nreverse args))))
        ;; A bool-vector copies to a fresh, independent bool-vector.
        ((bool-vector-p seq) (apply #'bool-vector (append seq nil)))
        ((char-table-p seq) (elisprs--copy-char-table seq))
        (t (signal 'wrong-type-argument (list 'sequencep seq)))))
(defun ensure-list (x) (if (listp x) x (list x)))
(defun mapcan (fn lst)
  ;; Fmapcan = mapcar then Fnconc, NOT append: results are spliced through
  ;; their last cons, so dotted results are legal -- (mapcan (lambda (x)
  ;; (cons x x)) (list -0.0 t)) => (-0.0 t . t) -- and a non-cons non-last
  ;; result signals `consp': (mapcan #'downcase (make-list 5 3)) =>
  ;; (wrong-type-argument consp 3).
  (apply (function nconc) (mapcar fn lst)))
(defun assoc-default (key alist &optional test default)
  ;; Faithful port of subr.el: each element (or its car) is compared to KEY via
  ;; (funcall (or TEST 'equal) ELEM KEY); on a hit return its cdr, else DEFAULT.
  (let (found (tail alist) value)
    (while (and tail (not found))
      (let ((elt (car tail)))
        (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
          (setq found t value (if (consp elt) (cdr elt) default))))
      (setq tail (cdr tail)))
    value))
(defun assoc-delete-all (key alist &optional test)
  ;; Faithful subr.el port (destructive, like rassq-delete-all): `(car alist)'
  ;; on a non-list signals listp naming it.
  (unless test (setq test #'equal))
  (while (and (consp (car alist)) (funcall test (car (car alist)) key))
    (setq alist (cdr alist)))
  (let ((tail alist) tail-cdr)
    (while (setq tail-cdr (cdr tail))
      (if (and (consp (car tail-cdr)) (funcall test (car (car tail-cdr)) key))
          (setcdr tail (cdr tail-cdr))
        (setq tail tail-cdr))))
  alist)
(defun assq-delete-all (key alist)
  ;; subr.el: assq-delete-all is assoc-delete-all with `eq'.
  (assoc-delete-all key alist #'eq))
;; Minimal completion API over a list (plain or alist), or a hash-table's keys.
;; (Function collections, obarrays, and completion-ignore-case are unsupported.)
(defun completion--str (e)
  (let ((c (if (consp e) (car e) e)))
    (cond ((symbolp c) (symbol-name c)) ((stringp c) c) (t (format "%s" c)))))
(defun completion--common-prefix (a b)
  (let ((n (min (length a) (length b))) (i 0))
    (while (and (< i n) (eq (aref a i) (aref b i))) (setq i (1+ i)))
    (substring a 0 i)))
(defun completion--elements (collection)
  (if (hash-table-p collection) (hash-table-keys collection) collection))
(defun all-completions (string collection &optional predicate)
  (let ((out nil))
    (dolist (e (completion--elements collection))
      (let ((c (completion--str e)))
        (when (and (string-prefix-p string c) (or (null predicate) (funcall predicate e)))
          (setq out (cons c out)))))
    (nreverse out)))
(defun try-completion (string collection &optional predicate)
  (let ((cands (all-completions string collection predicate)))
    (cond
     ((null cands) nil)
     ((and (null (cdr cands)) (string= (car cands) string)) t)
     (t (let ((common (car cands)))
          (dolist (c (cdr cands)) (setq common (completion--common-prefix common c)))
          common)))))
(defun test-completion (string collection &optional predicate)
  (let ((res nil))
    (dolist (e (completion--elements collection))
      (when (and (string= (completion--str e) string) (or (null predicate) (funcall predicate e)))
        (setq res t)))
    res))
(defun nreverse (seq)
  ;; Reverse a list in place by relinking its cons cells; other sequences copy.
  (if (listp seq)
      (let ((prev nil) (cur seq))
        (while (consp cur)
          (let ((next (cdr cur)))
            (setcdr cur prev)
            (setq prev cur cur next)))
        ;; Fnreverse's CHECK_LIST_END fires AFTER the relinking, so a dotted
        ;; tail signals listp naming the (already mutated) original head cons:
        ;; (nreverse (cons "p" 32)) => (wrong-type-argument listp ("p")).
        (when cur (signal 'wrong-type-argument (list 'listp seq)))
        prev)
    ;; Non-list: only arrays are reversible in place; else signal arrayp (Emacs).
    (if (arrayp seq) (reverse seq)
      (signal 'wrong-type-argument (list 'arrayp seq)))))

;;; ---- sort ----
;; `sort' itself is native: `host::call_function' intercepts it so PRED and :key
;; can re-enter elisp, and it handles the Emacs-30 keyword form and vectors,
;; neither of which the two-argument merge sort below ever did. Defining a Lisp
;; `sort' here only overwrote the subr's function cell, so `(func-arity 'sort)'
;; answered `(2 . 2)' where Emacs says `(1 . many)' and `(subrp (symbol-function
;; 'sort))' answered nil — while every actual call still went to the intercept.
;; The merge-sort helpers stay: `std--merge' is the stable merge other list code
;; uses directly.
(defun std--merge (a b pred)
  (cond ((null a) b)
        ((null b) a)
        ((funcall pred (car b) (car a)) (cons (car b) (std--merge a (cdr b) pred)))
        (t (cons (car a) (std--merge (cdr a) b pred)))))
(defun std--halves (lst)
  (let ((slow lst) (fast lst) (front nil))
    (while (and fast (cdr fast))
      (setq front (cons (car slow) front)) (setq slow (cdr slow)) (setq fast (cdr (cdr fast))))
    (cons (reverse front) slow)))

;;; ---- seq.el (list-oriented) ----
;; seq-generic: coerce to a list, then restore SEQ's own type (vector/string).
(defun seq-take (seq n)
  ;; seq.el: a list goes through `take`, whose N must be an integer; every other
  ;; sequence reaches a comparison first, which signals number-or-marker-p.
  ;; (seq-take nil 1.5) => integerp 1.5; (seq-take "abc" (quote x)) => number-or-marker-p x.
  (unless (listp seq)
    (unless (number-or-marker-p n) (signal (quote wrong-type-argument) (list (quote number-or-marker-p) n))))
  (if (or (stringp seq) (vectorp seq))
      (seq-subseq seq 0 (min (max n 0) (length seq)))
    (seq-into (take n (append seq nil)) (seq--type-of seq))))
(defun seq-drop (seq n)
  ;; seq.el: the list method is literally (nthcdr n list) -- so a non-integer
  ;; N signals `integerp' via nthcdr -- while other sequences go through the
  ;; generic (<= n 0) path, whose comparison signals number-or-marker-p:
  ;; (seq-drop '(1) "s") => integerp "s"; (seq-drop "abc" 's) =>
  ;; number-or-marker-p s.
  (if (listp seq)
      (nthcdr n seq)
    (if (<= n 0) seq
      (let ((len (seq-length seq)))
        (seq-subseq seq (min n len) len)))))
(defun seq-subseq (seq start &optional end)
  ;; Faithful seq.el: strings and vectors defer to `substring' (so a
  ;; non-integer index signals `integerp' and out-of-range signals
  ;; args-out-of-range); the list branch is subr.el's arithmetic walk, whose
  ;; out-of-range report is a plain `error'.
  (cond
   ((or (stringp seq) (vectorp seq)) (substring seq start end))
   ((listp seq)
    (let (len (orig-start start) (orig-end end))
      (and end (< end 0) (setq end (+ end (setq len (length seq)))))
      (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
      (unless (>= start 0)
        (error "Start index out of bounds: %s" orig-start))
      (when (> start 0)
        (setq seq (nthcdr (1- start) seq))
        (unless seq
          (error "Start index out of bounds: %s" orig-start))
        (setq seq (cdr seq)))
      (if end
          (let ((n (- end start)))
            (when (or (< n 0)
                      (if len
                          (> end len)
                        (and (> n 0) (null (nthcdr (1- n) seq)))))
              (error "End index out of bounds: %s" orig-end))
            (take n seq))
        (copy-sequence seq))))
   (t (error "Unsupported sequence: %s" seq))))
(defun seq-uniq (seq &optional testfn)
  (if (null testfn)
      (delete-dups (append seq nil))
    (let ((out nil))
      (dolist (x (append seq nil))
        (unless (let ((f nil)) (dolist (y out) (when (funcall testfn x y) (setq f t))) f)
          (setq out (cons x out))))
      (nreverse out))))
(defun seq-min (seq) (apply (function min) (append seq nil)))
(defun seq-max (seq) (apply (function max) (append seq nil)))
(defun seq-first (seq) (elt seq 0))
(defun seq-rest (seq) (seq-drop seq 1))
(defun seq-position (seq elt &optional testfn)
  (let ((test (or testfn #'equal)) (i 0) (res nil))
    (setq seq (append seq nil))
    (while (and seq (null res)) (if (funcall test (car seq) elt) (setq res i)) (setq seq (cdr seq)) (setq i (1+ i)))
    res))
(defun seq-into (seq type)
  ;; seq.el dispatches on TYPE with a `pcase' FIRST and only then touches
  ;; SEQUENCE (each arm calls its own `seq--into-*'), so an unknown TYPE is
  ;; reported even when SEQ is not a sequence at all:
  ;; (seq-into 0 'foo) => (error "Not a sequence type name: foo"), NOT
  ;; (wrong-type-argument sequencep 0). Coercing SEQ up front reversed that.
  ;; Each `seq--into-*' hands back SEQUENCE itself when it already has the
  ;; target type — (eq l (seq-into l 'list)) is t, and a dotted list is
  ;; returned whole rather than walked — and only converts otherwise.
  (cond ((eq type 'vector) (if (vectorp seq) seq (vconcat seq)))
        ((eq type 'string) (if (stringp seq) seq (concat seq)))
        ((eq type 'list) (if (listp seq) seq (append seq nil)))
        (t (error "Not a sequence type name: %S" type))))
(defun seq-difference (a b &optional testfn)
  (seq-filter (lambda (x) (not (seq-contains-p b x testfn))) a))
(defun seq-intersection (a b &optional testfn)
  (seq-filter (lambda (x) (seq-contains-p b x testfn)) a))
(defun seq-union (a b &optional testfn)
  ;; Emacs reduces an accumulator over both sequences, skipping an element it
  ;; already holds -- so duplicates *within* A are dropped too:
  ;; (seq-union '(1 1 2) '(2 3)) => (1 2 3), not (1 1 2 3).
  (let ((acc nil))
    (dolist (e (append a nil))
      (unless (seq-contains-p acc e testfn) (setq acc (cons e acc))))
    (dolist (e (append b nil))
      (unless (seq-contains-p acc e testfn) (setq acc (cons e acc))))
    (nreverse acc)))
(defun seq-sort (pred seq) (seq-into (sort (append seq nil) pred) (seq--type-of seq)))
(defun seq-partition (seq n)
  ;; Each chunk keeps SEQ's type (string→strings, vector→vectors, list→lists).
  ;; seq.el guards with (unless (< n 1)): N < 1 returns nil WITHOUT touching
  ;; SEQ at all -- (seq-partition 0 0) => nil, and (seq-partition "ab" 0) is
  ;; nil, not an infinite zero-progress loop.
  (unless (< n 1)
    (let ((out nil) (type (seq--type-of seq)) (l (append seq nil)))
      (while l
        (setq out (cons (seq-into (take n l) type) out))
        (setq l (nthcdr n l)))
      (reverse out))))
(defun seq-split (sequence length)
  ;; NOT an alias for `seq-partition': seq.el gives `seq-split' its own body, and
  ;; the guard is the opposite one. `seq-partition' returns nil for N < 1;
  ;; `seq-split' SIGNALS -- (seq-split '("a") 0) is
  ;; (error "Sub-sequence length must be larger than zero").
  (when (< length 1)
    (error "Sub-sequence length must be larger than zero"))
  (let ((result nil) (seq-length (length sequence)) (start 0))
    (while (< start seq-length)
      (setq result
            (cons (seq-subseq sequence start
                              (setq start (min seq-length (+ start length))))
                  result)))
    (nreverse result)))
(defun seq-set-equal-p (seq1 seq2 &optional testfn)
  (and (seq-every-p (lambda (x) (seq-contains-p seq2 x testfn)) seq1)
       (seq-every-p (lambda (x) (seq-contains-p seq1 x testfn)) seq2)))
(defun seq-into-sequence (seq)
  (if (sequencep seq) seq (error "Cannot convert %S into a sequence" seq)))
(defun seq-sort-by (fn pred seq)
  (seq-sort (lambda (a b) (funcall pred (funcall fn a) (funcall fn b))) seq))
(defun seq-positions (seq elt &optional testfn)
  (let ((test (or testfn 'equal)) (i 0) (out nil) (l (append seq nil)))
    (while l
      (when (funcall test (car l) elt) (setq out (cons i out)))
      (setq i (1+ i) l (cdr l)))
    (nreverse out)))
(defun seq-remove-at-position (sequence n)
  (seq-concatenate
   (if (listp sequence) (quote list) (type-of sequence))
   (seq-subseq sequence 0 n)
   (seq-subseq sequence (1+ n))))
(defun seq--type-of (seq)
  (cond ((listp seq) 'list) ((vectorp seq) 'vector) ((stringp seq) 'string) (t 'list)))
(defun seq-take-while (pred seq)
  ;; Leading run of SEQ for which PRED holds, returned as SEQ's own type.
  (let ((lst (append seq nil)) (acc nil) (go t))
    (while (and lst go)
      (if (funcall pred (car lst))
          (setq acc (cons (car lst) acc) lst (cdr lst))
        (setq go nil)))
    (seq-into (nreverse acc) (seq--type-of seq))))
(defun seq-drop-while (pred seq)
  ;; SEQ with its leading PRED-satisfying run removed, in SEQ's own type.
  (let ((lst (append seq nil)) (go t))
    (while (and lst go)
      (if (funcall pred (car lst)) (setq lst (cdr lst)) (setq go nil)))
    (seq-into lst (seq--type-of seq))))
(defun seq-contains (seq elt &optional testfn)
  ;; Deprecated in Emacs but still provided: returns the matching element.
  (let ((test (or testfn #'equal)) (l (append seq nil)) (res nil))
    (while (and l (null res))
      (when (funcall test elt (car l)) (setq res (car l)))
      (setq l (cdr l)))
    res))

;;; ---- cl-lib (subset) ----
(defun cl-mapcar (fn &rest seqs)
  (apply (function seq-mapn) fn (mapcar (lambda (s) (append s nil)) seqs)))
(defun cl-map (type fn &rest seqs)
  "Map FN over SEQS in parallel, collecting results into a sequence of TYPE.
TYPE nil maps for side effects only and returns nil."
  (let ((result (apply (function cl-mapcar) fn seqs)))
    (if (null type) nil (cl-coerce result type))))
(defun cl-subseq (seq start &optional end) (seq-subseq seq start end))
(defun cl-pairlis (the-keys the-values &optional alist)
  ;; Pair KEYS with VALUES (stopping at the shorter list), prepended to ALIST.
  (nconc (cl-mapcar 'cons the-keys the-values) alist))
(defun cl-remprop (symbol propname)
  ;; Remove the first PROPNAME/value pair from SYMBOL's plist; return t if one
  ;; was removed, else nil. Rebuilds the plist rather than splicing in place.
  (let ((plist (symbol-plist symbol)) (out nil) (found nil))
    (while plist
      (if (and (not found) (eq (car plist) propname))
          (setq found t)
        (setq out (append out (list (car plist) (car (cdr plist))))))
      (setq plist (cdr (cdr plist))))
    (when found (setplist symbol out))
    found))
(defun lax-plist-get (plist prop)
  (let ((res nil) (found nil))
    (while (and plist (not found))
      (if (equal (car plist) prop) (setq res (car (cdr plist)) found t)
        (setq plist (cdr (cdr plist)))))
    res))
(defun cl-tailp (sublist list)
  (let ((res nil))
    (while (and (consp list) (not res))
      (if (eq list sublist) (setq res t) (setq list (cdr list))))
    (or res (eq list sublist))))
(defun cl-ldiff (list sublist)
  (let ((res nil))
    (while (and (consp list) (not (eq list sublist)))
      (setq res (cons (car list) res) list (cdr list)))
    (nreverse res)))
(defun cl-getf (plist key &optional default)
  (let ((m (plist-member plist key))) (if m (cadr m) default)))
;; Remove the FIRST KEY/value pair from PLIST (eq comparison), like Emacs.
(defun cl--plist-remove-first (plist tag)
  (let ((out nil) (removed nil))
    (while plist
      (if (and (not removed) (eq (car plist) tag))
          (setq removed t)
        (setq out (cons (cadr plist) (cons (car plist) out))))
      (setq plist (cddr plist)))
    (nreverse out)))
(defmacro cl-remf (place tag)
  "Remove the property TAG from the plist stored in PLACE; return t if present."
  `(let ((--cl-remf-- (plist-member ,place ,tag)))
     (when --cl-remf-- (setf ,place (cl--plist-remove-first ,place ,tag)))
     (and --cl-remf-- t)))

;;; ---- subr-x macros ----
;; Build nested `(let ((VAR VAL)) (if VAR <inner> ELSE))` for a list of BINDINGS,
;; short-circuiting to ELSE the first time a bound value is nil.
(defun if-let--chain (bindings then else)
  (if (null bindings) then
    (let* ((b (car bindings))
           ;; Clause forms: SYMBOL (test its value), (SYMBOL VALUE) (bind+test),
           ;; or (VALUE) — a single-element list that is only tested, not bound.
           (test-only (and (consp b) (null (cdr b))))
           (var (cond ((not (consp b)) b)
                      (test-only (make-symbol "if-let"))
                      (t (car b))))
           (val (cond ((not (consp b)) b)
                      (test-only (car b))
                      (t (car (cdr b))))))
      (list 'let (list (list var val))
            (list 'if var (if-let--chain (cdr bindings) then else) else)))))
;; Accept the old single-binding spelling `(VAR VAL)` as well as a binding list.
(defun if-let--norm (spec)
  (if (and (consp spec) (symbolp (car spec))) (list spec) spec))
(defmacro if-let* (bindings then &rest else)
  (declare (indent 2))
  (if-let--chain bindings then (cons 'progn else)))
(defmacro when-let* (bindings &rest body)
  (declare (indent 1) (debug if-let*))
  (if-let--chain bindings (cons 'progn body) nil))
(defmacro if-let (bindings then &rest else)
  (declare (indent 2))
  (if-let--chain (if-let--norm bindings) then (cons 'progn else)))
(defmacro when-let (bindings &rest body)
  (declare (indent 1) (debug if-let))
  (if-let--chain (if-let--norm bindings) (cons 'progn body) nil))
(defmacro named-let (name bindings &rest body)
  ;; A self-recursive local loop: (named-let f ((i 0)) (if … (f (1+ i)) i)).
  (let ((vars (mapcar (function car) bindings))
        (vals (mapcar (lambda (b) (car (cdr b))) bindings)))
    `(progn (defun ,name ,vars ,@body) (,name ,@vals))))
;; cl-block / cl-return-from (cl-macs.el, 31.1): a LEXICALLY scoped escape. The
;; catch tag is a fresh cons bound to the variable `--cl-block-NAME--', so only
;; a `cl-return-from' written inside BODY can reach it: one in a function called
;; from BODY sees no such variable (`void-variable'), and a closure that outlives
;; its block throws to a tag no `catch' is waiting for (`no-catch'). A body with
;; no side effects drops the block outright, and the `cl--block-wrapper' compiler
;; macro (defined with `cl-define-compiler-macro', below) drops a block nothing
;; returns from. cl-return / cl-dolist / cl-dotimes use the nil block.
(defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
			    car-safe cdr-safe progn prog1 prog2))
(defconst cl--safe-funcs '(* / % length memq list vector vectorp
			  < > <= >= = error))
(defun cl--safe-expr-p (x)
  "Check if no side effects."
  (or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
      (and (symbolp (car x))
	   (or (memq (car x) cl--simple-funcs)
	       (memq (car x) cl--safe-funcs)
	       (get (car x) 'side-effect-free))
	   (progn
	     (while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
	     (null x)))))
;; cl-lib.el: `(defalias 'cl--block-wrapper #'identity)' and
;; `(defalias 'cl--block-throw #'throw)'; `defalias' is not defined yet here.
(fset 'cl--block-wrapper 'identity)
(fset 'cl--block-throw 'throw)
(defmacro cl-block (name &rest body)
  (declare (indent 1) (debug (symbolp body)))
  (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
    (let ((var (intern (format "--cl-block-%s--" name))))
      `(cl--block-wrapper
        ;; Build a unique "tag" in the form of a fresh cons.
        ;; We include `var' in the cons, just in case it help debugging.
        (let ((,var (cons ',var nil)))
         (catch ,var
           ,@body))))))
(defmacro cl-return-from (name &optional result)
  (declare (indent 1) (debug (symbolp &optional form)))
  (let ((name2 (intern (format "--cl-block-%s--" name))))
    `(cl--block-throw ,name2 ,result)))
(defmacro cl-return (&optional value) `(cl-return-from nil ,value))
(defmacro cl-dolist (spec &rest body) `(cl-block nil (dolist ,spec ,@body)))
(defmacro cl-dotimes (spec &rest body) `(cl-block nil (dotimes ,spec ,@body)))
(defmacro cl-pushnew (x place &rest _keys)
  ;; Add X to the front of PLACE unless already present (by eql). The place is
  ;; mentioned three times, so its subforms go through `setf--place-once' first.
  (let* ((xb (setf--bind1 x))
         (b (setf--place-once place))
         (p (cdr b))
         (xv (cdr xb)))
    (list 'let* (append (car xb) (car b))
          (list 'if (list 'memql xv p) p
                (list 'setf p (list 'cons xv p))))))
;;; ---- help.el usage/docstring helpers (help-add-fundoc-usage &c) ----
;; Faithful ports from lisp/help.el (30.2). cl-defgeneric/cl-defmethod expansion
;; in cl-generic.el calls `help-add-fundoc-usage' to append the "(fn ARGS)" line
;; to a method's docstring; these are the (formerly help-fns.el) helpers it needs.
(defun help--docstring-quote (string)
  "Return a doc string that represents STRING.
The result, when formatted by `substitute-command-keys', should equal STRING."
  (replace-regexp-in-string "['\\`‘’]" "\\\\=\\&" string))
(defun help--make-usage (function arglist)
  (cons (if (symbolp function) function 'anonymous)
        (mapcar (lambda (arg)
                  (cond
                   ;; Parameter name.
                   ((symbolp arg)
                    (let ((name (symbol-name arg)))
                      (cond
                       ((string-match "\\`&" name) (bare-symbol arg))
                       ((string-match "\\`_." name)
                        (intern (upcase (substring name 1))))
                       (t (intern (upcase name))))))
                   ;; Parameter with a default value (from cl-defgeneric etc).
                   ((and (consp arg)
                         (symbolp (car arg)))
                    (cons (intern (upcase (symbol-name (car arg)))) (cdr arg)))
                   ;; Something else.
                   (t arg)))
                arglist)))
;; (define-obsolete-function-alias 'help-make-usage ...) lives after `defalias'
;; is defined below — the alias body calls `defalias' at load time.
(defun help--make-usage-docstring (fn arglist)
  (let ((print-escape-newlines t))
    (help--docstring-quote (format "%S" (help--make-usage fn arglist)))))
;; `help-split-fundoc' is defined after `pcase' (below) since its body uses it
;; and elisprs expands macros at `defun'-definition time.
(defun help-add-fundoc-usage (docstring arglist)
  "Add the usage info to DOCSTRING.
If DOCSTRING already has a usage info, then just return it unchanged.
The usage info is built from ARGLIST.  DOCSTRING can be nil.
ARGLIST can also be t or a string of the form \"(FUN ARG1 ARG2 ...)\"."
  (unless (stringp docstring) (setq docstring ""))
  (if (or (string-match "\n\n(fn\\(\\( .*\\)?)\\)\\'" docstring)
          (eq arglist t))
      docstring
    (concat docstring
            (if (string-match "\n?\n\\'" docstring)
                (if (< (- (match-end 0) (match-beginning 0)) 2) "\n" "")
              "\n\n")
            (if (stringp arglist)
                (if (string-match "\\`[^ ]+\\(.*\\))\\'" arglist)
                    (concat "(fn" (match-string 1 arglist) ")")
                  (error "Unrecognized usage format"))
              (help--make-usage-docstring 'fn arglist)))))

;; cl-defstruct registries: --slots maps NAME -> full slot specs (read at
;; macroexpansion to inherit via :include); --parent maps child-tag -> parent-tag
;; (walked at runtime so a subtype satisfies a parent's predicate).
(defvar cl-struct--slots nil)
(defvar cl-struct--parent nil)
;; NAME -> index of its first slot: 1 for a named struct (a record, or a
;; `:type'd one with `:named'), 0 for an unnamed `:type list'/`:type vector'.
(defvar cl-struct--base nil)
;; NAME -> its `:type' option: `list', `vector', or nil for a record.  This is
;; cl-macs.el's `cl--struct-class-type', read by `cl-struct-sequence-type' and
;; `cl-struct-slot-info'.
(defvar cl-struct--type nil)
(defun cl-struct--is-a (tag target)
  (let ((res nil))
    (while (and tag (not res))
      (if (eq tag target) (setq res t) (setq tag (cdr (assq tag cl-struct--parent)))))
    res))
;; cl-defstruct: a struct is a record #s(NAME slot1 slot2 ...) whose slot 0 is the
;; bare type symbol NAME (so `type-of'/printing/`aref …0' all report NAME, exactly
;; like an Emacs record). Generates the `make-NAME' keyword constructor (with
;; per-slot defaults), `NAME-p' predicate, `NAME-SLOT' accessors (setf-able), and
;; `copy-NAME' copier. Parentage is tracked by bare NAME in `cl-struct--parent'.
(defmacro cl-defstruct (name-spec &rest slots)
  (declare (doc-string 2) (indent 1))
  ;; An optional docstring may precede the slot specs (cl-macs.el pops it via
  ;; `(if (stringp (car descs)) (pop descs))').  Record it on the struct's plist
  ;; and drop it so it is not mistaken for a slot.
  (let* ((--doc-- (and (stringp (car slots)) (car slots)))
         (slots (if --doc-- (cdr slots) slots))
         (name (if (consp name-spec) (car name-spec) name-spec))
         (sname (symbol-name name))
         ;; The record's slot-0 type tag is the bare struct NAME (Emacs records).
         (tag name)
         ;; Options: (:constructor NAME) renames the make-NAME constructor;
         ;; (:conc-name P) overrides the NAME- accessor prefix.
         ;; Constructors, as cl-macs.el reads the `:constructor' options in
         ;; order: `(:constructor NAME)' renames the keyword constructor (nil
         ;; suppresses it); `(:constructor NAME ARGLIST [DOC])' adds a BOA
         ;; constructor and, when NAME is the keyword constructor's name,
         ;; replaces it instead.  CTOR-OPTS is each option's `(cdr opt)'.
         (ctor-opts (let ((os nil))
                      (when (consp name-spec)
                        (dolist (opt (cdr name-spec))
                          (when (and (consp opt) (eq (car opt) :constructor))
                            (setq os (cons (cdr opt) os)))))
                      (reverse os)))
         ;; The keyword constructor's name, or nil when suppressed.
         (constructor (let ((c (intern (concat "make-" sname))))
                        (dolist (args ctor-opts)
                          (cond ((cdr args) (when (eq (car args) c) (setq c nil)))
                                (args (setq c (car args)))))
                        c))
         (conc (let ((p (concat sname "-")))
                 (when (consp name-spec)
                   (dolist (opt (cdr name-spec))
                     (when (and (consp opt) (eq (car opt) :conc-name))
                       (let ((v (car (cdr opt))))
                         (setq p (cond ((null v) "") ((symbolp v) (symbol-name v)) (t v)))))))
                 p))
         ;; (:copier NAME) renames the copy-NAME copier; (:copier nil) suppresses it.
         (copier (let ((c (concat "copy-" sname)))
                   (when (consp name-spec)
                     (dolist (opt (cdr name-spec))
                       (when (and (consp opt) (eq (car opt) :copier))
                         (setq c (and (car (cdr opt)) (symbol-name (car (cdr opt))))))))
                   c))
         ;; (:predicate NAME) renames the NAME-p predicate.
         (pred (let ((c (concat sname "-p")))
                 (when (consp name-spec)
                   (dolist (opt (cdr name-spec))
                     (when (and (consp opt) (eq (car opt) :predicate) (car (cdr opt)))
                       (setq c (symbol-name (car (cdr opt)))))))
                 c))
         ;; (:include PARENT) inherits PARENT's slots (prepended, same order) and
         ;; records the tag parentage so the predicate accepts subtypes.
         (parent (let ((p nil))
                   (when (consp name-spec)
                     (dolist (opt (cdr name-spec))
                       (when (and (consp opt) (eq (car opt) :include))
                         (setq p (car (cdr opt))))))
                   p))
         ;; (:type list)/(:type vector) select an untagged list or vector
         ;; representation instead of a record; a bare `:named' in the options
         ;; puts the type symbol back in slot 0.  A record is always named, so
         ;; without `:type' both of these are fixed.  cl-macs.el only generates
         ;; a predicate for a named struct, and only a named struct's slots are
         ;; offset by the tag -- BASE is that offset, and it is what makes an
         ;; unnamed `(:type list)' accessor `(nth 0 x)' rather than `(nth 1 x)'.
         (stype (let ((ty nil))
                  (when (consp name-spec)
                    (dolist (opt (cdr name-spec))
                      (when (and (consp opt) (eq (car opt) :type))
                        (setq ty (car (cdr opt))))))
                  ty))
         (named (or (null stype)
                    (and (consp name-spec) (memq :named (cdr name-spec)) t)))
         (base (if named 1 0))
         (parent-slots (and parent (boundp 'cl-struct--slots)
                            (cdr (assq parent cl-struct--slots))))
         (all-slots (append parent-slots slots))
         (snames (mapcar (lambda (s) (if (consp s) (car s) s)) all-slots))
         (defaults (mapcar (lambda (s) (if (consp s) (car (cdr s)) nil)) all-slots))
         ;; Per-slot options plist is (cddr SLOT): (:type T :read-only R :documentation D).
         ;; `:type'/`:documentation' are parsed and ignored for storage (Emacs does
         ;; not enforce :type at runtime); `:read-only' non-nil makes the slot's
         ;; setf-expander error, matching cl-macs.el:3257.
         (readonly (mapcar (lambda (s) (and (consp s) (plist-get (cdr (cdr s)) :read-only)))
                           all-slots))
         ;; cl-macs.el's DESCS: every slot as a `(NAME DEFAULT . OPTS)' spec,
         ;; led by the tag slot of a named struct.  A constructor's lambda list
         ;; carries it as `&cl-defs (nil . DESCS)', which is how an argument
         ;; named like a slot defaults to that slot's initform.
         (descs (append (and named '((cl-tag-slot)))
                        (mapcar (lambda (s) (if (consp s) s (list s))) all-slots)))
         ;; Every constructor as `(NAME ARGLIST DOC)': the BOA constructors in
         ;; option order, then the keyword constructor over all slots.
         (constrs (let ((cs nil))
                    (dolist (args ctor-opts)
                      (when (cdr args) (setq cs (cons args cs))))
                    (when constructor
                      (setq cs (cons (list constructor (cons '&key (copy-sequence snames))) cs)))
                    cs))
         (forms nil)
         ;; How an instance is built and how slot J is read and written.
         (build (cond ((eq stype 'list) 'list) ((eq stype 'vector) 'vector) (t 'record)))
         (tag-args (if named (list (list 'quote tag)) nil)))
    ;; Record this struct's full (inherited + own) slot specs at macroexpansion
    ;; time so a later (:include this) can read them.
    (setq cl-struct--slots (cons (cons name all-slots) cl-struct--slots))
    (setq cl-struct--base (cons (cons name base) cl-struct--base))
    (setq cl-struct--type (cons (cons name stype) cl-struct--type))
    ;; cl-macs.el: a constructor is a `cl-defun' whose lambda list is the
    ;; option's (or `&key' over every slot for the keyword constructor) behind
    ;; `&cl-defs (nil . DESCS)'.  `cl--transform-lambda' then gives it Emacs's
    ;; argument semantics: an unsupplied argument named like a slot takes that
    ;; slot's initform, evaluated only then and in slot order (so an initform
    ;; may read an earlier slot); an unknown or value-less keyword signals
    ;; unless `&allow-other-keys'; `&optional (b 7)', `&rest', `&key' and
    ;; `&aux' mean what they do in any cl lambda list.  A slot that is not an
    ;; argument is filled from its initform.  (cl-macs.el uses `cl-defsubst'
    ;; unless `:noinline'; elisprs has no `cl-defsubst', so the constructor is
    ;; never inlined and behaves as `(funcall #'make-NAME ...)' does in Emacs.)
    (dolist (constr constrs)
      (let* ((cname (nth 0 constr)) (args (nth 1 constr)) (doc (nth 2 constr))
             (anames (cl--arglist-args args))
             (make (let ((ms nil) (sn snames) (df defaults))
                     (while sn
                       (setq ms (cons (if (memq (car sn) anames) (car sn) (car df)) ms))
                       (setq sn (cdr sn) df (cdr df)))
                     (reverse ms))))
        (setq forms
              (cons `(cl-defun ,cname (&cl-defs (nil ,@descs) ,@args)
                       ,(if (stringp doc) doc
                          (format "Constructor for objects of type `%s'." name))
                       ,@(if (cl--safe-expr-p `(progn ,@defaults))
                             '((declare (side-effect-free t))))
                       (,build ,@tag-args ,@make))
                    forms))))
    ;; cl-macs.el generates a predicate only for a NAMED struct: an unnamed
    ;; `(:type list)' instance carries nothing to recognize it by, so
    ;; `(fboundp 'NAME-p)' is nil in Emacs and must be here too.
    (when named
      ;; cl-macs.el registers the predicate as the atomic type's test.
      (setq forms (cons `(define-symbol-prop ',name 'cl-deftype-satisfies ',(intern pred)) forms))
      (setq forms
            (cons (cond
                   ((eq stype 'list)
                    `(defun ,(intern pred) (--o--)
                       (and (consp --o--) (cl-struct--is-a (car --o--) ',tag))))
                   ((eq stype 'vector)
                    `(defun ,(intern pred) (--o--)
                       (and (vectorp --o--) (> (length --o--) 0)
                            (cl-struct--is-a (aref --o-- 0) ',tag))))
                   (t
                    `(defun ,(intern pred) (--o--)
                       (and (recordp --o--) (> (length --o--) 0)
                            (cl-struct--is-a (aref --o-- 0) ',tag)))))
                  forms)))
    ;; Record the tag's parent so the predicate accepts subtypes.  With an
    ;; explicit `:include' the parent is that struct; otherwise every "normal"
    ;; struct implicitly roots at `cl-structure-object' (cl-macs.el defaults
    ;; `parent-type' to it), which is what makes `cl-struct-p' — the predicate
    ;; for `cl-structure-object' — accept any struct.  The root itself is skipped
    ;; so it has no self-parent.
    (let ((ptag (cond (parent parent)
                      ((not (eq name 'cl-structure-object)) 'cl-structure-object))))
      (when ptag
        (setq forms (cons `(setq cl-struct--parent
                                 (cons (cons ',tag ',ptag) cl-struct--parent))
                          forms))))
    (when copier
      (setq forms (cons `(defun ,(intern copier) (--s--) (copy-sequence --s--)) forms)))
    ;; Register a `cl-structure-class' so cl-generic's typeof generalizer can
    ;; dispatch on this struct type (cl-preloaded.el:205).  Guarded so the many
    ;; structs defined before the class registry is bootstrapped are skipped.
    (setq forms
          (cons `(when (and (fboundp 'cl--struct-new-class)
                            (cl--find-class 'cl-structure-object))
                   (put ',name 'cl--class
                        (cl--struct-new-class
                         ',name ,--doc--
                         (list (or ,(if parent `(cl--find-class ',parent))
                                   (cl--find-class 'cl-structure-object)))
                         nil nil nil nil nil nil nil)))
                forms))
    (let ((j base) (ros readonly))
      (dolist (sn snames)
        (let ((acc (intern (concat conc (symbol-name sn)))))
          (setq forms (cons (if (eq stype 'list)
                                `(defun ,acc (--s--) (nth ,j --s--))
                              `(defun ,acc (--s--) (aref --s-- ,j)))
                            forms))
          ;; A list-typed slot's setter is `(setcar (nthcdr J S) V)', not `aset',
          ;; so the two representations need separate registries for `setf'.
          (setq forms (cons (if (eq stype 'list)
                                `(setq cl-struct--slot-list-index
                                       (cons (cons ',acc ,j) cl-struct--slot-list-index))
                              `(setq cl-struct--slot-index
                                     (cons (cons ',acc ,j) cl-struct--slot-index)))
                            forms))
          (when (car ros)
            (setq forms (cons `(setq cl-struct--slot-readonly
                                     (cons ',acc cl-struct--slot-readonly))
                              forms))))
        (setq ros (cdr ros))
        (setq j (1+ j))))
    `(progn ,@(reverse forms) ',name)))
;; Generic struct-slot introspection (cl-macs.el).  Slots are stored as bare
;; symbols (no default) or `(NAME DEFAULT . OPTS)' specs; CL-STRUCT--BASE is the
;; index of the first one.  An unknown STRUCT-TYPE is `cl--struct-get-class''s
;; "%S is not a struct name" error.
(defun cl-struct--slots-of (struct-type)
  (let ((e (assq struct-type cl-struct--slots)))
    (unless e (error "%S is not a struct name" struct-type))
    (cdr e)))
(defun cl-struct-sequence-type (struct-type)
  "Return the sequence used to build STRUCT-TYPE: `vector', `list', or nil."
  (cl-struct--slots-of struct-type)
  (cdr (assq struct-type cl-struct--type)))
(defun cl-struct-slot-offset (struct-type slot-name)
  (let ((slots (cl-struct--slots-of struct-type))
        (i (or (cdr (assq struct-type cl-struct--base)) 1))
        (idx nil))
    (dolist (s slots)
      (when (eq (if (consp s) (car s) s) slot-name) (setq idx i))
      (setq i (1+ i)))
    (or idx (signal 'cl-struct-unknown-slot (list struct-type slot-name)))))
(defun cl-struct-slot-value (struct-type slot-name inst)
  (aref inst (cl-struct-slot-offset struct-type slot-name)))
;; A record's info starts with the bare `(cl-tag-slot)' entry; a `:named'
;; `:type'd struct carries the tag as a real slot, `(cl-tag-slot nil)'; an
;; unnamed one has no tag entry at all.
(defun cl-struct-slot-info (struct-type)
  (let ((slots (mapcar (lambda (s) (if (consp s) s (list s nil)))
                       (cl-struct--slots-of struct-type))))
    (cond ((null (cdr (assq struct-type cl-struct--type))) (cons '(cl-tag-slot) slots))
          ((eq (cdr (assq struct-type cl-struct--base)) 1) (cons '(cl-tag-slot nil) slots))
          (t slots))))
(defmacro and-let* (bindings &rest body)
  (declare (indent 1) (debug if-let*))
  ;; Like when-let* but with no body returns the last bound value (SRFI-2).
  (if (null bindings)
      (cons 'let* (cons nil (or body '(t))))
    (if-let--chain bindings
                   (if body (cons 'progn body)
                     (let ((lastb (car (last bindings))))
                       (if (consp lastb) (car lastb) lastb)))
                   nil)))
;; let-alist (lisp/emacs-lisp/let-alist.el): bind every `.KEY' symbol in BODY to
;; the corresponding value in ALIST.  A DOTTED CHAIN descends: `.a.b.c' reads
;; (cdr (assq 'c (cdr (assq 'b (cdr (assq 'a ALIST)))))), so an intermediate
;; that is not a list signals `listp' rather than answering nil.  A name with a
;; SECOND leading dot escapes the mechanism: `..a' is the ordinary symbol `.a'.
(defun let-alist--dots (form acc)
  (cond
   ((and (symbolp form) form)
    (let ((n (symbol-name form)))
      (if (and (> (length n) 1) (eq (aref n 0) ?.) (not (memq form acc)))
          (cons form acc) acc)))
   ((consp form)
    (if (eq (car form) 'quote) acc
      (let-alist--dots (cdr form) (let-alist--dots (car form) acc))))
   (t acc)))
(defun let-alist--remove-dot (symbol)
  "SYMBOL without its leading dot."
  (let ((name (symbol-name symbol)))
    (if (string-prefix-p "." name) (intern (substring name 1)) symbol)))
(defun let-alist--list-to-sexp (list var)
  "Turn the key LIST into nested `(cdr (assq KEY ...))' reads of VAR."
  (list 'cdr (list 'assq (list 'quote (car list))
                   (if (cdr list) (let-alist--list-to-sexp (cdr list) var) var))))
(defun let-alist--access-sexp (symbol variable)
  "The form that reads SYMBOL's value out of VARIABLE."
  (let* ((clean (let-alist--remove-dot symbol))
         (name (symbol-name clean)))
    ;; Still dotted after removing one: `..a' means the plain symbol `.a'.
    (if (string-prefix-p "." name)
        clean
      (let-alist--list-to-sexp
       (mapcar #'intern (nreverse (split-string name "[.]"))) variable))))
(defmacro let-alist (alist &rest body)
  (let ((var (make-symbol "alist")))
    (list 'let (list (list var alist))
          (cons 'let
                (cons (mapcar (lambda (d) (list d (let-alist--access-sexp d var)))
                              (let-alist--dots body nil))
                      body)))))
;; cl-flet / cl-labels: lexical local functions. Rewrite calls to a NAME and
;; #'NAME in BODY into `funcall'/refs of a let-bound lambda. cl-labels also walks
;; the function bodies (so they can recurse / call each other) and binds via
;; setq so the lambdas capture the (by-reference) gensym vars.
;; Drop NAMES from ALIST — the local-function bindings a nested binding form
;; shadows for the extent of its body.
(defun cl-flet--shadow (alist names)
  (let ((out nil))
    (dolist (a alist) (unless (memq (car a) names) (setq out (cons a out))))
    (reverse out)))
(defun cl-flet--walk (form alist)
  (cond
   ((not (consp form)) form)
   ((eq (car form) 'quote) form)
   ((eq (car form) 'function)
    (let ((a (assq (car (cdr form)) alist)))
      (if a (cdr a) form)))
   ;; A nested cl-flet/cl-flet*/cl-labels rebinds function names. Two things must
   ;; happen that the generic descent got wrong:
   ;;   1. its BINDING LIST is not a list of call sites. `(cl-flet ((f (n) …)) …)'
   ;;      nested inside an outer `cl-flet' binding `f' had its own binding head
   ;;      rewritten to `(funcall G_outer (n) …)', which then failed to compile
   ;;      with "malformed lambda list".
   ;;   2. the names it binds SHADOW ours inside it, so calls in its body must be
   ;;      left for the nested form's own walk to rewrite.
   ;; A `cl-flet' binding's body sees the OUTER functions (the new names are not
   ;; in scope yet); a `cl-labels' binding's body sees the inner ones, so it can
   ;; recurse.
   ((memq (car form) '(cl-flet cl-flet* cl-labels))
    (let* ((binds (car (cdr form)))
           (names (mapcar (function car) binds))
           (inner (cl-flet--shadow alist names))
           (bind-scope (if (eq (car form) 'cl-labels) inner alist)))
      (cons (car form)
            (cons (mapcar (lambda (b) (cons (car b) (cl-flet--walk (cdr b) bind-scope))) binds)
                  (cl-flet--walk (cdr (cdr form)) inner)))))
   ((and (symbolp (car form)) (assq (car form) alist))
    (cons 'funcall (cons (cdr (assq (car form) alist)) (cl-flet--walk (cdr form) alist))))
   (t (cons (cl-flet--walk (car form) alist) (cl-flet--walk (cdr form) alist)))))
(defun cl-flet--cl-argp (arglist)
  ;; Non-nil when ARGLIST uses cl-lambda-list features a plain `lambda' can't
  ;; take: per-arg defaults (cons elements) or &key/&aux/&whole/&allow-other-keys.
  (let ((cl nil))
    (while (consp arglist)
      (when (or (consp (car arglist))
                (memq (car arglist) '(&key &aux &whole &allow-other-keys)))
        (setq cl t))
      (setq arglist (cdr arglist)))
    cl))
(defun cl-flet--lambda (spec)
  ;; SPEC is (ARGLIST . BODY). Build the local-function lambda, routing through
  ;; `cl-destructuring-bind' when ARGLIST needs full cl-lambda-list handling
  ;; (matching Emacs cl-flet/cl-labels, which accept cl-lambda-lists).
  (if (cl-flet--cl-argp (car spec))
      (list 'lambda '(&rest --cl-flet-args--)
            (cons 'cl-destructuring-bind
                  (cons (car spec) (cons '--cl-flet-args-- (cdr spec)))))
    (cons 'lambda spec)))
(defun cl-flet--binding-value (spec)
  ;; SPEC is (cdr BINDING).  Per cl-macs.el:2098, a length-1 SPEC is the
  ;; `(FUNC EXP)' form: EXP is an expression returning the function value to
  ;; bind (used by cl-generic's `(cl-flet ((cl-call-next-method CNM)) ...)').
  ;; Otherwise SPEC is `(ARGLIST BODY...)', shorthand for a local lambda.
  (if (= (length spec) 1)
      (car spec)
    (cl-flet--lambda spec)))
(defmacro cl-flet (bindings &rest body)
  (let* ((gs (mapcar (lambda (b) (make-symbol (symbol-name (car b)))) bindings))
         (alist (cl-mapcar (lambda (b g) (cons (car b) g)) bindings gs)))
    `(let ,(cl-mapcar (lambda (b g) (list g (cl-flet--binding-value (cdr b)))) bindings gs)
       ,@(cl-flet--walk body alist))))
(defmacro cl-flet* (bindings &rest body)
  ;; Sequential cl-flet: each local function sees the earlier ones.
  (if (null bindings)
      (cons 'progn body)
    `(cl-flet (,(car bindings)) (cl-flet* ,(cdr bindings) ,@body))))
(defmacro cl-labels (bindings &rest body)
  (let* ((gs (mapcar (lambda (b) (make-symbol (symbol-name (car b)))) bindings))
         (alist (cl-mapcar (lambda (b g) (cons (car b) g)) bindings gs)))
    `(let ,(mapcar (lambda (g) (list g nil)) gs)
       ,@(cl-mapcar (lambda (b g) (list 'setq g (cl-flet--binding-value (cl-flet--walk (cdr b) alist)))) bindings gs)
       ,@(cl-flet--walk body alist))))
;; cl-macrolet: local macros. Expand calls to them throughout BODY at expansion
;; time (re-walking each expansion), then leave the rest for the normal pass.
(defun cl-macrolet--walk (form expanders)
  (cond
   ((not (consp form)) form)
   ((eq (car form) 'quote) form)
   ((and (symbolp (car form)) (assq (car form) expanders))
    (cl-macrolet--walk (apply (cdr (assq (car form) expanders)) (cdr form)) expanders))
   (t (cons (cl-macrolet--walk (car form) expanders)
            (cl-macrolet--walk (cdr form) expanders)))))
(defmacro cl-macrolet (bindings &rest body)
  ;; eval each local-macro lambda into a real closure (apply needs a closure,
  ;; not a raw lambda list), then expand calls to them in BODY.
  (let ((expanders (mapcar (lambda (b) (cons (car b) (eval (cons 'lambda (cdr b)) t))) bindings)))
    (cons 'progn (cl-macrolet--walk body expanders))))
;; cl-symbol-macrolet: substitute each NAME with its EXPANSION in value position
;; throughout BODY; `(setq NAME v)` becomes `(setf EXPANSION v)`. (No shadowing
;; handling — don't rebind a symbol-macro name with let inside the body.)
(defun cl-symbol-macrolet--setq (pairs alist)
  (when pairs
    (let* ((sym (car pairs)) (a (assq sym alist)) (place (if a (car (cdr a)) sym)))
      (cons place (cons (cl-symbol-macrolet--walk (car (cdr pairs)) alist)
                        (cl-symbol-macrolet--setq (cdr (cdr pairs)) alist))))))
(defun cl-symbol-macrolet--walk (form alist)
  (cond
   ((symbolp form) (let ((a (assq form alist))) (if a (car (cdr a)) form)))
   ((not (consp form)) form)
   ((eq (car form) 'quote) form)
   ((eq (car form) 'setq) (cons 'setf (cl-symbol-macrolet--setq (cdr form) alist)))
   (t (cons (cl-symbol-macrolet--walk (car form) alist)
            (cl-symbol-macrolet--walk (cdr form) alist)))))
(defmacro cl-symbol-macrolet (bindings &rest body)
  (cons 'progn (cl-symbol-macrolet--walk body bindings)))
(defmacro letrec (bindings &rest body)
  (declare (debug let) (indent 1))
  ;; Bind to nil, then assign — so the (by-reference) closures can recurse / refer
  ;; to each other.
  `(let ,(mapcar (lambda (b) (list (car b) nil)) bindings)
     ,@(mapcar (lambda (b) (list 'setq (car b) (car (cdr b)))) bindings)
     ,@body))
(defmacro dlet (bindings &rest body)
  (declare (indent 1) (debug let))
  ;; Dynamic let. (No buffer-local distinction here, so a plain `let'.)
  `(let ,bindings ,@body))
(defmacro cl-letf (bindings &rest body)
  ;; Temporarily set generalized places, restoring them on exit. Each binding is
  ;; (PLACE [VALUE]); with no VALUE the place is just saved and restored.
  ;;
  ;; cl-macs.el special-cases a PLAIN SYMBOL place to an ordinary `let' binding,
  ;; and that case has to stay a `let': saving the old value first means READING
  ;; the symbol, so `(cl-letf ((x 1)) x)' on an unbound `x' signalled
  ;; `void-variable x' instead of answering 1. Symbol places are split out here
  ;; and bound directly; only generalized places take the save/set/restore path.
  (let ((simple nil) (general nil))
    (dolist (b bindings)
      (if (symbolp (car b)) (setq simple (cons b simple)) (setq general (cons b general))))
    (setq simple (reverse simple) general (reverse general))
    (let ((olds (mapcar (lambda (_b) (make-symbol "old")) general))
          (saves nil) (sets nil) (restores nil))
      (cl-mapcar (lambda (b o)
                   (setq saves (cons (list o (car b)) saves))
                   (when (cdr b) (setq sets (cons (list 'setf (car b) (car (cdr b))) sets)))
                   (setq restores (cons (list 'setf (car b) o) restores)))
                 general olds)
      (let ((core (if general
                      `(let ,(reverse saves)
                         (unwind-protect (progn ,@(reverse sets) ,@body)
                           ,@(reverse restores)))
                    `(progn ,@body))))
        (if simple `(let ,simple ,core) core)))))
(defmacro cl-letf* (bindings &rest body)
  ;; Sequential cl-letf: each binding's place is set before the next is saved.
  (if (null bindings)
      `(progn ,@body)
    `(cl-letf (,(car bindings)) (cl-letf* ,(cdr bindings) ,@body))))
(defmacro thread-first (x &rest forms)
  (let ((acc x))
    (while forms
      (let ((form (car forms)))
        (setq acc (if (consp form) (cons (car form) (cons acc (cdr form))) (list form acc))))
      (setq forms (cdr forms)))
    acc))
(defmacro thread-last (x &rest forms)
  (let ((acc x))
    (while forms
      (let ((form (car forms)))
        (setq acc (if (consp form) (append form (list acc)) (list form acc))))
      (setq forms (cdr forms)))
    acc))

;;; ---- more cl-lib / seq / subr-x / functional ----
;; cl-lib.el: a plain-variable place goes straight to `setq', and an omitted
;; increment uses `1+'/`1-' rather than `(+ PLACE 1)'. Routing everything through
;; `setf' printed `(progn (setq x (+ x 1)))' where Emacs prints `(setq x (1+ x))'.
;; cl-macs.el emits `1+'/`1-' for the no-DELTA symbol case, which is what
;; `(macroexpand '(cl-incf x))' => `(setq x (1+ x))' pins. Every other case goes
;; through `setf--rmw', so the place's subforms are evaluated once.
(defmacro cl-incf (place &rest amt)
  (if (symbolp place)
      (list 'setq place (if amt (list '+ place (car amt)) (list '1+ place)))
    (setf--rmw place (lambda (g) (list '+ g (if amt (car amt) 1))))))
(defmacro cl-decf (place &rest amt)
  (if (symbolp place)
      (list 'setq place (if amt (list '- place (car amt)) (list '1- place)))
    (setf--rmw place (lambda (g) (list '- g (if amt (car amt) 1))))))
;; cl-callf: (cl-callf FUNC PLACE ARGS...) -> (setf PLACE (FUNC PLACE ARGS...)).
;; cl-callf2 puts a fixed ARG1 before PLACE in the call.
(defmacro cl-callf (func place &rest args)
  (setf--rmw place (lambda (g) (cons func (cons g args)))))
(defmacro cl-callf2 (func arg1 place &rest args)
  (setf--rmw place (lambda (g) (cons func (cons arg1 (cons g args))))))
(defmacro cl-locally (&rest body) (cons 'progn body))
;; cl-psetf: evaluate all values first, then assign all places (parallel setf).
(defmacro cl-psetf (&rest pairs)
  (let ((binds nil) (sets nil) (ps pairs))
    (while ps
      (let ((tv (make-symbol "ps")))
        (setq binds (cons (list tv (cadr ps)) binds))
        (setq sets (cons (list 'setf (car ps) tv) sets))
        (setq ps (cddr ps))))
    `(let ,(reverse binds) ,@(reverse sets) nil)))
;; cl-psetq is cl-psetf restricted to variables; cl-lib.el defines it as the same
;; expander, so forward to it rather than duplicating the parallel-assign logic.
(defmacro cl-psetq (&rest pairs) `(cl-psetf ,@pairs))
;; cl-rotatef: rotate place values left (last gets the first's old value).
(defmacro cl-rotatef (&rest places)
  (if (cdr places)
      (let ((tv (make-symbol "rot")) (forms nil) (ps places))
        (while (cdr ps)
          (setq forms (cons (list 'setf (car ps) (cadr ps)) forms))
          (setq ps (cdr ps)))
        `(let ((,tv ,(car places)))
           ,@(reverse forms)
           (setf ,(car ps) ,tv)
           nil))
    nil))
;; cl-shiftf: shift place values left, the last place taking NEWVAL (the final
;; argument); returns the first place's old value.
(defmacro cl-shiftf (&rest args)
  (let* ((places (butlast args)) (newval (car (last args)))
         (tv (make-symbol "shf")) (forms nil) (ps places))
    (while (cdr ps)
      (setq forms (cons (list 'setf (car ps) (cadr ps)) forms))
      (setq ps (cdr ps)))
    `(let ((,tv ,(car places)))
       ,@(reverse forms)
       (setf ,(car ps) ,newval)
       ,tv)))
(defun cl-first (x) (car x))
(defun cl-fourth (x) (nth 3 x))
(defun cl-fifth (x) (nth 4 x))
(defun cl-sixth (x) (nth 5 x))
(defun cl-seventh (x) (nth 6 x))
(defun cl-eighth (x) (nth 7 x))
(defun cl-ninth (x) (nth 8 x))
(defun cl-tenth (x) (nth 9 x))
(defun cl-mapcan (fn &rest seqs) (apply 'nconc (apply 'cl-mapcar fn seqs)))
(defun cl-acons (key val alist) (cons (cons key val) alist))
(defun cl-list* (&rest args)
  (if (null (cdr args)) (car args) (cons (car args) (apply (function cl-list*) (cdr args)))))

(defun seq-map-indexed (fn seq)
  (let ((i 0) (out nil) (l (append seq nil)))
    (while l (setq out (cons (funcall fn (car l) i) out)) (setq l (cdr l)) (setq i (1+ i)))
    (reverse out)))
(defun seq-do-indexed (fn seq)
  (let ((i 0) (l (append seq nil)))
    (while l (funcall fn (car l) i) (setq l (cdr l)) (setq i (1+ i))))
  nil)
(defun seq-keep (fn seq) (seq-filter (function identity) (mapcar fn seq)))
(defun seq-mapcat (fn seq &optional type)
  (apply 'seq-concatenate (or type 'list) (mapcar fn (append seq nil))))
(defun seq-mapn (fn &rest seqs)
  ;; Apply FN across N sequences in parallel, stopping at the shortest:
  ;; (seq-mapn #'+ '(1 2) '(3 4)) => (4 6). Accepts any sequence types.
  (let ((r nil))
    ;; seq.el converts with `(seq-into s 'list)', which leaves a list as it
    ;; is: a dotted tail is reached by the `car' walk below, not by `append'.
    (setq seqs (mapcar (lambda (s) (seq-into s 'list)) seqs))
    (while (not (memq nil seqs))
      (setq r (cons (apply fn (mapcar (function car) seqs)) r))
      (setq seqs (mapcar (function cdr) seqs)))
    (reverse r)))
;; Curve-quote a format TEMPLATE: grave accent => left single quote, apostrophe
;; => right single quote.  This is `styled_format's message half (editfns.c), and
;; it is NOT `substitute-command-keys': the two differ on `\=', which
;; `substitute-command-keys' honors as an escape and `format-message' does not.
;; Measured on GNU Emacs 30.2:
;;   (format-message "a \\=`b")        => "a \\=‘b"
;;   (substitute-command-keys "a \\=`b") => "a `b"
(defun --curve-quotes-- (string)
  ;; help.el `substitute-quotes', which `styled_format' agrees with.
  ;; The replacement is character for character, so the template's text
  ;; properties stay where they were.
  (and string
       (elisprs--carry-text-properties
        string
        (cond ((eq (text-quoting-style) 'curve)
               (string-replace "'" "’" (string-replace "`" "‘" string)))
              ((eq (text-quoting-style) 'straight) (string-replace "`" "'" string))
              (t string)))))
(defun format-message (fmt &rest args)
  (apply (function format) (--curve-quotes-- fmt) args))
;; `substitute-command-keys' without a keymap database: the key-substitution
;; constructs need `where-is-internal' (no interactive keymaps here), but the
;; quote translation half is what callers and error reporting actually rely on,
;; and it is exactly the default `text-quoting-style' of `curve'.
;;
;; `\=' quotes the following character and is discarded, so `\=\=' yields `\=',
;; `\=\[' yields `\[', and `\=' + apostrophe yields a plain apostrophe rather
;; than a curved one.  A trailing `\=' with nothing after it stays literal.
;; NAMED limitation: \\[COMMAND] / \\{MAP} / \\<MAP> are passed through unchanged.
(defun substitute-command-keys (string &optional _no-face _include-menus)
  ;; A nil STRING comes back as nil, never as an error: `print_error_message'
  ;; funnels `(get ERRNAME 'error-message)' through here unconditionally, and an
  ;; unregistered error symbol has none.
  (when string
    (let ((i 0) (n (length string)) (out nil) c)
      (while (< i n)
        (setq c (aref string i))
        (cond
         ((and (eq c ?\\) (< (+ i 2) n) (eq (aref string (1+ i)) ?=))
          (push (aref string (+ i 2)) out)
          (setq i (+ i 3)))
         ((and (eq c ?`) (eq (text-quoting-style) 'curve)) (push ?‘ out) (setq i (1+ i)))
         ((and (eq c ?') (eq (text-quoting-style) 'curve)) (push ?’ out) (setq i (1+ i)))
         ((and (eq c ?`) (eq (text-quoting-style) 'straight)) (push ?' out) (setq i (1+ i)))
         (t (push c out) (setq i (1+ i)))))
      (apply (function string) (nreverse out)))))
;; help.el `substitute-quotes'.
(defun substitute-quotes (string)
  (cond ((eq (text-quoting-style) 'curve)
         (string-replace "`" "‘"
                         (string-replace "'" "’" string)))
        ((eq (text-quoting-style) 'straight)
         (string-replace "`" "'" string))
        (t string)))
;; minibuffer.el `format-prompt' and its format.
(defvar minibuffer-default-prompt-format " (default %s)")
(defun format-prompt (prompt default &rest format-args)
  (concat
   (if (null format-args)
       (substitute-command-keys prompt)
     (apply #'format (substitute-command-keys prompt) format-args))
   (and default
        (or (not (stringp default))
            (length> default 0))
        (format (substitute-command-keys minibuffer-default-prompt-format)
                (if (consp default)
                    (car default)
                  default)))
   ": "))
(defun cl--digitp (c) (and (>= c ?0) (<= c ?9)))
;; value<: a canonical total order within a type (numbers/strings/symbols/lists/
;; vectors); cross-type comparison signals an error, like Emacs 30.
(defun value<--class (x)
  (cond ((numberp x) 'number) ((stringp x) 'string)
        ((or (consp x) (null x)) 'list) ((symbolp x) 'symbol)
        ((vectorp x) 'vector) (t 'other)))
(defun value< (a b)
  (let ((ca (value<--class a)) (cb (value<--class b)))
    (unless (eq ca cb) (signal (quote type-mismatch) (list a b)))
    (cond
     ((eq ca 'number) (< a b))
     ((eq ca 'string) (string< a b))
     ((eq ca 'symbol) (string< (symbol-name a) (symbol-name b)))
     ((eq ca 'list)
      (cond ((null a) (not (null b)))
            ((null b) nil)
            ((value< (car a) (car b)) t)
            ((value< (car b) (car a)) nil)
            (t (value< (cdr a) (cdr b)))))
     ((eq ca 'vector)
      (let ((n (min (length a) (length b))) (i 0) (res 'eq))
        (while (and (< i n) (eq res 'eq))
          (cond ((value< (aref a i) (aref b i)) (setq res t))
                ((value< (aref b i) (aref a i)) (setq res nil)))
          (setq i (1+ i)))
        (if (eq res 'eq) (< (length a) (length b)) res)))
     (t (signal (quote type-mismatch) (list a b))))))
;; ── filevercmp ───────────────────────────────────────────────────────────────
;; `string-version-lessp' is `filevercmp (S1, S2) < 0' in Emacs, and filevercmp
;; is gnulib's Debian version-sort, NOT a byte comparison with numeric runs.
;; Comparing raw character codes got the digit runs right and everything else
;; wrong: `(string-version-lessp "a" " ")' is t in Emacs (punctuation sorts
;; AFTER letters) and `(string-version-lessp "." "9")' is t (a lone "." sorts
;; before every other name). The three helpers below are statement-for-statement
;; ports of gnulib lib/filevercmp.c so those rules come out of the algorithm
;; instead of being special-cased.
(defun filevercmp--alpha-p (c) (or (and (>= c ?A) (<= c ?Z)) (and (>= c ?a) (<= c ?z))))
(defun filevercmp--alnum-p (c) (or (cl--digitp c) (filevercmp--alpha-p c)))

;; gnulib `order': the sort weight of the byte at POS. Past the end sorts first,
;; then `~', then any digit (all digits tie — runs are compared numerically
;; below), then letters by code, then every other byte AFTER the letters.
(defun filevercmp--order (s pos len)
  (if (= pos len)
      -1
    (let ((c (aref s pos)))
      (cond ((cl--digitp c) 0)
            ((filevercmp--alpha-p c) c)
            ((eq c ?~) -2)
            ;; c + UCHAR_MAX + 1: pushes punctuation past every letter.
            (t (+ c 256))))))

;; gnulib `verrevcmp': the Debian version-comparison algorithm. Alternates
;; between a non-digit stretch compared through `filevercmp--order' and a digit
;; run compared numerically (leading zeros skipped, longer run wins).
(defun filevercmp--verrevcmp (s1 n1 s2 n2)
  (let ((p1 0) (p2 0) (result nil) (first-diff 0))
    (while (and (null result) (or (< p1 n1) (< p2 n2)))
      (setq first-diff 0)
      (while (and (null result)
                  (or (and (< p1 n1) (not (cl--digitp (aref s1 p1))))
                      (and (< p2 n2) (not (cl--digitp (aref s2 p2))))))
        (let ((c1 (filevercmp--order s1 p1 n1))
              (c2 (filevercmp--order s2 p2 n2)))
          (if (/= c1 c2)
              (setq result (- c1 c2))
            (setq p1 (1+ p1) p2 (1+ p2)))))
      (unless result
        (while (and (< p1 n1) (eq (aref s1 p1) ?0)) (setq p1 (1+ p1)))
        (while (and (< p2 n2) (eq (aref s2 p2) ?0)) (setq p2 (1+ p2)))
        (while (and (< p1 n1) (< p2 n2)
                    (cl--digitp (aref s1 p1)) (cl--digitp (aref s2 p2)))
          (when (= first-diff 0)
            (setq first-diff (- (aref s1 p1) (aref s2 p2))))
          (setq p1 (1+ p1) p2 (1+ p2)))
        ;; A digit left over on one side means that run is longer, so larger.
        (cond ((and (< p1 n1) (cl--digitp (aref s1 p1))) (setq result 1))
              ((and (< p2 n2) (cl--digitp (aref s2 p2))) (setq result -1))
              ((/= first-diff 0) (setq result first-diff)))))
    (or result 0)))

;; gnulib `file_prefixlen': length of S up to its file suffixes, where a suffix
;; matches "(\.[A-Za-z~][A-Za-z0-9~]*)*$". Comparing prefixes first is why
;; "foo2.png" sorts before "foo12.png".
(defun filevercmp--prefixlen (s n)
  (let ((i 0) (prefixlen 0) (done nil))
    (while (not done)
      (if (= i n)
          (setq done t)
        (setq i (1+ i))
        (setq prefixlen i)
        (while (and (< (1+ i) n) (eq (aref s i) ?.)
                    (let ((c (aref s (1+ i))))
                      (or (filevercmp--alpha-p c) (eq c ?~))))
          (setq i (+ i 2))
          (while (and (< i n)
                      (let ((c (aref s i)))
                        (or (filevercmp--alnum-p c) (eq c ?~))))
            (setq i (1+ i))))))
    prefixlen))

;; gnulib `filenvercmp'.
(defun filevercmp--cmp (a b)
  (let ((alen (length a)) (blen (length b)))
    (cond
     ;; Empty sorts before everything.
     ((= alen 0) (if (= blen 0) 0 -1))
     ((= blen 0) 1)
     ;; Leading ".": "." sorts first, then "..", then other dotted names, then
     ;; everything else.
     ((and (eq (aref a 0) ?.) (not (eq (aref b 0) ?.))) -1)
     ((and (eq (aref b 0) ?.) (not (eq (aref a 0) ?.))) 1)
     ((and (eq (aref a 0) ?.) (= alen 1)) (if (= blen 1) 0 -1))
     ((and (eq (aref b 0) ?.) (= blen 1)) 1)
     ((and (eq (aref a 0) ?.) (> alen 1) (eq (aref a 1) ?.) (= alen 2))
      (if (and (> blen 1) (eq (aref b 1) ?.) (= blen 2)) 0 -1))
     ((and (eq (aref b 0) ?.) (> blen 1) (eq (aref b 1) ?.) (= blen 2)) 1)
     (t
      (let* ((ap (filevercmp--prefixlen a alen))
             (bp (filevercmp--prefixlen b blen))
             ;; With both suffixes empty the second pass would repeat the first.
             (one-pass (and (= ap alen) (= bp blen)))
             (result (filevercmp--verrevcmp a ap b bp)))
        (if (or (/= result 0) one-pass)
            result
          (filevercmp--verrevcmp a alen b blen)))))))

(defun string-version-lessp (s1 s2)
  ;; `filevercmp (S1, S2) < 0' — see `filevercmp--cmp' above. NOT `string-lessp'
  ;; with numeric runs: the byte order is `filevercmp--order''s, not ASCII's.
  ;; fns.c `Fstring_version_lessp' takes SYMBOLP first and uses the print name,
  ;; then CHECK_STRINGs both operands -- so `t' and `car' are legal arguments
  ;; ((string-version-lessp "ab" t) => t, comparing "ab" against "t"), while a
  ;; number is (wrong-type-argument stringp 0), not `sequencep'. Reading the
  ;; operands with `length'/`aref' alone reported `sequencep' for both.
  (if (symbolp s1) (setq s1 (symbol-name s1)))
  (if (symbolp s2) (setq s2 (symbol-name s2)))
  (unless (stringp s1) (signal 'wrong-type-argument (list 'stringp s1)))
  (unless (stringp s2) (signal 'wrong-type-argument (list 'stringp s2)))
  (< (filevercmp--cmp s1 s2) 0))
(defun seq-concatenate (type &rest seqs)
  ;; Concatenate SEQS into one sequence of TYPE (`list', `vector', or `string').
  (let ((all nil))
    (dolist (s seqs) (setq all (append all (append s nil))))
    (cond ((eq type 'list) all)
          ((eq type 'vector) (vconcat all))
          ((eq type 'string) (apply (function string) all))
          (t (error "Not a sequence type name: %S" type)))))
(defun cl-concatenate (type &rest seqs) (apply #'seq-concatenate type seqs))
;; cl-equalp: like equal but numbers compare with `=' (1 = 1.0) and strings
;; case-insensitively; recurses through conses and vectors. (Characters are
;; integers in elisp, so they compare numerically, like Emacs.)
(defun cl-equalp (x y)
  (cond
   ((and (numberp x) (numberp y)) (= x y))
   ((and (stringp x) (stringp y)) (string-equal-ignore-case x y))
   ((and (consp x) (consp y)) (and (cl-equalp (car x) (car y)) (cl-equalp (cdr x) (cdr y))))
   ((and (vectorp x) (vectorp y))
    (and (= (length x) (length y)) (cl-equalp (append x nil) (append y nil))))
   (t (equal x y))))
(defun copy-alist (al)
  (mapcar (lambda (p) (if (consp p) (cons (car p) (cdr p)) p)) al))
;; substring-no-properties is a native subr (builtins.rs): it is a C subr in
;; Emacs, so `#'substring-no-properties` must print `#<subr …>`, and the subr
;; checks `stringp` before the indices.
;; The human-readable message for an error object (ERROR-SYMBOL . DATA) — a
;; statement-for-statement port of print.c `print_error_message', because every
;; corner of it is observable and none of it follows from the happy path:
;;
;;   * ERRNAME is `(car ERR)', so a non-list ERR is `(wrong-type-argument listp ERR)'.
;;   * The `error' symbol is special-cased BEFORE any property lookup: DATA
;;     becomes `(cdr ERR)' and the MESSAGE is its car, so `(error 1 2)' has the
;;     non-string message 1 and reads "peculiar error: 2".
;;   * Every other ERRNAME goes through `get', whose CHECK_SYMBOL is what makes
;;     `(error-message-string '(1 2))' signal `(wrong-type-argument symbolp 1)'.
;;   * TAIL is `cdr-safe', and the loop runs while TAIL is a cons — a dotted tail
;;     is dropped, never an error: `(error-message-string '(foo 1 . 2))' is
;;     "peculiar error: 1".
;;   * A non-string message prints "peculiar error"; an EMPTY message suppresses
;;     the separator entirely, so `(error-message-string '(error "" 1 2))' is
;;     "1, 2" and not ": 1, 2".
;;   * For a `file-error' condition the FIRST datum becomes the message and the
;;     rest print with `princ' — as do `end-of-file' and `user-error' data,
;;     which is the whole difference between `(user-error "a" "b")' => "a, b"
;;     and a *child* of user-error with the same data => "\"a\", \"b\"".
(defun error-message-string (err)
  (let ((errname (car err)) (errmsg nil) (file-error nil)
        (data err) (tail nil) (out "") (sep ": "))
    (if (eq errname 'error)
        (progn
          (setq data (cdr err))
          (unless (consp data) (setq data nil))
          (setq errmsg (car data) file-error nil))
      (setq errmsg (get errname 'error-message))
      ;; The substitution result replaces ERRMSG only when it is non-nil.
      (let ((subs (substitute-command-keys errmsg)))
        (when subs (setq errmsg subs)))
      (setq file-error (memq 'file-error (get errname 'error-conditions))))
    (setq tail (cdr-safe data))
    (when (and file-error (consp tail))
      (setq errmsg (car tail) tail (cdr tail)))
    (cond
     ((not (stringp errmsg)) (setq out "peculiar error"))
     ((> (length errmsg) 0) (setq out errmsg))
     (t (setq sep nil)))
    (let ((princy (or file-error
                      (eq errname 'end-of-file)
                      (eq errname 'user-error))))
      (while (consp tail)
        (when sep (setq out (concat out sep)))
        (setq sep ", ")
        (let ((obj (car tail)))
          (setq out (concat out (if princy (format "%s" obj) (prin1-to-string obj)))))
        (setq tail (cdr tail))))
    out))
(defun seq-group-by (fn seq)
  ;; Faithful port of Emacs `seq-group-by' (seq.el): fold over the REVERSED
  ;; sequence, prepending newly-seen keys and pushing each element onto its
  ;; group's cdr. This yields groups in reverse first-encounter order with
  ;; items in forward order.
  (seq-reduce
   (lambda (acc elt)
     (let* ((key (funcall fn elt)) (cell (assoc key acc)))
       (if cell (setcdr cell (cons elt (cdr cell)))
         (setq acc (cons (list key elt) acc)))
       acc))
   (reverse (append seq nil))
   nil))

(defun plist-put (plist prop val &optional predicate)
  ;; Fplist_put: step by two, breaking BEFORE the key test when the cdr is not
  ;; a cons; overwrite in place on a match; CHECK_TYPE names the WHOLE plist
  ;; under `plistp' when the walk ends on a non-nil tail -- so both
  ;; (plist-put '(1) 1 9) and (plist-put '(1 . 2) 1 9) are plistp errors even
  ;; though the key is present. Otherwise splice a fresh (PROP VAL) cell onto
  ;; the last pair (nil PLIST returns the new cell bare).
  (let ((test (or predicate #'eq)) (prev nil) (tail plist) (r nil) (done nil))
    (while (and (not done) (consp tail))
      (cond
       ((not (consp (cdr tail))) (setq done t))
       ((funcall test (car tail) prop) (setcar (cdr tail) val) (setq r plist done t))
       (t (setq prev tail tail (cddr tail)))))
    (cond
     (r r)
     (t
      (unless (null tail) (signal 'wrong-type-argument (list 'plistp plist)))
      (let ((newcell (cons prop (cons val (if prev (cddr prev) plist)))))
        (if (null prev) newcell
          (progn (setcdr (cdr prev) newcell) plist)))))))
;; Symbol property lists, backed by a hash table (we have no per-symbol plist
;; slot). Enough for `get`/`put`/`define-error` and the error-condition system.
(defvar symbol-plist--table (make-hash-table :test 'eq))
;; Fget/Fput/Fsymbol_plist/Fsetplist all open with CHECK_SYMBOL, so a non-symbol
;; is `(wrong-type-argument symbolp X)' and never a quiet nil. That check is the
;; whole reason `(error-message-string '(1 2))' signals: print_error_message asks
;; `(get ERRNAME 'error-conditions)' before it can decide anything about ERRNAME.
(defun symbol-plist--check (sym)
  (unless (symbolp sym) (signal 'wrong-type-argument (list 'symbolp sym))))
;; A `compiler-macro' property changes how `macroexpand-all' treats every call
;; to SYM, so the host keeps a set of the symbols that have one and only looks
;; the property up for those (see `ElispHost::compiler_macros'). The note is
;; taken here, not in `function-put', because `cl-define-compiler-macro'
;; stores the property with `define-symbol-prop' and plain `put' is just as
;; valid a way to install one: `macroexp--compiler-macro' reads the plist.
(defun put (sym prop val)
  (symbol-plist--check sym)
  (when (eq prop 'compiler-macro) (--note-compiler-macro sym))
  (puthash sym (plist-put (gethash sym symbol-plist--table) prop val) symbol-plist--table)
  val)
(defun get (sym prop)
  (symbol-plist--check sym)
  (plist-get (gethash sym symbol-plist--table) prop))
;; The command line, defined after `put' because a `defvar' docstring is
;; stored with it.  `elisp FILE a b c' models `emacs -l FILE a b c', where
;; `command-line-args' is the whole invocation and `command-line-args-left' is
;; what follows the script.  Both are (re)set per run by the entry point, since
;; the bytecode cache would otherwise replay the *previous* run's arguments; the
;; values here are the `emacs --eval' answers (nil args-left), which is what
;; `elisp -e' models.  `argv' is an alias, not a copy -- startup.el does
;; `(defvaralias 'argv 'command-line-args-left)', so `(setq argv ...)' is visible
;; through both names.
(defvar command-line-args nil
  "List of command line arguments, as they were given to this process.")
(defvar command-line-args-left nil
  "List of command line arguments not yet processed.")
(defvaralias 'argv 'command-line-args-left
  "List of command line arguments not yet processed.")
;; backquote.el marks the two unquote symbols as reader constructs.
(put '\, 'reader-construct t)
(put '\,@ 'reader-construct t)
;; `Fdefine_hash_table_test' (fns.c) is exactly this `put': the declaration
;; lives on NAME's `hash-table-test' property as (TESTFN HASHFN), and
;; `make-hash-table' reads it back.  The value is the property list `put'
;; returns, not NAME.
(defun define-hash-table-test (name test hash)
  "Define a new hash table test named NAME.
TEST compares two keys; HASH maps a key to a hash value.  A table made with
`:test NAME' calls them -- so both are ordinary elisp and may do anything a
function may, `gethash' on such a table included."
  (put name 'hash-table-test (list test hash)))
(defun symbol-plist (sym)
  (symbol-plist--check sym)
  (gethash sym symbol-plist--table))
(defun setplist (sym plist)
  (symbol-plist--check sym)
  (puthash sym plist symbol-plist--table) plist)
;; Function properties share the symbol plist table. subr.el's `function-get'
;; walks the function-cell alias chain and its `(symbolp f)' guard is what keeps
;; a non-symbol from reaching `get' — `(function-get 1 'x)' is nil, not an error.
(defun function-get (f prop &optional autoload)
  (let ((val nil))
    (while (and (symbolp f)
                (null (setq val (get f prop)))
                (fboundp f))
      (let ((fundef (symbol-function f)))
        (if (and autoload (autoloadp fundef)
                 (not (equal fundef (autoload-do-load fundef f))))
            nil
          (setq f fundef))))
    val))
(defun function-put (f prop value)
  (put f prop value))
(defun define-symbol-prop (symbol prop value) (put symbol prop value))
;; `record'/`make-record' are `Obj::Record' primitives (see builtins.rs); a record
;; is a distinct type from a vector, with the type symbol in slot 0.
(defun define-error (name message &optional parent)
  "Define NAME as a new error signal (subr.el).
PARENT is either a signal or a list of signals from which it inherits.
Defaults to `error'.  The conditions are de-duplicated, so two parents that
share `error' list it once."
  (unless parent (setq parent 'error))
  (let ((conditions
         (if (consp parent)
             (apply #'append
                    (mapcar (lambda (parent)
                              (cons parent
                                    (or (get parent 'error-conditions)
                                        (error "Unknown signal `%s'" parent))))
                            parent))
           (cons parent (get parent 'error-conditions)))))
    (put name 'error-conditions
         (delete-dups (copy-sequence (cons name conditions))))
    (when message (put name 'error-message message))))
;; Seed the standard error symbols (so `error-message-string' / `get' match Emacs).
(define-error 'error "error" nil)
(put 'error 'error-conditions '(error))
(define-error 'user-error "")
(define-error 'quit "Quit" nil)
;; `quit' is NOT an `error': data.c seeds it with `error-conditions' = (quit)
;; alone, which is why `(condition-case nil (signal 'quit nil) (error 'caught))'
;; does not catch it while a `t' handler does. `define-error' defaults a nil
;; PARENT to `error', so the chain has to be overridden here (same shape as the
;; `error' seed above).
(put 'quit 'error-conditions '(quit))
(define-error 'minibuffer-quit "Quit" 'quit)
(define-error 'args-out-of-range "Args out of range")
(define-error 'cl-struct-unknown-slot "struct has no slot")
(define-error 'arith-error "Arithmetic error")
(define-error 'type-mismatch "Types do not match")
(define-error 'wrong-type-argument "Wrong type argument")
(define-error 'wrong-number-of-arguments "Wrong number of arguments")
(define-error 'void-variable "Symbol's value as variable is void")
(define-error 'void-function "Symbol's function definition is void")
(define-error 'invalid-function "Invalid function")
(define-error 'wrong-length-argument "Wrong length argument")
(define-error 'invalid-regexp "Invalid regexp")
(define-error 'cyclic-variable-indirection "Symbol's chain of variable indirections contains a loop")
(define-error 'cl-assertion-failed "Assertion failed")
(define-error 'end-of-file "End of file during parsing")
;; The rest of the data.c/fileio.c seed table, verbatim (messages and parents as
;; `emacs -Q' reports them). Without these an unregistered symbol has no
;; `error-conditions' chain, so `error-message-string' called it a "peculiar
;; error" and `condition-case' could not dispatch a `file-error' handler onto
;; `file-missing' or an `arith-error' handler onto `overflow-error'. The
;; `file-error' family also selects print.c's concatenating branch, where the
;; first datum becomes the message and string data print unquoted.
(define-error 'file-error "File error")
(define-error 'file-missing "File is missing" 'file-error)
(define-error 'file-already-exists "File already exists" 'file-error)
(define-error 'file-date-error "Cannot set file date" 'file-error)
(define-error 'file-notify-error "File notification error" 'file-error)
(define-error 'permission-denied "Cannot access file or directory" 'file-error)
(define-error 'remote-file-error "Remote file error" 'file-error)
(define-error 'range-error "Arithmetic range error" 'arith-error)
(define-error 'overflow-error "Arithmetic overflow error" 'range-error)
(define-error 'search-failed "Search failed")
(define-error 'scan-error "Scan error")
(define-error 'circular-list "List contains a loop")
(define-error 'buffer-read-only "Buffer is read-only")
(define-error 'text-read-only "Text is read-only" 'buffer-read-only)
(define-error 'beginning-of-buffer "Beginning of buffer")
(define-error 'end-of-buffer "End of buffer")
(define-error 'no-catch "No catch for tag")
(define-error 'invalid-read-syntax "Invalid read syntax")
(define-error 'setting-constant "Attempt to set a constant symbol")
(define-error 'recursion-error "Excessive recursive calling error")
(define-error 'excessive-lisp-nesting "Lisp nesting exceeds `max-lisp-eval-depth'" 'recursion-error)
;; The remaining standard error symbols `emacs -Q' seeds (data.c, eval.c,
;; json.c, search.c, ...), messages and parents as Emacs 31.1 reports them.
;; `signal' refuses a symbol with no `error-conditions', so every condition
;; a builtin or library raises must be registered.
(define-error 'excessive-variable-binding "Variable binding depth exceeds max-specpdl-size" 'recursion-error)
(define-error 'domain-error "Arithmetic domain error" 'arith-error)
(define-error 'singularity-error "Arithmetic singularity error" 'domain-error)
(define-error 'underflow-error "Arithmetic underflow error" 'range-error)
(define-error 'cyclic-function-indirection "Symbol's chain of function indirections contains a loop")
(define-error 'inhibited-interaction "User interaction while inhibited")
(define-error 'invalid-arity "Invalid function arity")
(define-error 'malformed-keyword-arg-list "Keyword lacks a corresponding value")
(define-error 'mark-inactive "The mark is not active now")
(define-error 'protected-field "Attempt to modify a protected field")
(define-error 'trapping-constant "Attempt to trap writes to a constant symbol")
(define-error 'user-search-failed "Search failed" '(user-error search-failed))
;; search.c seeds this list literally; `define-error' would put `error' second.
(put 'user-search-failed 'error-conditions '(user-search-failed user-error search-failed error))
(define-error 'json-error "generic JSON error")
(define-error 'json-parse-error "could not parse JSON stream" 'json-error)
(define-error 'json-end-of-file "end of JSON stream" 'json-parse-error)
(define-error 'json-trailing-content "trailing content after JSON stream" 'json-parse-error)
(define-error 'json-escape-sequence-error "invalid escape sequence" 'json-parse-error)
(define-error 'json-invalid-surrogate-error "invalid surrogate pair" 'json-error)
(define-error 'json-number-out-of-range-error "number out of range" 'json-error)
(define-error 'json-object-too-deep "object cyclic or Lisp evaluation too deep" 'json-error)
(define-error 'json-out-of-memory "not enough memory for creating JSON object" 'json-error)
(define-error 'json-utf8-decode-error "invalid utf-8 encoding" 'json-error)
;; eval.c's recursion guard. Reached before the native stack is, so runaway
;; recursion signals `(excessive-lisp-nesting DEPTH)' — which `condition-case'
;; can catch — instead of aborting the process on a stack overflow.
(defvar max-lisp-eval-depth 1600)
;; `when'/`unless' are lowered by the compiler (compiler.rs `compile_when'), so
;; they own no function cell — but in Emacs they are ordinary subr.el macros, and
;; introspection sees that: `(type-of (symbol-function 'when))' is `cons', not
;; `symbol'. Register the same `(macro . FUNCTION)' pair the byte-compiler would
;; have produced, for `symbol-function' / `fboundp' / `indirect-function' only.
;; The bodies are subr.el's:
;;   (defmacro when   (cond &rest body) (list 'if cond (cons 'progn body)))
;;   (defmacro unless (cond &rest body) (cons 'if (cons cond (cons nil body))))
(--set-intrinsic-macro-cell
 'when (cons 'macro (lambda (cond &rest body) (list 'if cond (cons 'progn body)))))
(--set-intrinsic-macro-cell
 'unless (cons 'macro (lambda (cond &rest body) (cons 'if (cons cond (cons nil body))))))
;; subr.el: (defmacro lambda (&rest cdr) (list 'function (cons 'lambda cdr)))
(--set-intrinsic-macro-cell
 'lambda (cons 'macro (lambda (&rest cdr) (list 'function (cons 'lambda cdr)))))
;; byte-run.el's `defmacro' and `defun' are compiler special forms here; their
;; properties are the ones byte-run.el puts and declares.
(function-put 'defmacro 'doc-string-elt 3)
(function-put 'defmacro 'lisp-indent-function 2)
(function-put 'defmacro 'autoload-macro 'expand)
(function-put 'defun 'doc-string-elt 3)
(function-put 'defun 'lisp-indent-function 2)
(function-put 'defun 'autoload-macro 'expand)
;; The subr.el `declare's of the three intrinsic macros above: when/unless
;; `(indent 1) (debug t)', lambda `(doc-string 2) (indent defun) (debug ...)'.
(function-put 'when 'lisp-indent-function 1)
(put 'when 'edebug-form-spec t)
(function-put 'unless 'lisp-indent-function 1)
(put 'unless 'edebug-form-spec t)
(function-put 'lambda 'doc-string-elt 2)
(function-put 'lambda 'lisp-indent-function 'defun)
(put 'lambda 'edebug-form-spec
     '(&define lambda-list lambda-doc [&optional ("interactive" interactive)] def-body))
(defun add-to-list (var elt &optional append compare-fn)
  "Add ELT to VAR's list value unless it is already there.
VAR should not name a lexical variable -- the compiler macro below rewrites
those call sites, and this function cannot: it reads and writes the SYMBOL's
value cell.

Faithful to subr.el, membership included: the default test is `member', an
explicit `eq'/`eql' COMPARE-FN uses `memq'/`memql', and any other is walked by
hand until it matches.  Which of the four runs is observable through a
COMPARE-FN with side effects, and through how many times it is called."
  ;; subr.el declares the compiler macro here.  This prelude is ONE file, and
  ;; the `declare' bridge (`byte-run--set-compiler-macro') is not defined until
  ;; much further down -- in Emacs byte-run.el is a separate file loaded first --
  ;; so a `declare' here would be silently dropped.  It is registered by hand
  ;; below instead; see `add-to-list--anon-cmacro'.
  (if (cond
       ((null compare-fn) (member elt (symbol-value var)))
       ((eq compare-fn #'eq) (memq elt (symbol-value var)))
       ((eq compare-fn #'eql) (memql elt (symbol-value var)))
       (t (let ((lst (symbol-value var)))
            (while (and lst (not (funcall compare-fn elt (car lst))))
              (setq lst (cdr lst)))
            lst)))
      (symbol-value var)
    (set var (if append
                 (append (symbol-value var) (list elt))
               (cons elt (symbol-value var))))))
;; equal-including-properties compares text as `equal' does, and additionally
;; requires matching text properties on strings.
(defun equal-including-properties (a b)
  (and (equal a b)
       (or (not (stringp a))
           ;; `compare_string_intervals': interval by interval, property values
           ;; compared with `equal', whatever the two strings' splits are.
           (let ((i 0) (n (length a)) (ok t))
             (while (and ok (< i n))
               (let ((pa (text-properties-at i a)) (pb (text-properties-at i b)))
                 (unless (and (= (length pa) (length pb))
                              (let ((p pa) (same t))
                                (while (and same p)
                                  (let ((cell (plist-member pb (car p))))
                                    (unless (and cell (equal (cadr cell) (cadr p)))
                                      (setq same nil)))
                                  (setq p (cddr p)))
                                same))
                   (setq ok nil)))
               (setq i (1+ i)))
             ok))))

;; `Ftext_property_any' / `Ftext_property_not_all' (textprop.c): the first
;; position in [START, END) where PROP is -- or is not -- `eq' to VALUE, nil if
;; there is none.  OBJECT is a buffer or a string, defaulting to the current
;; buffer.  An empty range answers nil for both, and a range outside OBJECT is
;; `(args-out-of-range START END)' -- which `get-text-property' already reports.
(defun text-property--validate-range (start end object)
  "Signal unless [START, END] lies within OBJECT, as `validate_interval_range' does.
The datum names START and END as GIVEN, which is why the walk cannot just let
`get-text-property' report the first bad position it reaches."
  (let ((lo 0) (hi 0))
    (if (stringp object)
        (setq lo 0 hi (length object))
      ;; `set-buffer' + `unwind-protect' rather than `with-current-buffer':
      ;; that macro is defined further down this file, and a macro used before
      ;; its definition compiles as a CALL ("macro called as a function").
      (if (bufferp object)
          (let ((old (current-buffer)))
            (unwind-protect
                (progn (set-buffer object) (setq lo (point-min) hi (point-max)))
              (set-buffer old)))
        (setq lo (point-min) hi (point-max))))
    (unless (and (<= lo (min start end)) (<= (max start end) hi))
      (signal 'args-out-of-range (list start end)))))
(defun text-property-any (start end prop value &optional object)
  "Return the first position in [START, END) where PROP is `eq' to VALUE."
  (text-property--validate-range start end object)
  (let ((pos start) (found nil))
    (while (and (null found) (< pos end))
      (if (eq (get-text-property pos prop object) value)
          (setq found pos)
        (setq pos (1+ pos))))
    found))
(defun text-property-not-all (start end prop value &optional object)
  "Return the first position in [START, END) where PROP is not `eq' to VALUE."
  (text-property--validate-range start end object)
  (let ((pos start) (found nil))
    (while (and (null found) (< pos end))
      (if (eq (get-text-property pos prop object) value)
          (setq pos (1+ pos))
        (setq found pos)))
    found))

;; `listify-key-sequence' (subr.el).  A key sequence may be a vector of events
;; or a string of characters; a UNIBYTE string encodes the meta bit as the high
;; bit, so a character above 127 is converted back to the meta modifier.  A
;; multibyte string holds real characters and is taken as-is.
(defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
(defun listify-key-sequence (key)
  "Convert the key sequence KEY to a list of events."
  (if (or (vectorp key) (multibyte-string-p key))
      (append key nil)
    (mapcar (lambda (c) (if (> c 127) (logxor c listify-key-sequence-1) c))
            key)))


(defun apply-partially (fn &rest args) (lambda (&rest more) (apply fn (append args more))))
(defun complement (fn) (lambda (&rest args) (not (apply fn args))))
(defun cl-constantly (x) (lambda (&rest --ignore--) x))

(defun string-chop-newline (s) (if (string-suffix-p "\n" s) (substring s 0 (- (length s) 1)) s))
(defun pp-to-string (object) (concat (prin1-to-string object) "\n"))
(defun pp (object &optional _stream) (princ (pp-to-string object)) nil)
;; cl-print: elisprs has no special struct/closure rendering, so these fall back
;; to the ordinary printer.
(defun cl-prin1-to-string (object) (prin1-to-string object))
(defun cl-prin1 (object &optional stream) (prin1 object stream))
(defun subst-char-in-string (from to string &optional _inplace)
  (concat (mapcar (lambda (c) (if (eq c from) to c)) string)))
(defun string-bytes (s)
  ;; Number of bytes in the UTF-8 encoding of S.
  (let ((n 0) (l (string-to-list s)))
    (while l
      (let ((c (car l)))
        (setq n (+ n (cond ((< c 128) 1) ((< c 2048) 2) ((< c 65536) 3) (t 4)))))
      (setq l (cdr l)))
    n))
;; `char-width' is a subr (`builtins::char_width_fn'), matching Emacs's
;; `Fchar_width' in indent.c. `format' measures its field width and `%.Ns'
;; precision in display columns and needs the same table from Rust, so keeping a
;; second copy here would have been two implementations of one answer.
(defun string-width (s &optional from to)
  ;; `string-to-list' accepts any sequence, so the string check has to be explicit:
  ;; Emacs signals `stringp', not `sequencep'.
  (unless (stringp s) (signal 'wrong-type-argument (list 'stringp s)))
  ;; character.c validates FROM and TO with `validate_subarray', as `substring' does.
  (let ((w 0) (l (string-to-list (substring s from to))))
    (while l (setq w (+ w (char-width (car l))) l (cdr l)))
    w))
(defun cl-type-of (obj)
  (cond ((null obj) 'null)
        ((integerp obj) 'fixnum)
        ((floatp obj) 'float)
        ((symbolp obj) 'symbol)
        ((stringp obj) 'string)
        ((consp obj) 'cons)
        (t (type-of obj))))
(defun number-or-marker-p (x) (or (numberp x) (markerp x)))
(defun integer-or-marker-p (x) (or (integerp x) (markerp x)))
(defun string-pad (s len &optional padding start)
  ;; Pad S to LENGTH chars with PADDING (default space); pad on the left when
  ;; START is non-nil, otherwise on the right.
  (unless (natnump len) (signal 'wrong-type-argument (list 'natnump len)))
  (let ((pad (or padding 32)) (cur (length s)))
    (if (>= cur len) s
      (let ((fill (make-string (- len cur) pad)))
        (if start (concat fill s) (concat s fill))))))
;; A horizontal rule: LENGTH dashes (default 79, the batch text width) + newline.
;; (Emacs returns a string with a face applied; the plain text is returned here.)
(defun make-separator-line (&optional length)
  (concat (make-string (or length 79) ?-) "\n"))
(defun string-lines (string &optional omit-nulls keep-newlines)
  ;; Split STRING into a list of lines on newline.  When OMIT-NULLS, drop empty
  ;; lines; when KEEP-NEWLINES, retain the trailing newline on each line.
  (if (equal string "")
      (list "")
    (let ((lines nil) (start 0) (len (length string)))
      (while (< start len)
        (let ((nl (string-search "\n" string start)))
          (if nl
              (progn
                (let ((line (substring string start (if keep-newlines (1+ nl) nl))))
                  (when (or (not omit-nulls) (not (string= line "")))
                    (push line lines)))
                (setq start (1+ nl)))
            (let ((line (substring string start)))
              (when (or (not omit-nulls) (not (string= line "")))
                (push line lines))
              (setq start len)))))
      (nreverse lines))))
(defun string-glyph-split (string)
  ;; Split STRING into its glyphs.  Without composition tables this is a
  ;; per-character split, which matches Emacs for non-composed text.
  (mapcar #'char-to-string (string-to-list string)))
(defun string-limit (string length &optional end _coding-system)
  ;; First LENGTH chars of STRING (or last LENGTH when END is non-nil); the whole
  ;; string if it is already short enough. (Byte-based CODING-SYSTEM unsupported.)
  (let ((len (length string)))
    (if (<= len length)
        string
      (if end
          (substring string (- len length) len)
        (substring string 0 length)))))
(defun string-fill (s len)
  ;; Greedily wrap S so no line exceeds LEN columns, breaking only at spaces.
  (let ((words (split-string s)) (lines nil) (cur ""))
    (dolist (w words)
      (cond ((string= cur "") (setq cur w))
            ((<= (+ (length cur) 1 (length w)) len) (setq cur (concat cur " " w)))
            (t (push cur lines) (setq cur w))))
    (unless (string= cur "") (push cur lines))
    (mapconcat 'identity (reverse lines) "\n")))
(defun string-equal-ignore-case (a b)
  ;; Unlike `string=', this is `compare-strings' underneath in Emacs, which
  ;; takes only actual strings: (string-equal-ignore-case nil "x") signals
  ;; `stringp nil' rather than comparing the symbol's name.
  (unless (stringp a) (signal 'wrong-type-argument (list 'stringp a)))
  (unless (stringp b) (signal 'wrong-type-argument (list 'stringp b)))
  (string= (downcase a) (downcase b)))
(defun upcase-initials (s)
  "Convert the initial of each word in the argument to upper case.
This means that each word's first character is converted to either
title case or upper case, and the rest are left unchanged.
The argument may be a character or string.  The result has the same type."
  (char-or-string--check s)
  (if (integerp s) (--char-titlecase-1-- s) (--casify-capitalize-- s t)))
(defun string-replace (from to s)
  ;; Emacs signals on an empty FROMSTRING rather than looping forever.
  (if (string-empty-p from) (signal 'wrong-length-argument (list 0))
    (let ((out "") (pos (string-search from s)))
      (while pos
        (setq out (concat out (substring s 0 pos) to))
        (setq s (substring s (+ pos (length from)) (length s)))
        (setq pos (string-search from s)))
      (concat out s))))
;; Shell-like quoting (subr.el): combine strings into one quoted command line and
;; split one back, respecting double-quoted segments (read as elisp string literals).
(defun combine-and-quote-strings (strings &optional separator)
  (let* ((sep (or separator " "))
         (re (concat "[\\\"]\\|" (regexp-quote sep))))
    (mapconcat
     (lambda (str)
       (if (or (= (length str) 0) (string-match re str))
           (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
         str))
     strings sep)))
(defun split-string-and-unquote (string &optional separator)
  (let ((sep (or separator "[ \t\n\r\f]+"))
        (i (string-search "\"" string)))
    (if (null i)
        (split-string string sep t)
      (append (unless (= i 0) (split-string (substring string 0 i) sep t))
              (let ((rfs (read-from-string string i)))
                (cons (car rfs)
                      (split-string-and-unquote (substring string (cdr rfs)) sep)))))))
;;; ---- json.el (encode subset) ----
;; Encode elisp data to a JSON string (the forgiving json.el `json-encode' API,
;; not the strict native `json-serialize'). Lists are objects when they look like
;; an alist/plist, else arrays; nil encodes as null; symbols as their name.
(defun json-encode-string (s)
  (let ((out "\""))
    (dolist (c (string-to-list s))
      (setq out (concat out
                        (cond ((eq c 34) "\\\"")
                              ((eq c 92) "\\\\")
                              ((eq c 8) "\\b")
                              ((eq c 9) "\\t")
                              ((eq c 10) "\\n")
                              ((eq c 12) "\\f")
                              ((eq c 13) "\\r")
                              ((< c 32) (format "\\u%04x" c))
                              (t (char-to-string c))))))
    (concat out "\"")))
(defun json-alist-p (l)
  (and (consp l) (let ((ok t)) (dolist (e l) (unless (consp e) (setq ok nil))) ok)))
(defun json-plist-p (l) (and (consp l) (keywordp (car l))))
(defun json--encode-key (k)
  (json-encode-string (cond ((stringp k) k)
                            ((keywordp k) (substring (symbol-name k) 1))
                            ((symbolp k) (symbol-name k))
                            (t (format "%s" k)))))
(defun json--encode-kv (k v) (concat (json--encode-key k) ":" (json-encode v)))
(defun json-encode (object)
  (cond
   ((eq object t) "true")
   ((eq object json-false) "false")
   ((eq object json-null) "null")
   ((null object) "null")
   ((stringp object) (json-encode-string object))
   ((keywordp object) (json-encode-string (substring (symbol-name object) 1)))
   ((numberp object) (number-to-string object))
   ((hash-table-p object)
    (let ((parts nil))
      (maphash (lambda (k v) (setq parts (cons (json--encode-kv k v) parts))) object)
      (concat "{" (mapconcat (function identity) (nreverse parts) ",") "}")))
   ((vectorp object)
    (concat "[" (mapconcat (function json-encode) (append object nil) ",") "]"))
   ((json-alist-p object)
    (concat "{" (mapconcat (lambda (p) (json--encode-kv (car p) (cdr p))) object ",") "}"))
   ((json-plist-p object)
    (let ((parts nil) (l object))
      (while l (setq parts (cons (json--encode-kv (car l) (car (cdr l))) parts)) (setq l (cddr l)))
      (concat "{" (mapconcat (function identity) (nreverse parts) ",") "}")))
   ((listp object) (concat "[" (mapconcat (function json-encode) object ",") "]"))
   ((symbolp object) (json-encode-string (symbol-name object)))
   (t (error "Unknown JSON object: %S" object))))
;; json.el reading (json-read-from-string). Defaults: objects → alists with
;; symbol keys, arrays → vectors, true→t, false→json-false, null→json-null.
(defvar json-object-type 'alist)
(defvar json-array-type 'vector)
(defvar json-key-type nil)
(defvar json-null nil)
(defvar json-false :json-false)
(defun json--skip-ws (s i)
  (let ((n (length s)))
    (while (and (< i n) (memq (aref s i) '(32 9 10 13))) (setq i (1+ i)))
    i))
(defun json--lookahead (s i word)
  (and (<= (+ i (length word)) (length s)) (string= (substring s i (+ i (length word))) word)))
(defun json--read-string (s i)
  (setq i (1+ i))
  (let ((out "") (done nil))
    (while (not done)
      (let ((c (aref s i)))
        (cond
         ((eq c 34) (setq i (1+ i) done t))
         ((eq c 92)
          (setq i (1+ i))
          (let ((e (aref s i)))
            (if (eq e ?u)
                (setq out (concat out (char-to-string (string-to-number (substring s (1+ i) (+ i 5)) 16)))
                      i (+ i 5))
              (setq out (concat out (char-to-string
                                     (cond ((eq e ?n) 10) ((eq e ?t) 9) ((eq e ?r) 13)
                                           ((eq e ?b) 8) ((eq e ?f) 12) ((eq e ?/) 47)
                                           (t e))))
                    i (1+ i)))))
         (t (setq out (concat out (char-to-string c)) i (1+ i))))))
    (cons out i)))
(defun json--read-number (s i)
  (let ((start i) (n (length s)))
    (while (and (< i n) (memq (aref s i) '(?- ?+ ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?. ?e ?E)))
      (setq i (1+ i)))
    (cons (string-to-number (substring s start i)) i)))
(defun json--read-array (s i)
  (setq i (json--skip-ws s (1+ i)))
  (let ((items nil))
    (if (eq (aref s i) ?\])
        (setq i (1+ i))
      (let ((done nil))
        (while (not done)
          (let ((r (json--read s i)))
            (setq items (cons (car r) items) i (json--skip-ws s (cdr r))))
          (cond ((eq (aref s i) ?,) (setq i (json--skip-ws s (1+ i))))
                ((eq (aref s i) ?\]) (setq i (1+ i) done t))
                (t (error "json-read: malformed array"))))))
    (setq items (nreverse items))
    (cons (if (eq json-array-type 'list) items (vconcat items)) i)))
(defun json--object-key (k)
  (cond ((eq json-key-type 'string) k)
        ((eq json-key-type 'keyword) (intern (concat ":" k)))
        (t (intern k))))
(defun json--build-object (pairs)
  (cond
   ((eq json-object-type 'hash-table)
    (let ((h (make-hash-table :test 'equal))) (dolist (p pairs) (puthash (car p) (cdr p) h)) h))
   ((eq json-object-type 'plist)
    (let ((out nil)) (dolist (p pairs) (setq out (cons (cdr p) (cons (intern (concat ":" (car p))) out)))) (nreverse out)))
   (t (mapcar (lambda (p) (cons (json--object-key (car p)) (cdr p))) pairs))))
(defun json--read-object (s i)
  (setq i (json--skip-ws s (1+ i)))
  (let ((pairs nil))
    (if (eq (aref s i) ?})
        (setq i (1+ i))
      (let ((done nil))
        (while (not done)
          (let ((kr (json--read-string s i)))
            (setq i (json--skip-ws s (cdr kr)))
            (setq i (json--skip-ws s (1+ i)))  ; skip the ':'
            (let ((vr (json--read s i)))
              (setq pairs (cons (cons (car kr) (car vr)) pairs) i (json--skip-ws s (cdr vr)))))
          (cond ((eq (aref s i) ?,) (setq i (json--skip-ws s (1+ i))))
                ((eq (aref s i) ?}) (setq i (1+ i) done t))
                (t (error "json-read: malformed object"))))))
    (cons (json--build-object (nreverse pairs)) i)))
(defun json--read (s i)
  (setq i (json--skip-ws s i))
  (let ((c (aref s i)))
    (cond
     ((eq c ?{) (json--read-object s i))
     ((eq c ?\[) (json--read-array s i))
     ((eq c 34) (json--read-string s i))
     ((or (eq c ?-) (and (>= c ?0) (<= c ?9))) (json--read-number s i))
     ((json--lookahead s i "true") (cons t (+ i 4)))
     ((json--lookahead s i "false") (cons json-false (+ i 5)))
     ((json--lookahead s i "null") (cons json-null (+ i 4)))
     (t (error "json-read: unexpected character")))))
(defun json-read-from-string (s) (car (json--read s 0)))
;; The native JSON API (`json-parse-string', `json-parse-buffer',
;; `json-serialize', `json-insert') is json.c's, in Rust: src/json.rs.
;;; ---- file names ----
;; `file-name-directory', `file-name-nondirectory', `file-name-as-directory',
;; `directory-file-name', `directory-name-p', `file-name-concat',
;; `file-name-absolute-p' and `expand-file-name' are fileio.c's, in Rust:
;; src/fileio.rs. The Lisp ones below are files.el's (Emacs 31.1) without the
;; file-name-handler dispatch.
(defun file-name-sans-extension (filename)
  (save-match-data
    (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
	  directory)
      (if (and (string-match "\\.[^.]*\\'" file)
	       (not (eq 0 (match-beginning 0))))
	  (if (setq directory (file-name-directory filename))
	      (concat directory (substring file 0 (match-beginning 0)))
	    (substring file 0 (match-beginning 0)))
	filename))))
(defun file-name-extension (filename &optional period)
  (save-match-data
    (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
      (if (and (string-match "\\.[^.]*\\'" file)
	       (not (eq 0 (match-beginning 0))))
          (substring file (+ (match-beginning 0) (if period 0 1)))
        (if period
            "")))))
(defun file-name-base (&optional filename)
  (file-name-sans-extension
   (file-name-nondirectory (or filename (buffer-file-name)))))
;; `temporary-file-directory' (Vtemporary_file_directory, callproc.c
;; `init_callproc') is a C variable read at load time by stock lisp (files.el,
;; jka-compr.el, url-*.el, ...). The Rust primitive returns the raw dir
;; ($TMPDIR if present -- even empty -- else the macOS Darwin per-user temp dir
;; from confstr(_CS_DARWIN_USER_TEMP_DIR), else "/tmp/"); `file-name-as-directory'
;; adds the trailing slash exactly as the C `Ffile_name_as_directory' call does.
;; Values verified against GNU Emacs 30.2 for TMPDIR set/unset/empty.
(defvar temporary-file-directory
  (file-name-as-directory (--temp-directory--)))
;; No separate small-file temp dir by default, matching `emacs -Q'.
(defvar small-temporary-file-directory nil)
;; `make-temp-name' (Fmake_temp_name, fileio.c) delegates to
;; `make-temp-file-internal' with DIR-FLAG 0, which calls the gnulib
;; `gen_tempname' (tempname.c) in its GT_NOCREATE mode: it replaces a run of
;; 6 `X's with random characters drawn from the 62-char base
;; "a..zA..Z0..9", and loops (up to 62^3 = 238328 attempts) until the name
;; belongs to no existing file (glibc `try_nocreate' uses lstat, so a broken
;; symlink also counts as existing). The random suffix makes the result
;; non-deterministic, so this matches Emacs's observable contract -- PREFIX +
;; 6 base62 chars naming a nonexistent file -- rather than a fixed value.
(defvar make-temp-name--letters
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  "The 62-char base gnulib `gen_tempname' draws temp-name suffix chars from.")
(defun make-temp-name (prefix)
  "Generate temporary file name (string) starting with PREFIX (a string).

This function tries to choose a name that has no existing file.
For this to work, PREFIX should be an absolute file name, and PREFIX
and the returned string should both be non-magic."
  (unless (stringp prefix)
    (signal 'wrong-type-argument (list 'stringp prefix)))
  (let ((attempts 238328)          ; 62 * 62 * 62, gnulib ATTEMPTS_MIN
        (result nil))
    (while (and (null result) (> attempts 0))
      (setq attempts (1- attempts))
      (let ((candidate prefix)
            (i 0))
        (while (< i 6)
          (setq candidate
                (concat candidate
                        (char-to-string
                         (aref make-temp-name--letters (random 62)))))
          (setq i (1+ i)))
        ;; lstat semantics: a real file OR a (possibly broken) symlink counts.
        (unless (or (file-exists-p candidate) (file-symlink-p candidate))
          (setq result candidate))))
    (unless result
      (signal 'file-error (list "Creating file name with prefix" prefix)))
    result))
(defun file-name-split (filename)
  (let ((components nil))
    (when (directory-name-p filename)
      (push "" components)
      (setq filename (directory-file-name filename)))
    (while (length> filename 0)
      (push (file-name-nondirectory filename) components)
      (let ((dir (file-name-directory filename)))
        (setq filename (and dir (directory-file-name dir)))
        (when (and dir (equal dir filename))
          (push (if (equal dir "") ""
                  (substring dir 0 -1))
                components)
          (setq filename nil))))
    components))
(defun file-name-with-extension (filename extension)
  (let ((extn (string-trim-left extension "[.]")))
    (cond ((string-empty-p filename) (error "Empty filename"))
          ((string-empty-p extn) (error "Malformed extension: %s" extension))
          ((directory-name-p filename) (error "Filename is a directory: %s" filename))
          (t (concat (file-name-sans-extension filename) "." extn)))))
(defun file-name-parent-directory (filename)
  (let* ((expanded (expand-file-name filename))
         (parent (file-name-directory (directory-file-name expanded))))
    (cond ((or (null parent) (equal parent expanded)) nil)
          ((not (file-name-absolute-p filename)) (file-relative-name parent))
          (t parent))))
(defun file-name-quoted-p (name &optional top)
  (let ((file-name-handler-alist (unless top file-name-handler-alist)))
    (string-prefix-p "/:" (file-local-name name))))
(defun file-name-quote (name &optional top)
  (let ((file-name-handler-alist (unless top file-name-handler-alist)))
    (if (file-name-quoted-p name top)
        name
      (concat (file-remote-p name) "/:" (file-local-name name)))))
(defun file-name-unquote (name &optional top)
  (let* ((file-name-handler-alist (unless top file-name-handler-alist))
         (localname (file-local-name name)))
    (when (file-name-quoted-p localname top)
      (setq
       localname (if (= (length localname) 2) "/" (substring localname 2))))
    (concat (file-remote-p name) localname)))
(defun file-local-name (file)
  (or (file-remote-p file 'localname) file))
;; env.el (Emacs 31.1).
;; callproc.c's environment lists (set at startup by src/lib.rs
;; `install_process_environment') and env.el's accessors over them.
;; `locale-coding-system' is UTF-8 here, so env.el's encode/decode steps
;; are the identity and are left out.

(defvar process-environment nil
  "List of overridden environment variables for subprocesses to inherit.")
(defvar initial-environment nil
  "List of environment variables inherited from the parent process.")

(defun setenv-internal (env variable value keep-empty)
  "Set VARIABLE to VALUE in ENV, adding empty entries if KEEP-EMPTY.
Changes ENV by side-effect, and returns its new value."
  (declare (important-return-value t))
  (let ((pattern (concat "\\`" (regexp-quote variable) "\\(=\\|\\'\\)"))
	(case-fold-search nil)
	(scan env)
	prev found)
    ;; Handle deletions from the beginning of the list specially.
    (if (and (null value)
	     (not keep-empty)
	     env
	     (stringp (car env))
             (string-match-p pattern (car env)))
	(cdr env)
      ;; Try to find existing entry for VARIABLE in ENV.
      (while (and scan (stringp (car scan)))
        (when (string-match-p pattern (car scan))
	  (if value
	      (setcar scan (concat variable "=" value))
	    (if keep-empty
		(setcar scan variable)
	      (setcdr prev (cdr scan))))
	  (setq found t
		scan nil))
	(setq prev scan
	      scan (cdr scan)))
      (if (and (not found) (or value keep-empty))
	  (cons (if value
		    (concat variable "=" value)
		  variable)
		env)
	env))))

(defun setenv (variable &optional value substitute-env-vars)
  "Set the value of the environment variable named VARIABLE to VALUE.
VARIABLE should be a string.  VALUE is optional; if not provided or
nil, the environment variable VARIABLE will be removed.

SUBSTITUTE-ENV-VARS, if non-nil, means to substitute environment
variables in VALUE with `substitute-env-vars', which see.

The return value is the new value of VARIABLE, or nil if
it was removed from the environment.

This function works by modifying `process-environment'.

As a special case, setting variable `TZ' calls `set-time-zone-rule' as
a side-effect."
  (and value
       substitute-env-vars
       (setq value (substitute-env-vars value)))
  (if (string-search "=" variable)
      (error "Environment variable name `%s' contains `='" variable))
  (if (string-equal "TZ" variable)
      (set-time-zone-rule value))
  (setq process-environment (setenv-internal process-environment
                                             variable value t))
  value)

(defun getenv (variable &optional frame)
  "Get the value of environment variable VARIABLE.
VARIABLE should be a string.  Value is nil if VARIABLE is undefined in
the environment.  Otherwise, value is a string.

If optional parameter FRAME is non-nil, then it should be a
frame.  This function will look up VARIABLE in FRAME's `environment'
parameter.

Otherwise, this function searches `process-environment' for
VARIABLE and returns its value if found.  If not found, and VARIABLE
is \"DISPLAY\", the function uses the `display' parameter of the selected
frame, and if that is also nil, it searches the `initial-environment' list."
  (declare (side-effect-free t))
  (getenv-internal variable
                   (and frame
                        (assq 'environment
                              (frame-parameters frame)))))

(defmacro with-environment-variables (variables &rest body)
  "Set VARIABLES in the environment and execute BODY.
VARIABLES is a list of variable settings of the form (VAR VALUE),
where VAR is the name of the variable (a string) and VALUE
is its value (also a string).

The previous values will be restored upon exit."
  (declare (indent 1) (debug (sexp body)))
  (unless (consp variables)
    (error "Invalid VARIABLES: %s" variables))
  `(let ((process-environment (copy-sequence process-environment)))
     ,@(mapcar (lambda (elem)
                 `(setenv ,(car elem) ,(cadr elem)))
               variables)
     ,@body))
(defconst env--substitute-vars-regexp
  "\\$\\(?:\\(?1:[[:alnum:]_]+\\)\\|{\\(?1:[^{}]+\\)}\\|\\$\\)")
(defun substitute-env-vars (string &optional when-undefined)
  (let ((start 0))
    (while (string-match env--substitute-vars-regexp string start)
      (cond ((match-beginning 1)
	     (let* ((var (match-string 1 string))
                    (value (getenv var)))
               (if (and (null value)
                        (if (functionp when-undefined)
                            (null (setq value (funcall when-undefined var)))
                          when-undefined))
                   (setq start (match-end 0))
                 (setq string (replace-match (or value "") t t string)
                       start (+ (match-beginning 0) (length value))))))
	    (t
	     (setq string (replace-match "$" t t string)
		   start (+ (match-beginning 0) 1)))))
    string))
(defun substitute-env-in-file-name (filename)
  (substitute-env-vars filename
                       (if (memq system-type '(windows-nt ms-dos))
                           (lambda (var) (getenv (upcase var)))
                         t)))
;; fileio.c `search_embedded_absfilename': the index of an absolute file name
;; ("//foo", "/~", "/~user") that follows a `/' inside NM, or nil.
(defun substitute-in-file-name--embedded (nm)
  (let ((p 1) (end (length nm)) (found nil))
    (while (and (not found) (< p end))
      (when (and (eq (aref nm (1- p)) ?/) (file-name-absolute-p (substring nm p)))
        (setq found p))
      (setq p (1+ p)))
    found))
;; fileio.c `Fsubstitute_in_file_name', Unix branch.
(defun substitute-in-file-name (filename)
  (unless (stringp filename) (signal 'wrong-type-argument (list 'stringp filename)))
  (let ((p (substitute-in-file-name--embedded filename)))
    (if p
        (substitute-in-file-name (substring filename p))
      (let ((tmp (substitute-env-in-file-name filename)))
        (unless (stringp tmp) (signal 'wrong-type-argument (list 'stringp tmp)))
        (if (eq tmp filename)
            filename
          (let ((start 0) q)
            (while (setq q (substitute-in-file-name--embedded (substring tmp start)))
              (setq start (+ start q)))
            (if (= start 0) tmp (substring tmp start))))))))
;; POSIX: standard file names need no conversion.
(defun convert-standard-filename (filename) filename)
(defvar default-directory (file-name-as-directory (--current-directory--)))
;; `file-name-handler-alist' (C `Vfile_name_handler_alist', fileio.c): alist of
;; (REGEXP . HANDLER) pairs consulted by file-name operations to dispatch magic
;; file names. The C variable is initialized to nil; the batch default below is
;; the post-loadup set Emacs 30.2 reports under `emacs -Q --batch' — the epa,
;; jka-compr, tramp, and `file-name-non-special' handlers installed at startup.
;; elisprs handles compressed loads in Rust (no dispatch through this alist), so
;; this is data other code reads/rebinds, matching the oracle value-for-value.
(defvar file-name-handler-alist
  '(("\\.gpg\\(~\\|\\.~[0-9]+~\\)?\\'" . epa-file-handler)
    ("\\(?:\\.tzst\\|\\.zst\\|\\.dz\\|\\.txz\\|\\.xz\\|\\.lzma\\|\\.lz\\|\\.g?z\\|\\.\\(?:tgz\\|svgz\\|sifz\\)\\|\\.tbz2?\\|\\.bz2\\|\\.Z\\)\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)?\\'" . jka-compr-handler)
    ("\\`/\\(?:-\\|[^/:|]\\{2,\\}\\):" . tramp-autoload-file-name-handler)
    ("\\`/:" . file-name-non-special)))
;; `load' machinery. These are dynamic (special) variables the `load' builtin
;; rebinds around a file's evaluation and restores afterward. At top level
;; `load-file-name'/`load-true-file-name' are nil and `load-in-progress' is nil,
;; matching Emacs. `load-path' is searched for a bare (directory-less) FILE;
;; `load-suffixes' are the extensions tried (elisprs has no bytecode, so `.elc'
;; is never found); crossed with `load-file-rep-suffixes' = `("" ".gz")', so
;; `.el', `.el.gz', the exact name, and its `.gz' variant all resolve.
(defvar load-path nil)
(defvar load-file-name nil)
(defvar load-true-file-name nil)
(defvar load-in-progress nil)
(defvar load-suffixes '(".elc" ".el"))
;; jka-compr (auto-compression-mode, on by default) sets this to `("" ".gz")' so
;; `load' transparently finds and gunzips compressed libraries — the stock Emacs
;; lisp tree ships as `*.el.gz'. The `load' builtin honors the `.gz' rep-suffix.
(defvar load-file-rep-suffixes '("" ".gz"))
;; get-load-suffixes (C `Fget_load_suffixes', lread.c): the cross product of
;; `load-suffixes' with `load-file-rep-suffixes', in the same order the C loop
;; conses then nreverses — suffix0+rep0, suffix0+rep1, suffix1+rep0, ...
(defun get-load-suffixes ()
  "Return the list of suffixes that `load' should try, in order."
  (let ((lst nil))
    (dolist (suffix load-suffixes)
      (dolist (ext load-file-rep-suffixes)
        (setq lst (cons (concat suffix ext) lst))))
    (nreverse lst)))
;; locate-library (subr.el:3153): resolve LIBRARY to the file `load' would pick,
;; searching `load-path' (or PATH) with the load + rep suffixes.
(defun locate-library (library &optional nosuffix path interactive-call)
  "Show the precise file name of Emacs library LIBRARY.
LIBRARY should be a relative file name of the library, a string.
Optional second arg NOSUFFIX non-nil means don't add suffixes.
Optional third arg PATH is a list of directories to search instead
of `load-path'."
  (let ((file (locate-file library
			   (or path load-path)
			   (append (unless nosuffix (get-load-suffixes))
				   load-file-rep-suffixes))))
    (if interactive-call
	(if file
	    (message "Library is file %s" (abbreviate-file-name file))
	  (message "No library %s in search path" library)))
    file))
;; Emacs startup variables (startup.el). `init-file-debug' gates verbose init
;; error reporting; nil by default. `user-init-file'/`user-emacs-directory' are
;; set by real Emacs before init loads — nil here until a caller binds them.
(defvar init-file-debug nil)
(defvar user-init-file nil)
;; custom.el:1216 — searched by `load-theme'/`customize-themes'. Faithful port of
;; the preloaded defvar; value is the literal list `(custom-theme-directory t)'
;; (the two symbols are quoted, not evaluated), matching the real Emacs default.
(defvar custom-theme-load-path (list 'custom-theme-directory t)
  "List of directories to search for custom theme files.")
;; files.el (Emacs 31.1). No file name handlers or remote files here, and no
;; DOS drive letters; case folding follows minibuffer.el's default for
;; `read-file-name-completion-ignore-case', which is what files.el consults.
(defvar read-file-name-completion-ignore-case
  (if (memq system-type '(ms-dos windows-nt darwin cygwin)) t nil))
(defvar file-name-version-regexp
  "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)")
(defun file-name-sans-versions (name &optional keep-backup-version)
  (substring name 0
             (unless keep-backup-version
               (string-match (concat file-name-version-regexp "\\'")
                             name))))
(defun file-relative-name (filename &optional directory)
  (save-match-data
    (setq directory
          (file-name-as-directory (expand-file-name (or directory
                                                        default-directory))))
    (setq filename (expand-file-name filename))
    (let ((fold-case read-file-name-completion-ignore-case)
          (ancestor ".")
          (filename-dir (file-name-as-directory filename)))
      (while (not
              (or (string-prefix-p directory filename-dir fold-case)
                  (string-prefix-p directory filename fold-case)))
        (setq directory (file-name-directory (substring directory 0 -1))
              ancestor (if (equal ancestor ".")
                           ".."
                         (concat "../" ancestor))))
      (if (string-prefix-p directory filename fold-case)
          (let ((rest (substring filename (length directory))))
            (if (and (equal ancestor ".") (not (equal rest "")))
                rest
              (concat (file-name-as-directory ancestor) rest)))
        ancestor))))
;; files.el (Emacs 31.1), without the file-name-handler dispatch. elisprs
;; strings are all multibyte, so `directory-abbrev-make-regexp' never takes
;; its `decode-coding-string' branch.
(defvar directory-abbrev-alist nil)
(defun directory-abbrev-make-regexp (directory)
  (concat "\\`" (regexp-quote directory) "\\(/\\|\\'\\)"))
(defun directory-abbrev-apply (filename)
  (dolist (dir-abbrev directory-abbrev-alist filename)
    (when (string-match (car dir-abbrev) filename)
         (setq filename (concat (cdr dir-abbrev)
                                (substring filename (match-end 0)))))))
(defvar abbreviated-home-dir nil)
(defun abbreviate-file-name (filename)
  (save-match-data
    (let ((case-fold-search (file-name-case-insensitive-p filename)))
      (setq filename (directory-abbrev-apply filename))
      (unless abbreviated-home-dir
        (put 'abbreviated-home-dir 'home (expand-file-name "~"))
        (setq abbreviated-home-dir
              (directory-abbrev-make-regexp
               (let ((abbreviated-home-dir "\\`\\'."))
                 (abbreviate-file-name
                  (get 'abbreviated-home-dir 'home))))))
      (let (mb1)
        (if (and (string-match abbreviated-home-dir filename)
                 (setq mb1 (match-beginning 1))
                 (not (and (= (match-end 0) 1)
                           (= (aref filename 0) ?/)))
                 (not (and (memq system-type '(ms-dos windows-nt cygwin))
                           (string-match "\\`[a-zA-`]:/\\'" filename)))
                 (equal (get 'abbreviated-home-dir 'home)
                        (expand-file-name "~")))
            (setq filename
                  (concat "~"
                          (substring filename mb1))))
        filename))))
;; files.el (Emacs 31.1), without the file-name-handler dispatch. The one
;; `mkdir' is `make-directory-internal' (a Rust subr, fileio.c's).
(defun files--ensure-directory (dir)
  "Make directory DIR if it is not already a directory.
Return non-nil if DIR is already a directory."
  (condition-case err
      (make-directory-internal dir)
    (error
     (or (file-directory-p dir)
	 (signal err)))))
(defun make-directory (dir &optional parents)
  "Create the directory DIR and optionally any nonexistent parent dirs.
Return non-nil if PARENTS is non-nil and DIR already exists as a
directory, and nil if DIR did not already exist but was created.
Signal an error if unsuccessful."
  (setq dir (expand-file-name dir))
  (if (not parents)
      (make-directory-internal dir)
    (let ((dir (directory-file-name (expand-file-name dir)))
	  already-dir create-list parent)
      (while (progn
	       (setq parent (directory-file-name
			     (file-name-directory dir)))
	       (condition-case ()
		   (ignore (setq already-dir
				 (files--ensure-directory dir)))
		 (error
		  ;; Do not loop if root does not exist (Bug#2309).
		  (not (string= dir parent)))))
	(setq create-list (cons dir create-list)
	      dir parent))
      (dolist (dir create-list)
	(setq already-dir (files--ensure-directory dir)))
      already-dir)))
(defun directory-files (dir &optional full match nosort)
  ;; Names in DIR (incl. "." ".."), sorted unless NOSORT, filtered by MATCH regexp;
  ;; with FULL, each name is prefixed with DIR's expanded path (uncollapsed).
  (let ((names (--directory-files-- dir match nosort)))
    (if full
        (let ((d (file-name-as-directory (expand-file-name dir))))
          (mapcar (lambda (n) (concat d n)) names))
      names)))

;; ── exec-path / file-location subsystem ──────────────────────────────────
;; Faithful port of the process/file-search machinery Emacs builds on:
;; `path-separator', `exec-suffixes', `exec-directory', `exec-path',
;; `invocation-name'/`invocation-directory', `executable-find', `locate-file'
;; (the last two are verbatim from files.el; `locate-file-internal' reimplements
;; the C `openp' search from lread.c). Values match `emacs -Q --batch' on unix
;; for the parts that are OS-defined (path-separator, exec-suffixes) and mirror
;; Emacs's structure for the rest.
(defvar path-separator ":"
  "The directory separator in search paths, as a string.")
(defvar exec-suffixes '("")
  "List of suffixes to try to find executable file names (empty on POSIX).")
;; Emacs's `exec-directory' is the libexec dir holding its C helper programs;
;; elisprs has none, so it points at the directory of the running `elisp'
;; binary — a sensible, real directory that keeps `exec-path's structure
;; (PATH dirs + exec-directory) intact. `invocation-name'/`invocation-directory'
;; are the binary's basename and directory, mirroring Emacs's C-level values.
(defvar invocation-name (file-name-nondirectory (--invocation-file--))
  "The program name that was used to run this instance of elisprs.")
(defvar invocation-directory (file-name-directory (--invocation-file--))
  "The directory in which the elisprs executable was found, to run subprocesses.")
(defvar exec-directory (file-name-as-directory (file-name-directory (--invocation-file--)))
  "Directory of architecture-dependent files that come with elisprs.")
;; Emacs's `data-directory' is the `etc/' dir of the installation (a string,
;; used by libraries such as `shadow' via `expand-file-name'); elisprs ships no
;; `etc/', so — like `exec-directory' — it points at the running binary's
;; directory, keeping it a real, absolute string.
(defvar data-directory (file-name-as-directory (file-name-directory (--invocation-file--)))
  "Directory of machine-independent files that come with elisprs.")
;; Built exactly like Emacs's `init_callproc' (callproc.c): `decode_env_path'
;; on $PATH (splitting on `path-separator', empty elements → ".") followed by
;; `exec-directory' with its trailing slash removed (`directory-file-name').
(defvar exec-path
  (append (mapcar (lambda (d) (if (string= d "") "." d))
                  (split-string (or (getenv "PATH") "") path-separator))
          (list (directory-file-name exec-directory)))
  "List of directories to search programs to run in subprocesses.")
;; callproc.c; set per run from $SHELL by src/builtins.rs `install_exec_path'.
(defvar shell-file-name "/bin/sh"
  "File name to load inferior shells from.
Initialized from the SHELL environment variable, or to a system-dependent
default if SHELL is unset.  See Info node `(elisp)Security Considerations'.")
;; simple.el.
(defvar shell-command-switch "-c"
  "Switch used to have the shell execute its command line argument.")
;; elisprs models no remote/TRAMP files, so every file name is local: this
;; returns nil for all inputs (Emacs returns nil for local names too), which
;; makes `executable-find's remote branch dead code (as intended here).
(defun file-remote-p (file &optional _identification _connected)
  "Test whether FILE specifies a location on a remote system.
elisprs has no remote-file support, so this is always nil."
  (ignore file) nil)
(defun locate-file-internal (filename path &optional suffixes predicate)
  "Faithful reimplementation of the C `openp' search backing `locate-file'.
Search each directory in PATH, trying each suffix in SUFFIXES (defaulting to
`(\"\")'), for FILENAME.  Return the first absolute candidate satisfying
PREDICATE, else nil.  PREDICATE nil means `file-readable-p'; an integer is a
POSIX access(2) mode bitmask (1=X_OK 2=W_OK 4=R_OK, 0=existence); a function is
called on the candidate.  Directories are skipped unless PREDICATE is a function
that returns the symbol `dir-ok'.  An absolute or `~'-prefixed FILENAME is tried
once regardless of PATH."
  (let ((suffixes (or suffixes '("")))
        (absolute (and (> (length filename) 0) (memq (aref filename 0) '(?/ ?~)))))
    (catch 'found
      (dolist (dir (if absolute '(nil) path))
        (dolist (suffix suffixes)
          (let* ((candidate (expand-file-name (concat filename suffix) dir))
                 (isdir (file-directory-p candidate)))
            (cond
             ((integerp predicate)
              (when (and (not isdir) (locate-file--access-ok candidate predicate))
                (throw 'found candidate)))
             ((functionp predicate)
              (let ((res (funcall predicate candidate)))
                (when (and res (or (not isdir) (eq res 'dir-ok)))
                  (throw 'found candidate))))
             (t
              (when (and (not isdir) (file-readable-p candidate))
                (throw 'found candidate)))))))
      nil)))
(defun locate-file--access-ok (file mode)
  "Non-nil if FILE passes the POSIX access(2) MODE bitmask (see `locate-file-internal')."
  (and (or (zerop (logand mode 1)) (file-executable-p file))
       (or (zerop (logand mode 2)) (file-writable-p file))
       (or (zerop (logand mode 4)) (file-readable-p file))
       (file-exists-p file)))
(defun locate-file (filename path &optional suffixes predicate)
  "Search for FILENAME through PATH.
If found, return the absolute file name of FILENAME; otherwise return nil.
PATH should be a list of directories to look in, like the lists in `exec-path'
or `load-path'.  If SUFFIXES is non-nil, it should be a list of suffixes to
append to file name when searching.  If SUFFIXES is nil, it is equivalent to
`(\"\")'.  If non-nil, PREDICATE is used instead of `file-readable-p'.
PREDICATE can also be an integer access(2) mode, or one of the symbols
`executable', `readable', `writable', `exists', or a list of them."
  (if (and predicate (symbolp predicate) (not (functionp predicate)))
      (setq predicate (list predicate)))
  (when (and (consp predicate) (not (functionp predicate)))
    (setq predicate
          (logior (if (memq 'executable predicate) 1 0)
                  (if (memq 'writable predicate) 2 0)
                  (if (memq 'readable predicate) 4 0))))
  (locate-file-internal filename path suffixes predicate))
(defun executable-find (command &optional remote)
  "Search for COMMAND in `exec-path' and return the absolute file name.
Return nil if COMMAND is not found anywhere in `exec-path'.
If REMOTE is non-nil, search on a remote host if `default-directory' is
remote, otherwise search locally."
  (if (and remote (file-remote-p default-directory))
      (let ((res (locate-file
                  command
                  (mapcar
                   (lambda (x) (concat (file-remote-p default-directory) x))
                   (exec-path))
                  exec-suffixes 'file-executable-p)))
        (when (stringp res) (file-local-name res)))
    ;; Use 1 rather than file-executable-p to better match the
    ;; behavior of call-process.
    (let ((default-directory (file-name-quote default-directory 'top)))
      (locate-file command exec-path exec-suffixes 1))))

;; save-current-buffer: restore the current buffer after BODY (if it is still live).
(defmacro save-current-buffer (&rest body)
  `(let ((--scb-- (current-buffer)))
     (unwind-protect (progn ,@body)
       (when (buffer-live-p --scb--) (set-buffer --scb--)))))
;; with-current-buffer: evaluate BODY with BUFFER-OR-NAME current, restoring after.
(defmacro with-current-buffer (buffer-or-name &rest body)
  (declare (indent 1) (debug t))
  `(save-current-buffer (set-buffer ,buffer-or-name) ,@body))
;; subr.el (Emacs 31.1), verbatim.
(defmacro with-temp-buffer (&rest body)
  "Create a temporary buffer, and evaluate BODY there like `progn'.
The buffer does not run the hooks `kill-buffer-hook',
`kill-buffer-query-functions', and `buffer-list-update-hook'.
See also `with-temp-file' and `with-output-to-string'."
  (declare (indent 0) (debug t))
  (let ((temp-buffer (make-symbol "temp-buffer")))
    `(let ((,temp-buffer (generate-new-buffer " *temp*" t)))
       ;; `kill-buffer' can change current-buffer in some odd cases.
       (with-current-buffer ,temp-buffer
         (unwind-protect
	     (progn ,@body)
           (and (buffer-name ,temp-buffer)
                (kill-buffer ,temp-buffer)))))))
;; subr.el's `with-output-to-string': BODY prints into a fresh buffer bound as
;; `standard-output', whose text is the value.
(defmacro with-output-to-string (&rest body)
  "Execute BODY, return the text it sent to `standard-output', as a string."
  (declare (indent 0) (debug t))
  `(let ((standard-output (generate-new-buffer " *string-output*" t)))
     (unwind-protect
         (progn
           (let ((standard-output standard-output))
             ,@body)
           (with-current-buffer standard-output
             (buffer-string)))
       (kill-buffer standard-output))))
;; subr.el (Emacs 31.1): `process-lines' runs PROGRAM through `call-process'.
(defun process-lines-handling-status (program status-handler &rest args)
  "Execute PROGRAM with ARGS, returning its output as a list of lines.
If STATUS-HANDLER is non-nil, it must be a function with one
argument, which will be called with the exit status of the
program before the output is collected.  If STATUS-HANDLER is
nil, an error is signaled if the program returns with a non-zero
exit status."
  (with-temp-buffer
    (let ((status (apply #'call-process program nil (current-buffer) nil args)))
      (if status-handler
	  (funcall status-handler status)
	(unless (eq status 0)
	  (error "%s exited with status %s" program status)))
      (goto-char (point-min))
      (let (lines)
	(while (not (eobp))
	  (setq lines (cons (buffer-substring-no-properties
			     (line-beginning-position)
			     (line-end-position))
			    lines))
	  (forward-line 1))
	(nreverse lines)))))
(defun process-lines (program &rest args)
  "Execute PROGRAM with ARGS, returning its output as a list of lines.
Signal an error if the program returns with a non-zero exit status.
Also see `process-lines-ignore-status'."
  (apply #'process-lines-handling-status program nil args))
(defun process-lines-ignore-status (program &rest args)
  "Execute PROGRAM with ARGS, returning its output as a list of lines.
The exit status of the program is ignored.
Also see `process-lines'."
  (apply #'process-lines-handling-status program #'ignore args))
;;; ---- format-spec.el ----
;; Faithful port of format-spec.el (Emacs 30.2). The previous implementation
;; substituted %CHAR and nothing else: it dropped the flag/width/precision
;; syntax silently, so `(format-spec "%-5a|" '((?a . "x")))' answered "5a|" —
;; the width digits fell through as literal text.
(defun format-spec (format specification &optional ignore-missing split)
  "Return a string based on FORMAT and SPECIFICATION.
Each %-spec may carry flags, a width and a precision:

  %<flags><width><precision>character

Flags: 0 pad with zeros, - pad on the right, < truncate on the left,
> truncate on the right, ^ upcase, _ downcase.

IGNORE-MISSING nil signals on a %-spec with no entry in SPECIFICATION;
`ignore' leaves it verbatim, `delete' removes it.  With SPLIT, return the
list of pieces instead of one string."
  (with-temp-buffer
    (let ((split-start (point-min))
          (split-result nil))
      (insert format)
      (goto-char (point-min))
      (while (search-forward "%" nil t)
        (cond
         ;; Quoted percent sign.
         ((= (following-char) ?%)
          (when (memq ignore-missing '(nil ignore delete))
            (delete-char 1)))
         ;; Valid format spec.
         ((looking-at "\\([ 0<>^_-]+\\)?\\([0-9]+\\)?\\(\\.[0-9]+\\)?\\([[:alpha:]]\\)")
          (let* ((beg (point))
                 (end (match-end 0))
                 (flags (match-string 1))
                 (width (match-string 2))
                 (trunc (match-string 3))
                 (char (string-to-char (match-string 4)))
                 (text (let ((res (cdr (assq char specification))))
                         (if (functionp res) (funcall res) res))))
            (when (and split (not (= (1- beg) split-start)))
              (push (buffer-substring split-start (1- beg)) split-result))
            (cond (text
                   (setq text (format-spec--do-flags
                               (format "%s" text)
                               (format-spec--parse-flags flags)
                               (and width (string-to-number width))
                               (and trunc (car (read-from-string trunc 1)))))
                   ;; Insert first, to preserve text properties.
                   (insert-and-inherit text)
                   ;; Delete the specifier body.
                   (delete-region (point) (+ end (length text)))
                   ;; Delete the percent sign.
                   (delete-region (1- beg) beg))
                  ((eq ignore-missing 'delete)
                   (delete-region (1- beg) end))
                  ((not ignore-missing)
                   (error "Invalid format character: `%%%c'" char)))
            (when split
              (push (buffer-substring (1- beg) (point)) split-result)
              (setq split-start (point)))))
         ;; Signal an error on bogus format strings.
         ((not ignore-missing)
          (error "Invalid format string"))))
      (if (not split)
          (buffer-string)
        (unless (= split-start (point-max))
          (push (buffer-substring split-start (point-max)) split-result))
        (nreverse split-result)))))

(defun format-spec--do-flags (str flags width trunc)
  "Return STR formatted according to FLAGS, WIDTH, and TRUNC."
  (let (diff str-width)
    ;; Truncate original string first, like `format' does.
    (when trunc
      (setq str-width (string-width str))
      (when (> (setq diff (- str-width trunc)) 0)
        (setq str (if (memq :chop-left flags)
                      (truncate-string-to-width str str-width diff)
                    (format (format "%%.%ds" trunc) str))
              str-width trunc)))
    ;; Pad or chop to width.
    (when width
      (setq str-width (or str-width (string-width str))
            diff (- width str-width))
      (cond ((zerop diff))
            ((> diff 0)
             (let ((pad (make-string diff (if (memq :pad-zero flags) ?0 ?\s))))
               (setq str (if (memq :pad-right flags)
                             (concat str pad)
                           (concat pad str)))))
            ((memq :chop-left flags)
             (setq str (truncate-string-to-width str str-width (- diff))))
            ((memq :chop-right flags)
             (setq str (format (format "%%.%ds" width) str))))))
  ;; Fiddle case.
  (cond ((memq :upcase flags) (upcase str))
        ((memq :downcase flags) (downcase str))
        (str)))

(defun format-spec--parse-flags (flags)
  "Convert sequence of FLAGS to list of human-readable keywords."
  (mapcan (lambda (char)
            (cond ((eq char ?0) (list :pad-zero))
                  ((eq char ?-) (list :pad-right))
                  ((eq char ?<) (list :chop-left))
                  ((eq char ?>) (list :chop-right))
                  ((eq char ?^) (list :upcase))
                  ((eq char ?_) (list :downcase))))
          flags))

(defun format-spec-make (&rest pairs)
  "Return an alist suitable for use in `format-spec' based on PAIRS.
PAIRS is a property list with characters as keys."
  (let (alist)
    (while pairs
      (unless (cdr pairs)
        (error "Invalid list of pairs"))
      (push (cons (car pairs) (cadr pairs)) alist)
      (setq pairs (cddr pairs)))
    (nreverse alist)))
;; save-excursion: restore the current buffer AND point after BODY. Point is saved
;; as a marker-like position that tracks insertions/deletions during BODY.
(defmacro save-excursion (&rest body)
  `(let ((--se-b-- (current-buffer)))
     (--se-push--)
     (unwind-protect (progn ,@body)
       (when (buffer-live-p --se-b--) (set-buffer --se-b--))
       (--se-pop--))))
;; save-restriction: restore the buffer's narrowing after BODY (the saved bounds
;; track edits made in BODY, like Emacs markers).
;; ---- overlays: the subr.el layer over the primitives ----
;; `overlay-recenter' was an optimisation hint for Emacs's old overlay
;; representation; it has been a no-op there since the interval tree landed, and
;; elisprs scans a per-buffer list, so it is one here too.
(defun overlay-recenter (_pos) nil)
(defun copy-overlay (o)
  "Return a copy of overlay O, with the same range, buffer and properties."
  (let ((o1 (if (overlay-buffer o)
                (make-overlay (overlay-start o) (overlay-end o) (overlay-buffer o) nil nil)
              ;; A detached overlay copies to a detached overlay.
              (let ((tmp (make-overlay (point-min) (point-min))))
                (delete-overlay tmp)
                tmp)))
        (props (overlay-properties o)))
    (while props
      (overlay-put o1 (pop props) (pop props)))
    o1))
(defun remove-overlays (&optional beg end name val)
  "Remove overlays between BEG and END whose property NAME is `eq' to VAL.
An overlay that only partly overlaps the range is MOVED out of it rather than
removed, and one that spans the range is split in two -- which is why this needs
`copy-overlay' and cannot just delete what `overlays-in' reports."
  (unless beg (setq beg (point-min)))
  (unless end (setq end (point-max)))
  (overlay-recenter end)
  (if (< end beg) (setq beg (prog1 end (setq end beg))))
  (save-excursion
    (dolist (o (overlays-in beg end))
      (when (eq (overlay-get o name) val)
        (if (< (overlay-start o) beg)
            (if (> (overlay-end o) end)
                (progn
                  (move-overlay (copy-overlay o) (overlay-start o) beg)
                  (move-overlay o end (overlay-end o)))
              (move-overlay o (overlay-start o) beg))
          (if (> (overlay-end o) end)
              (move-overlay o end (overlay-end o))
            (delete-overlay o)))))))

(defmacro save-restriction (&rest body)
  `(progn (--save-restriction--)
     (unwind-protect (progn ,@body) (--restore-restriction--))))
;; Region case conversion: rewrite [BEG,END) through FN. A length-preserving
;; result overwrites the text in place, as casefiddle.c's `casify_region'
;; does (markers, point and text properties stay; one `modify_text' of the
;; whole region); a result of another length is deleted and re-inserted.
(defun buffer--map-region (beg end fn)
  (let* ((lo (min beg end)) (hi (max beg end))
         (new (funcall fn (buffer-substring-no-properties lo hi))))
    (unless (elisprs--replace-chars-in-place lo hi new)
      (save-excursion
        (let ((s (buffer-substring lo hi)))
          (delete-region lo hi)
          (goto-char lo)
          (insert (funcall fn s)))))))
(defun upcase-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'upcase) nil)
(defun downcase-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'downcase) nil)
(defun capitalize-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'capitalize) nil)
;; casefiddle.c `Fupcase_initials_region': CASE_CAPITALIZE_UP, like `capitalize-region'
;; but leaving the rest of each word as it is.
(defun upcase-initials-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'upcase-initials) nil)
;; editfns.c `Fsubst_char_in_region': the text from the first FROMCHAR to END
;; is rewritten in place (one `modify_text' from there), and nothing at all
;; happens when FROMCHAR does not occur.
;; Case-convert ARG words forward from point, leaving point after them.
(defun buffer--case-word (arg fn)
  (let ((beg (point)))
    (forward-word arg)
    (let* ((end (point)) (lo (min beg end)) (hi (max beg end)) (s (buffer-substring lo hi)))
      (delete-region lo hi)
      (goto-char lo)
      (insert (funcall fn s))
      (goto-char (+ lo (length s))))))
(defun upcase-word (arg) (interactive "p") (buffer--case-word arg #'upcase) nil)
(defun downcase-word (arg) (interactive "p") (buffer--case-word arg #'downcase) nil)
(defun capitalize-word (arg) (interactive "p") (buffer--case-word arg #'capitalize) nil)
;; The kill ring, ported from simple.el / subr.el (Emacs 31.1). There is no
;; window system here, so the interprogram cut/paste hooks start nil (in
;; `emacs --batch' they are `gui-select-text'/`gui-selection-value', which do
;; nothing there either), and no command loop, so `last-command' stays nil
;; and successive kills never append.
(defvar kill-ring nil)
(defvar kill-ring-max 120)
(defvar kill-ring-yank-pointer nil)
(defvar kill-do-not-save-duplicates nil)
(defvar kill-transform-function nil)
(defvar kill-read-only-ok nil)
(defvar kill-whole-line nil)
(defvar kill-append-merge-undo nil)
(defvar show-trailing-whitespace nil)
(defvar interprogram-cut-function nil)
(defvar interprogram-paste-function nil)
(defvar save-interprogram-paste-before-kill nil)
(defvar yank-pop-change-selection nil)
(defvar yank-excluded-properties
  '(category field follow-link fontified font-lock-face help-echo intangible
    invisible keymap local-map mouse-face read-only yank-handler))
(defvar yank-transform-functions nil)
(defvar yank-undo-function nil)
(defvar this-command nil)
(defvar last-command nil)
(defvar history-length 100)
(defvar history-delete-duplicates nil)
(defvar-local mark-ring nil)
(defvar mark-ring-max 16)
(defvar filter-buffer-substring-function #'buffer-substring--filter)
(defun add-to-history (history-var newelt &optional maxelt keep-all)
  (unless maxelt
    (setq maxelt (or (get history-var 'history-length)
                     history-length)))
  (let ((history (symbol-value history-var))
        tail)
    (when (and (listp history)
               (or keep-all
                   (not (stringp newelt))
                   (> (length newelt) 0))
               (or keep-all
                   (not (equal (car history) newelt))))
      (if history-delete-duplicates
          (setq history (delete newelt history)))
      (setq history (cons newelt history))
      (when (integerp maxelt)
        (if (>= 0 maxelt)
            (setq history nil)
          (setq tail (nthcdr (1- maxelt) history))
          (when (consp tail)
            (setcdr tail nil))))
      (set history-var history))))
(defun remove-list-of-text-properties (start end list-of-properties &optional object)
  (remove-text-properties start end
                          (mapcan (lambda (p) (list p nil)) list-of-properties)
                          object))
(defun remove-yank-excluded-properties (beg end)
  (let ((inhibit-read-only t))
    (if (eq yank-excluded-properties t)
        (set-text-properties beg end nil)
      (remove-list-of-text-properties beg end yank-excluded-properties))))
(defun buffer-substring--filter (beg end &optional delete)
  (cond
   (delete
    (save-excursion
      (goto-char beg)
      (delete-and-extract-region beg end)))
   (t
    (buffer-substring beg end))))
(defun filter-buffer-substring (beg end &optional delete)
  (funcall filter-buffer-substring-function beg end delete))
(defun kill-new (string &optional replace)
  (when (or (not kill-transform-function)
            (setq string (funcall kill-transform-function string)))
    (unless (and kill-do-not-save-duplicates
                 (equal-including-properties string (car kill-ring)))
      (if (and replace kill-ring)
          (setcar kill-ring string)
        (let ((history-delete-duplicates nil))
          (add-to-history 'kill-ring string kill-ring-max t))))
    (setq kill-ring-yank-pointer kill-ring)
    (if interprogram-cut-function
        (funcall interprogram-cut-function string))))
(defun kill-append (string before-p)
  (let ((cur (car kill-ring)))
    (kill-new (if before-p (concat string cur) (concat cur string))
              (or (= (length cur) 0)
                  (null (get-text-property 0 'yank-handler cur))))))
(defun current-kill (n &optional do-not-move)
  (let ((interprogram-paste (and (= n 0)
                                 interprogram-paste-function
                                 (funcall interprogram-paste-function))))
    (if interprogram-paste
        (progn
          (let ((interprogram-cut-function nil)
                (interprogram-paste-function nil))
            (if (listp interprogram-paste)
                (mapc #'kill-new (reverse interprogram-paste))
              (kill-new interprogram-paste)))
          (car kill-ring))
      (or kill-ring (error "Kill ring is empty"))
      (let ((ARGth-kill-element
             (nthcdr (mod (- n (length kill-ring-yank-pointer))
                          (length kill-ring))
                     kill-ring)))
        (unless do-not-move
          (setq kill-ring-yank-pointer ARGth-kill-element)
          (when (and yank-pop-change-selection
                     (> n 0)
                     interprogram-cut-function)
            (funcall interprogram-cut-function (car ARGth-kill-element))))
        (car ARGth-kill-element)))))
(defun rotate-yank-pointer (arg) (current-kill arg))
(defun kill-region (beg end &optional region)
  (condition-case nil
      (let ((string (if region
                        (filter-buffer-substring (region-beginning) (region-end) 'delete)
                      (filter-buffer-substring beg end 'delete))))
        (when string
          (if (eq last-command 'kill-region)
              (kill-append string (< end beg))
            (kill-new string)))
        (when (or string (eq last-command 'kill-region))
          (setq this-command 'kill-region))
        (setq deactivate-mark t)
        nil)
    ((buffer-read-only text-read-only)
     (copy-region-as-kill beg end region)
     (setq this-command 'kill-region)
     (if kill-read-only-ok
         (progn (message "Read only text copied to kill ring") nil)
       (barf-if-buffer-read-only)
       (signal 'text-read-only (list (current-buffer)))))))
(defun copy-region-as-kill (beg end &optional region)
  (let ((str (if region
                 (filter-buffer-substring (region-beginning) (region-end))
               (filter-buffer-substring beg end))))
    (if (eq last-command 'kill-region)
        (kill-append str (< end beg))
      (kill-new str)))
  (setq deactivate-mark t)
  nil)
(defun kill-ring-save (beg end &optional region)
  (copy-region-as-kill beg end region)
  nil)
(defun barf-if-buffer-read-only (&optional position)
  (when (and buffer-read-only
             (not inhibit-read-only)
             (not (and position (get-text-property position 'inhibit-read-only))))
    (signal 'buffer-read-only (list (current-buffer)))))
(defun forward-visible-line (arg)
  (condition-case nil
      (if (> arg 0)
          (while (> arg 0)
            (or (zerop (forward-line 1))
                (signal 'end-of-buffer nil))
            (setq arg (1- arg)))
        (let ((first t))
          (while (or first (<= arg 0))
            (if first
                (beginning-of-line)
              (or (zerop (forward-line -1))
                  (signal 'beginning-of-buffer nil)))
            (unless (bobp)
              (setq arg (1+ arg)))
            (setq first nil))))
    ((beginning-of-buffer end-of-buffer)
     nil)))
(defun end-of-visible-line () (end-of-line))
(defun kill-line (&optional arg)
  (kill-region (point)
               (progn
                 (if arg
                     (forward-visible-line (prefix-numeric-value arg))
                   (if (eobp)
                       (signal 'end-of-buffer nil))
                   (let ((end
                          (save-excursion
                            (end-of-visible-line) (point))))
                     (if (or (save-excursion
                               (unless show-trailing-whitespace
                                 (skip-chars-forward " \t" end))
                               (= (point) end))
                             (and kill-whole-line (bolp)))
                         (forward-visible-line 1)
                       (goto-char end))))
                 (point))))
(defun kill-word (arg)
  (kill-region (point) (progn (forward-word arg) (point))))
(defun backward-kill-word (arg)
  (kill-word (- arg)))
;;; ---- the mark (simple.el, Emacs 31.1) ----
;; `mark-marker' is a Rust subr (the buffer's marker); `region-beginning' and
;; `region-end' are editfns.c's. The C variables keep their batch values.
(defvar transient-mark-mode nil)
(defvar mark-even-if-inactive t)
(defvar select-active-regions t)
(defvar saved-region-selection nil)
(defvar executing-kbd-macro nil)
(defvar last-input-event nil)
(defvar global-mark-ring nil)
(defvar global-mark-ring-max 16)
(defvar use-empty-active-region nil)
(defvar exchange-point-and-mark-highlight-region t)
(defvar activate-mark-hook nil)
(defvar deactivate-mark-hook nil)
(define-error 'mark-inactive "The mark is not active now")
(defun mouse-movement-p (object)
  (eq (car-safe object) 'mouse-movement))
;; minibuf.c: no minibuffer is ever active in batch.
(defun minibuffer-depth () 0)
(defvar region-extract-function
  (lambda (method)
    (let ((beg (region-beginning)))
      (cond
       ((eq method 'bounds)
        (list (cons beg (region-end))))
       ((eq method 'delete-only)
        (delete-region beg (region-end)))
       (t
        (filter-buffer-substring beg (region-end) method))))))
(defun mark (&optional force)
  (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
      (marker-position (mark-marker))
    (signal 'mark-inactive nil)))
;; Not followed: the PRIMARY-selection update (guarded by
;; `display-selections-p', nil without a window system) and the region
;; highlight of `redisplay--update-region-highlight' (elisprs has no windows).
(defun deactivate-mark (&optional force)
  (when (or (region-active-p) force)
    (when mark-active (force-mode-line-update))
    (cond
     ((eq (car-safe transient-mark-mode) 'only)
      (setq transient-mark-mode (cdr transient-mark-mode))
      (if (eq transient-mark-mode (default-value 'transient-mark-mode))
          (kill-local-variable 'transient-mark-mode)))
     ((eq transient-mark-mode 'lambda)
      (kill-local-variable 'transient-mark-mode)))
    (setq mark-active nil)
    (run-hooks 'deactivate-mark-hook)))
(defun activate-mark (&optional no-tmm)
  (when (mark t)
    (unless (region-active-p)
      (force-mode-line-update)
      (setq mark-active t)
      (unless (or transient-mark-mode no-tmm)
        (setq-local transient-mark-mode 'lambda))
      (run-hooks 'activate-mark-hook))))
(defun set-mark (pos)
  (if pos
      (progn
        (set-marker (mark-marker) pos (current-buffer))
        (activate-mark 'no-tmm))
    (deactivate-mark t)
    (setq mark-active nil)
    (set-marker (mark-marker) nil)))
(defun use-region-p ()
  (and (region-active-p)
       (or (> (region-end) (region-beginning))
           (and use-empty-active-region
                (not (eq (car-safe last-input-event) 'down-mouse-1))
                (not (mouse-movement-p last-input-event))))))
(defun use-region-beginning ()
  (and (use-region-p) (region-beginning)))
(defun use-region-end ()
  (and (use-region-p) (region-end)))
(defun use-region-noncontiguous-p ()
  (and (use-region-p) (region-noncontiguous-p)))
(defun region-bounds ()
  (funcall region-extract-function 'bounds))
(defun region-noncontiguous-p ()
  (let ((bounds (region-bounds))) (and (cdr bounds) bounds)))
(defun push-mark (&optional location nomsg activate)
  (when (mark t)
    (let ((old (nth mark-ring-max mark-ring))
          (history-delete-duplicates nil))
      (add-to-history 'mark-ring (copy-marker (mark-marker)) mark-ring-max t)
      (when old
        (set-marker old nil))))
  (set-marker (mark-marker) (or location (point)) (current-buffer))
  (unless (and global-mark-ring
               (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
    (let ((old (nth global-mark-ring-max global-mark-ring))
          (history-delete-duplicates nil))
      (add-to-history
       'global-mark-ring (copy-marker (mark-marker)) global-mark-ring-max t)
      (when old
        (set-marker old nil))))
  (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
      (message "Mark set"))
  (if (or activate (not transient-mark-mode))
      (set-mark (mark t)))
  nil)
(defun pop-mark ()
  (when mark-ring
    (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
    (set-marker (mark-marker) (car mark-ring))
    (set-marker (car mark-ring) nil)
    (pop mark-ring))
  (deactivate-mark))
(defun save-mark-and-excursion--save ()
  (cons
   (let ((mark (mark-marker)))
     (and (marker-position mark) (copy-marker mark)))
   mark-active))
(defun save-mark-and-excursion--restore (saved-mark-info)
  (let ((saved-mark (car saved-mark-info))
        (omark (marker-position (mark-marker)))
        (nmark nil)
        (saved-mark-active (cdr saved-mark-info)))
    (if (null saved-mark)
        (set-marker (mark-marker) nil)
      (setf nmark (marker-position saved-mark))
      (set-marker (mark-marker) nmark)
      (set-marker saved-mark nil))
    (let ((cur-mark-active mark-active))
      (setq mark-active saved-mark-active)
      (if saved-mark-active
          (when (or (not cur-mark-active)
                    (not (eq omark nmark)))
            (run-hooks 'activate-mark-hook))
        (when cur-mark-active
          (run-hooks 'deactivate-mark-hook))))))
(defmacro save-mark-and-excursion (&rest body)
  (declare (indent 0) (debug t))
  (let ((saved-marker-sym (make-symbol "saved-marker")))
    `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
       (unwind-protect
            (save-excursion ,@body)
         (save-mark-and-excursion--restore ,saved-marker-sym)))))
;; keyboard.c's `translation-table-for-input' is nil in batch.
(defvar translation-table-for-input nil)
(defun zap-to-char (arg char &optional interactive)
  (with-no-warnings
    (if (char-table-p translation-table-for-input)
	(setq char (or (aref translation-table-for-input char) char))))
  (let ((case-fold-search (if (and interactive (char-uppercase-p char))
                              nil
                            case-fold-search)))
    (kill-region (point) (search-forward (char-to-string char) nil nil arg))))
;; misc.el
(defun zap-up-to-char (arg char &optional interactive)
  (let ((direction (if (>= arg 0) 1 -1))
        (case-fold-search (if (and interactive (char-uppercase-p char))
                              nil
                            case-fold-search)))
    (kill-region (point)
		 (progn
		   (forward-char direction)
		   (unwind-protect
		       (search-forward (char-to-string char) nil nil arg)
		     (backward-char direction))
		   (point)))))
(defun kill-whole-line (&optional arg)
  (or arg (setq arg 1))
  (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
      (signal 'end-of-buffer nil))
  (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
      (signal 'beginning-of-buffer nil))
  (unless (eq last-command 'kill-region)
    (kill-new "")
    (setq last-command 'kill-region))
  (let ((regions-begin (point-marker))
        (region1-end (cond ((zerop arg)
                            (prog1 (save-excursion
                                     (forward-visible-line 0)
                                     (point-marker))
                              (end-of-visible-line)))
	                   ((< arg 0)
	                    (prog1 (save-excursion
                                     (end-of-visible-line)
                                     (point-marker))
                              (forward-visible-line (1+ arg))
	                      (unless (bobp) (backward-char))))
	                   (t
	                    (prog1 (save-excursion
                                     (forward-visible-line 0)
                                     (point-marker))
	                      (forward-visible-line arg))))))
    (let ((kill-read-only-ok (or kill-read-only-ok
                                 (/= regions-begin (point)))))
      (kill-region (marker-position regions-begin)
                   (marker-position region1-end)))
    (kill-region (marker-position regions-begin)
                 (point))
    (set-marker regions-begin nil)
    (set-marker region1-end nil)))
(defun mark-word (&optional arg allow-extend)
  (cond ((and allow-extend
	      (or (and (eq last-command this-command) (mark t))
		  (region-active-p)))
	 (setq arg (if arg (prefix-numeric-value arg)
		     (if (< (mark) (point)) -1 1)))
	 (set-mark
	  (save-excursion
	    (goto-char (mark))
	    (forward-word arg)
	    (point))))
	(t
	 (push-mark
	  (save-excursion
	    (forward-word (prefix-numeric-value arg))
	    (point))
	  nil t))))
;; emacs-lisp/lisp.el
(defun mark-sexp (&optional arg allow-extend)
  (cond ((and allow-extend
	      (or (and (eq last-command this-command) (mark t))
		  (and transient-mark-mode mark-active)))
	 (setq arg (if arg (prefix-numeric-value arg)
		     (if (< (mark) (point)) -1 1)))
	 (set-mark
	  (save-excursion
	    (goto-char (mark))
            (condition-case error
	        (forward-sexp arg)
              (scan-error
               (user-error (if (equal (cadr error)
                                      "Containing expression ends prematurely")
                               "No more sexp to select"
                             (cadr error)))))
	    (point))))
	(t
	 (push-mark
	  (save-excursion
            (condition-case error
	        (forward-sexp (prefix-numeric-value arg))
              (scan-error
               (user-error (if (equal (cadr error)
                                      "Containing expression ends prematurely")
                               "No sexp to select"
                             (cadr error)))))
	    (point))
	  nil t))))
(defun kill-sexp (&optional arg interactive)
  (if interactive
      (condition-case _
          (kill-sexp arg nil)
        (scan-error (user-error (if (> arg 0)
                                    "No next sexp"
                                  "No previous sexp"))))
    (let ((opoint (point)))
      (forward-sexp (or arg 1))
      (kill-region opoint (point)))))
(defun backward-kill-sexp (&optional arg interactive)
  (kill-sexp (- (or arg 1)) interactive))
(defun upcase-dwim (arg)
  (if (use-region-p)
      (upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
    (upcase-word arg)))
(defun downcase-dwim (arg)
  (if (use-region-p)
      (downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
    (downcase-word arg)))
(defun capitalize-dwim (arg)
  (if (use-region-p)
      (capitalize-region (region-beginning) (region-end) (region-noncontiguous-p))
    (capitalize-word arg)))
(defun exchange-point-and-mark (&optional arg)
  (let ((omark (mark t))
        (region-was-active (region-active-p))
	(temp-highlight (eq (car-safe transient-mark-mode) 'only)))
    (if (null omark)
        (user-error "No mark set in this buffer"))
    (set-mark (point))
    (goto-char omark)
    (cond (temp-highlight)
          ((xor arg (if exchange-point-and-mark-highlight-region
                        (not (region-active-p))
                      (not region-was-active)))
	   (deactivate-mark))
	  (t (activate-mark)))
    nil))
(defun insert-for-yank (string)
  (run-hook-wrapped 'yank-transform-functions
                    (lambda (f) (setq string (funcall f string)) nil))
  (let (to)
    (while (setq to (next-single-property-change 0 'yank-handler string))
      (insert-for-yank-1 (substring string 0 to))
      (setq string (substring string to))))
  (insert-for-yank-1 string))
(defun insert-for-yank-1 (string)
  (let* ((handler (and (stringp string)
                       (get-text-property 0 'yank-handler string)))
         (param (or (nth 1 handler) string))
         (opoint (point))
         end)
    (setq yank-undo-function t)
    (if (nth 0 handler)
        (funcall (car handler) param)
      (insert param))
    (setq end (point))
    (unless (nth 2 handler)
      (remove-yank-excluded-properties opoint end))
    (if (and (> end opoint)
             (text-properties-at (1- end)))
        (put-text-property (1- end) end 'rear-nonsticky t))
    (if (eq yank-undo-function t)
        (setq yank-undo-function (nth 3 handler)))
    (if (nth 4 handler)
        (setq this-command (nth 4 handler)))))
(defun yank (&optional arg)
  (setq yank-window-start (window-start))
  (setq this-command t)
  (push-mark)
  (insert-for-yank (current-kill (cond
                                  ((listp arg) 0)
                                  ((eq arg '-) -2)
                                  (t (1- arg)))))
  (if (consp arg)
      (goto-char (prog1 (mark t)
                   (set-marker (mark-marker) (point) (current-buffer)))))
  (if (eq this-command t)
      (setq this-command 'yank))
  nil)
(defun transpose-chars (arg)
  (when (and (eolp) (not (bobp))
             (not (get-text-property (1- (point)) 'read-only)))
    (forward-char -1))
  (transpose-subr #'forward-char arg))
(defun transpose-words (arg)
  (transpose-subr 'forward-word arg))
(defun transpose-lines (arg)
  (transpose-subr (lambda (arg)
                    (if (> arg 0)
                        (progn
                          (setq arg (forward-line arg))
                          (if (/= (preceding-char) ?\n)
                              (setq arg (1+ arg)))
                          (if (> arg 0)
                              (newline arg)))
                      (forward-line arg)))
                  arg))
(defun transpose-subr (mover arg &optional special)
  (let ((aux (if special mover
               (lambda (x)
                 (cons (progn (funcall mover x) (point))
                       (progn (funcall mover (- x)) (point))))))
        pos1 pos2)
    (cond
     ((= arg 0)
      (save-excursion
        (setq pos1 (funcall aux 1))
        (goto-char (or (mark) (error "No mark set in this buffer")))
        (setq pos2 (funcall aux 1))
        (transpose-subr-1 pos1 pos2))
      (goto-char (prog1 (mark t) (set-mark (point)))))
     ((> arg 0)
      (setq pos1 (funcall aux -1))
      (setq pos2 (funcall aux arg))
      (transpose-subr-1 pos1 pos2)
      (goto-char (car pos2)))
     (t
      (setq pos1 (funcall aux -1))
      (goto-char (car pos1))
      (setq pos2 (funcall aux arg))
      (transpose-subr-1 pos1 pos2)
      (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
(defun transpose-subr-1 (pos1 pos2)
  (unless (and pos1 pos2)
    (error "Don't have two things to transpose"))
  (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
  (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
  (when (> (car pos1) (car pos2))
    (let ((swap pos1))
      (setq pos1 pos2 pos2 swap)))
  (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
  (let* ((word (buffer-substring (car pos2) (cdr pos2)))
         (len1 (- (cdr pos1) (car pos1)))
         (len2 (length word))
         (boundary (make-marker)))
    (set-marker boundary (car pos2))
    (goto-char (cdr pos1))
    (insert-before-markers word)
    (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
    (goto-char boundary)
    (insert word)
    (goto-char (+ boundary len1))
    (delete-region (point) (+ (point) len2))
    (set-marker boundary nil)))
(defvar inhibit-read-only nil)
(defun buffer-narrowed-p ()
  (/= (- (point-max) (point-min)) (buffer-size)))
;; subr.el (Emacs 31.1) motion by whitespace runs and by symbols.
(defun forward-whitespace (arg)
  (if (natnump arg)
      (re-search-forward "[ \t]+\\|\n" nil 'move arg)
    (while (< arg 0)
      (if (re-search-backward "[ \t]+\\|\n" nil 'move)
          (or (eq (char-after (match-beginning 0)) ?\n)
              (skip-chars-backward " \t")))
      (setq arg (1+ arg)))))
(defun forward-symbol (arg)
  (if (natnump arg)
      (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
    (while (< arg 0)
      (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
          (skip-syntax-backward "w_"))
      (setq arg (1+ arg)))))
(defun forward-same-syntax (&optional arg)
  (or arg (setq arg 1))
  (while (< arg 0)
    (skip-syntax-backward
     (char-to-string (char-syntax (char-before))))
    (setq arg (1+ arg)))
  (while (> arg 0)
    (skip-syntax-forward (char-to-string (char-syntax (char-after))))
    (setq arg (1- arg))))
;; thingatpt.el (Emacs 31.1): the generic THING machinery and the things
;; that need no window, URL or file-system support.
(defvar thing-at-point-provider-alist nil)
(defvar forward-thing-provider-alist nil)
(defvar bounds-of-thing-at-point-provider-alist nil)
(defun forward-thing (thing &optional n)
  (setq n (or n 1))
  (if (assq thing forward-thing-provider-alist)
      (let* ((backward (< n 0))
             (reducer (if backward #'max #'min))
             (limit (if backward (point-min) (point-max))))
        (catch 'done
          (dotimes (_ (abs n))
            (let ((new-point (seq-reduce
                              (lambda (value elt)
                                (if (eq (car elt) thing)
                                    (save-excursion
                                      (funcall (cdr elt) backward)
                                      (if value
                                          (funcall reducer value (point))
                                        (point)))
                                  value))
                              forward-thing-provider-alist nil)))
              (if (and new-point (/= new-point (point)))
                  (goto-char new-point)
                (goto-char limit)
                (throw 'done t))))))
    (let ((forward-op (or (get thing 'forward-op)
                          (intern-soft (format "forward-%s" thing)))))
      (if (functionp forward-op)
          (funcall forward-op n)
        (error "Can't determine how to move over a %s" thing)))))
(defun bounds-of-thing-at-point (thing)
  (cond
   ((seq-some (lambda (elt)
                (and (eq (car elt) thing)
                     (funcall (cdr elt))))
              bounds-of-thing-at-point-provider-alist))
   ((get thing 'bounds-of-thing-at-point)
    (funcall (get thing 'bounds-of-thing-at-point)))
   ((and (not (eq thing 'whitespace))
         (save-excursion
           (goto-char (point-min))
           (not (re-search-forward "[^\t\n ]" nil t))))
    nil)
   (t
    (let ((orig (point)))
      (ignore-errors
        (save-excursion
          (funcall
           (or (get thing 'end-op)
               (lambda () (forward-thing thing 1))))
          (funcall
           (or (get thing 'beginning-op)
               (lambda () (forward-thing thing -1))))
          (let ((beg (point)))
            (if (<= beg orig)
                (let ((real-end
                       (progn
                         (funcall
                          (or (get thing 'end-op)
                              (lambda () (forward-thing thing 1))))
                         (point))))
                  (when (and (<= orig real-end) (< beg real-end))
                    (cons beg real-end)))
              (goto-char orig)
              (funcall
               (or (get thing 'beginning-op)
                   (lambda () (forward-thing thing -1))))
              (funcall
               (or (get thing 'end-op)
                   (lambda () (forward-thing thing 1))))
              (let ((end (point))
                    (real-beg
                     (progn
                       (funcall
                        (or (get thing 'beginning-op)
                            (lambda () (forward-thing thing -1))))
                       (point))))
                (if (and (<= real-beg orig) (<= orig end) (< real-beg end))
                    (cons real-beg end)))))))))))
(defun thing-at-point (thing &optional no-properties)
  (let ((text
         (cond
          ((let ((alist thing-at-point-provider-alist)
                 elt result)
             (while (and alist (null result))
               (setq elt (car alist)
                     alist (cdr alist))
               (and (eq (car elt) thing)
                    (setq result (funcall (cdr elt)))))
             result))
          ((get thing 'thing-at-point)
           (funcall (get thing 'thing-at-point)))
          (t
           (let ((bounds (bounds-of-thing-at-point thing)))
             (when bounds
               (buffer-substring (car bounds) (cdr bounds))))))))
    (when (and text no-properties (sequencep text))
      (set-text-properties 0 (length text) nil text))
    text))
(defun beginning-of-thing (thing)
  (let ((bounds (bounds-of-thing-at-point thing)))
    (or bounds (error "No %s here" thing))
    (goto-char (car bounds))))
(defun end-of-thing (thing)
  (let ((bounds (bounds-of-thing-at-point thing)))
    (or bounds (error "No %s here" thing))
    (goto-char (cdr bounds))))
(put 'line 'beginning-op
     (lambda () (if (bolp) (forward-line -1) (beginning-of-line))))
(defun thing-at-point--end-of-sexp ()
  (let ((char-syntax (syntax-after (point))))
    (if (or (eq char-syntax ?\))
            (and (eq char-syntax ?\") (nth 3 (syntax-ppss))))
        (forward-char 1)
      (condition-case _
          (forward-sexp 1)
        (scan-error nil)))))
(put 'sexp 'end-op 'thing-at-point--end-of-sexp)
(defun thing-at-point--beginning-of-sexp ()
  (let ((char-syntax (char-syntax (char-before))))
    (if (or (eq char-syntax ?\()
            (and (eq char-syntax ?\") (nth 3 (syntax-ppss))))
        (forward-char -1)
      (forward-sexp -1))))
(put 'sexp 'beginning-op 'thing-at-point--beginning-of-sexp)
(put 'symbol 'beginning-op 'thing-at-point--beginning-of-symbol)
(defun thing-at-point--beginning-of-symbol ()
  (and (re-search-backward "\\(\\sw\\|\\s_\\)+")
       (skip-syntax-backward "w_")))
(put 'list 'bounds-of-thing-at-point 'thing-at-point-bounds-of-list-at-point)
(defun thing-at-point-bounds-of-list-at-point ()
  (save-excursion
    (if (ignore-errors (up-list -1))
        (ignore-errors (cons (point) (progn (forward-sexp) (point))))
      (let ((bound (bounds-of-thing-at-point 'sexp)))
        (and bound
             (<= (car bound) (point)) (< (point) (cdr bound))
             bound)))))
(put 'buffer 'end-op (lambda () (goto-char (point-max))))
(put 'buffer 'beginning-op (lambda () (goto-char (point-min))))
(defun thing-at-point-looking-at (regexp &optional distance)
  (let* ((old (point))
         (beg (if distance (max (point-min) (- old distance)) (point-min)))
         (end (if distance (min (point-max) (+ old distance))))
         prev match)
    (save-excursion
      (goto-char beg)
      (while (and (setq prev (point)
                        match (re-search-forward regexp end t))
                  (< (match-end 0) old))
        (goto-char (match-beginning 0))
        (unless (< prev (point)) (forward-char))))
    (and match (<= (match-beginning 0) old (match-end 0)))))
(defun word-at-point (&optional no-properties)
  (thing-at-point 'word no-properties))
(defun thing-at-point--read-from-whole-string (str)
  (let* ((read-data (read-from-string str))
         (more-left
          (condition-case nil
              (progn (ignore (read-from-string (substring str (cdr read-data))))
                     t)
            (end-of-file nil))))
    (if more-left
        (error "Can't read whole string")
      (car read-data))))
(defun form-at-point (&optional thing pred)
  (let* ((obj (thing-at-point (or thing 'sexp)))
         (sexp (if (stringp obj)
                   (ignore-errors
                     (thing-at-point--read-from-whole-string obj))
                 obj)))
    (if (or (not pred) (funcall pred sexp)) sexp)))
(defun sexp-at-point ()
  (form-at-point 'sexp))
(defun symbol-at-point ()
  (let ((thing (thing-at-point 'symbol)))
    (if thing (intern thing))))
(defvar thing-at-point-decimal-regexp
  "-?[0-9]+\\.?[0-9]*")
(defvar thing-at-point-hexadecimal-regexp
  "\\(0x\\|#x\\)\\([a-fA-F0-9]+\\)")
(defun number-at-point ()
  (cond
   ((thing-at-point-looking-at thing-at-point-hexadecimal-regexp 500)
    (string-to-number
     (buffer-substring (match-beginning 2) (match-end 2))
     16))
   ((thing-at-point-looking-at thing-at-point-decimal-regexp 500)
    (string-to-number
     (buffer-substring (match-beginning 0) (match-end 0))))))
(put 'number 'bounds-of-thing-at-point
     (lambda ()
       (and (or (thing-at-point-looking-at thing-at-point-hexadecimal-regexp 500)
                (thing-at-point-looking-at thing-at-point-decimal-regexp 500))
            (cons (match-beginning 0) (match-end 0)))))
(put 'number 'forward-op 'forward-word)
(put 'number 'thing-at-point 'number-at-point)
(defun list-at-point (&optional ignore-comment-or-string)
  (let ((ppss (and ignore-comment-or-string (syntax-ppss))))
    (save-excursion
      (goto-char (or (nth 8 ppss) (point)))
      (form-at-point 'list 'listp))))
;; buffer-hash: a SHA-1 of the buffer contents (BUFFER arg ignored — current only).
(defun buffer-hash (&optional _buffer) (sha1 (buffer-string)))
;; Character at/before point (0 at the buffer's end/start), like Emacs.
(defun following-char () (or (char-after) 0))
(defun preceding-char () (or (char-before) 0))
;; Insert N newlines at point (default 1); like insert, no kill ring.
(defun newline (&optional n _interactive) (insert (make-string (or n 1) ?\n)) nil)
;; Insert N newlines after point, leaving point before them.
(defun open-line (n) (save-excursion (insert (make-string n ?\n))) nil)
;; insert-before-markers: like insert, but markers exactly at point advance past
;; the new text (handled by the primitive --insert-before-markers--).
(defun insert-before-markers (&rest args)
  (dolist (a args) (--insert-before-markers-- a))
  nil)
(defun count-words (start end)
  (length (split-string (buffer-substring start end) "[^[:alnum:]]+" t)))
;; subr.el `replace-string-in-region' / `replace-regexp-in-region': replace in
;; START..END (default point..point-max) with case-fold-search nil, returning the
;; count or nil. The region is a narrowing, so START > END is swapped (Emacs answers
;; nil, not "wrong side of point") and an out-of-range START signals
;; `narrow-to-region''s `(args-out-of-range START END)'.
(defun replace-string-in-region (string replacement &optional start end)
  (if start
      (when (< start (point-min)) (error "Start before start of buffer"))
    (setq start (point)))
  (if end
      (when (> end (point-max)) (error "End after end of buffer"))
    (setq end (point-max)))
  (save-excursion
    (goto-char start)
    (save-restriction
      (narrow-to-region start end)
      (let ((matches 0) (case-fold-search nil))
        (while (search-forward string nil t)
          (delete-region (match-beginning 0) (match-end 0))
          (insert replacement)
          (setq matches (1+ matches)))
        (and (not (zerop matches)) matches)))))
(defun replace-regexp-in-region (regexp replacement &optional start end)
  (if start
      (when (< start (point-min)) (error "Start before start of buffer"))
    (setq start (point)))
  (if end
      (when (> end (point-max)) (error "End after end of buffer"))
    (setq end (point-max)))
  (save-excursion
    (goto-char start)
    (save-restriction
      (narrow-to-region start end)
      (let ((matches 0) (case-fold-search nil))
        (while (re-search-forward regexp nil t)
          (replace-match replacement t)
          (setq matches (1+ matches)))
        (and (not (zerop matches)) matches)))))
;; replace.el `how-many'. RSTART/REND are ordered (a reversed pair counts the
;; same region), and `search-upper-case' turns case folding off for a REGEXP
;; with an upper-case letter. `isearch-no-upper-case-p' and `search-upper-case'
;; are defined with `keep-lines' further down; they are only called at run time.
(defun how-many (regexp &optional rstart rend interactive)
  "Return the number of matches for REGEXP following point (or in RSTART..REND)."
  (save-excursion
    (if rstart
        (if rend
            (progn
              (goto-char (min rstart rend))
              (setq rend (max rstart rend)))
          (goto-char rstart)
          (setq rend (point-max)))
      (if (and interactive (use-region-p))
          (setq rstart (region-beginning)
                rend (region-end))
        (setq rstart (point)
              rend (point-max)))
      (goto-char rstart))
    (let ((count 0)
          (case-fold-search
           (if (and case-fold-search search-upper-case)
               (isearch-no-upper-case-p regexp t)
             case-fold-search)))
      (while (and (< (point) rend)
                  (re-search-forward regexp rend t))
        ;; Ensure forward progress on zero-length matches like "^$".
        (when (and (= (match-beginning 0) (match-end 0))
                   (not (eobp)))
          (forward-char 1))
        (setq count (1+ count)))
      (when interactive (message (ngettext "%d occurrence"
                                           "%d occurrences"
                                           count)
                                 count))
      count)))
;;; ---- misc small subr.el helpers ----
(defun ngettext (singular plural n) (if (= n 1) singular plural))

;;; ---- version comparison (faithful port of lisp/subr.el, Emacs 30.2) ----
;; version-to-list parses a version string into a list of integers; the
;; version-list-* comparators do the significant-trailing-zero comparison; and
;; version< / version<= / version= wrap them over two version strings. The
;; version-regexp-alist data is copied value-for-value from subr.el so that
;; non-numeric qualifiers (snapshot/alpha/beta/pre/rc) sort exactly as Emacs.
(defconst version-separator "."
  "Specify the string used to separate the version elements.")

(defconst version-regexp-alist
  '(("^[-._+ ]?snapshot$"                                 . -4)
    ("^[-._+]$"                                           . -4)
    ("^[-._+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4)
    ("^[-._+ ]?unknown$"                                  . -4)
    ("^[-._+ ]?alpha$"                                    . -3)
    ("^[-._+ ]?beta$"                                     . -2)
    ("^[-._+ ]?\\(pre\\|rc\\)$"                           . -1))
  "Specify association between non-numeric version and its priority.")

(defun version-to-list (ver)
  "Convert version string VER into a list of integers."
  (declare (side-effect-free t))
  (unless (stringp ver)
    (error "Version must be a string"))
  ;; Change .x.y to 0.x.y
  (if (and (>= (length ver) (length version-separator))
	   (string-equal (substring ver 0 (length version-separator))
			 version-separator))
      (setq ver (concat "0" ver)))
  (unless (string-match-p "^[0-9]" ver)
    (error "Invalid version syntax: `%s' (must start with a number)" ver))
  (save-match-data
    (let ((i 0)
	  (case-fold-search t)		; ignore case in matching
	  lst s al)
      ;; Parse the version-string up to a separator until there are none left
      (while (and (setq s (string-match "[0-9]+" ver i))
		  (= s i))
        ;; Add the numeric part to the beginning of the version list;
        ;; lst gets reversed at the end
	(setq lst (cons (string-to-number (substring ver i (match-end 0)))
			lst)
	      i   (match-end 0))
	;; handle non-numeric part
	(when (and (setq s (string-match "[^0-9]+" ver i))
		   (= s i))
	  (setq s (substring ver i (match-end 0))
		i (match-end 0))
	  ;; handle alpha, beta, pre, etc. separator
	  (unless (string= s version-separator)
	    (setq al version-regexp-alist)
	    (while (and al (not (string-match (caar al) s)))
	      (setq al (cdr al)))
	    (cond (al
		   (push (cdar al) lst))
        ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc., but only if
        ;; the letter is the end of the version-string, to avoid
        ;; 22.8X3 being valid
        ((and (string-match "^[-._+ ]?\\([a-zA-Z]\\)$" s)
           (= i (length ver)))
		   (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
			 lst))
		  (t (error "Invalid version syntax: `%s'" ver))))))
    (nreverse lst))))

(defun version-list-< (l1 l2)
  "Return t if L1, a list specification of a version, is lower than L2."
  (declare (pure t) (side-effect-free t))
  (while (and l1 l2 (= (car l1) (car l2)))
    (setq l1 (cdr l1)
	  l2 (cdr l2)))
  (cond
   ((and l1 l2) (< (car l1) (car l2)))
   ((and (null l1) (null l2)) nil)
   (l1 (< (version-list-not-zero l1) 0))
   (t  (< 0 (version-list-not-zero l2)))))

(defun version-list-= (l1 l2)
  "Return t if L1, a list specification of a version, is equal to L2."
  (declare (pure t) (side-effect-free t))
  (while (and l1 l2 (= (car l1) (car l2)))
    (setq l1 (cdr l1)
	  l2 (cdr l2)))
  (cond
   ((and l1 l2) nil)
   ((and (null l1) (null l2)))
   (l1 (zerop (version-list-not-zero l1)))
   (t  (zerop (version-list-not-zero l2)))))

(defun version-list-<= (l1 l2)
  "Return t if L1, a list specification of a version, is lower or equal to L2."
  (declare (pure t) (side-effect-free t))
  (while (and l1 l2 (= (car l1) (car l2)))
    (setq l1 (cdr l1)
	  l2 (cdr l2)))
  (cond
   ((and l1 l2) (< (car l1) (car l2)))
   ((and (null l1) (null l2)))
   (l1 (<= (version-list-not-zero l1) 0))
   (t  (<= 0 (version-list-not-zero l2)))))

(defun version-list-not-zero (lst)
  "Return the first non-zero element of LST, which is a list of integers.
If all LST elements are zeros or LST is nil, return zero."
  (declare (pure t) (side-effect-free t))
  (while (and lst (zerop (car lst)))
    (setq lst (cdr lst)))
  (if lst
      (car lst)
    0))

(defun version< (v1 v2)
  "Return t if version V1 is lower (older) than V2."
  (declare (side-effect-free t))
  (version-list-< (version-to-list v1) (version-to-list v2)))

(defun version<= (v1 v2)
  "Return t if version V1 is lower (older) than or equal to V2."
  (declare (side-effect-free t))
  (version-list-<= (version-to-list v1) (version-to-list v2)))

(defun version= (v1 v2)
  "Return t if version V1 is equal to V2."
  (declare (side-effect-free t))
  (version-list-= (version-to-list v1) (version-to-list v2)))
;; ---- Lisp timestamps: a port of timefns.c (Emacs 31.1) ----
;; Every time value decodes to an exact (TICKS . HZ) pair (bignum arithmetic,
;; no floats), so sums, differences and comparisons are exact and come back in
;; the form timefns.c picks: an integer when HZ is 1, (TICKS . HZ) when either
;; input was in that form or HZ does not divide a trillion, otherwise the
;; (HI LO US PS) list `current-time-list' asks for.
(defvar current-time-list t)
(defun time--gcd (a b)
  (setq a (abs a) b (abs b))
  (while (/= b 0) (setq b (prog1 (% a b) (setq a b))))
  a)
;; `time--decode' (src/timefns.rs) is decode_lisp_time: TIME as exact (TICKS . HZ).
;; ticks_hz_list4: floor to picoseconds, then split.
(defun time--list4 (ticks hz)
  (let* ((x (floor (* ticks 1000000000000) hz))
         (s (floor x 1000000000000))
         (fullps (mod x 1000000000000)))
    (list (ash s -16) (logand s 65535) (/ fullps 1000000) (% fullps 1000000))))
;; ticks_hz_hz_ticks: floor (TICKS * HZ / T.HZ), validating HZ.
(defun time--hz-ticks (th hz)
  (unless (and (integerp hz) (> hz 0))
    (signal 'error (list "Invalid time frequency" hz)))
  (floor (* (car th) hz) (cdr th)))
(defun time--trillion-factor (hz)
  (and (fixnump hz) (= 0 (% 1000000000000 hz))))
;; time_arith.
(defun time--arith (a b subtract)
  (let ((ta (time--decode a)) (tb (time--decode b)) ticks hz)
    (if (eql (cdr ta) (cdr tb))
        (setq hz (cdr ta)
              ticks (if subtract (- (car ta) (car tb)) (+ (car ta) (car tb))))
      (let* ((da (cdr ta)) (db (cdr tb))
             (hzmin (min da db))
             (g (time--gcd da db))
             (fa (/ da g)) (fb (/ db g))
             (ihz (* fa db))
             (iticks (if subtract
                         (- (* fb (car ta)) (* fa (car tb)))
                       (+ (* fb (car ta)) (* fa (car tb)))))
             (ig (time--gcd iticks ihz)))
        (when (> ig 1)
          (setq iticks (/ iticks ig) ihz (/ ihz ig))
          (when (< ihz hzmin)
            (let ((rescale (ceiling hzmin ihz)))
              (setq iticks (* iticks rescale) ihz (* ihz rescale)))))
        (setq ticks iticks hz ihz)))
    (cond ((eql hz 1) ticks)
          ((or (not current-time-list)
               (and (consp a) (not (consp (cdr a))))
               (and (consp b) (not (consp (cdr b))))
               (not (time--trillion-factor hz)))
           (cons ticks hz))
          (t (time--list4 ticks hz)))))
(defun time-add (a b) (time--arith a b nil))
(defun time-subtract (a b)
  (if (eq a b)
      (if current-time-list (list 0 0 0 0) (cons 0 1000000000))
    (time--arith a b t)))
;; time_cmp, including its fast paths that compare without validating.
(defun time--cmp (a b)
  (if (eq a b)
      0
    (let ((x a) (y b))
      (when (and (consp a) (consp b) (eql (cdr a) (cdr b)))
        (setq x (car a) y (car b)))
      (if (and (fixnump x) (fixnump y))
          (- x y)
        (let ((ta (time--decode a)) (tb (time--decode b)))
          (- (* (car ta) (cdr tb)) (* (car tb) (cdr ta))))))))
(defun time-less-p (a b) (< (time--cmp a b) 0))
(defun time-equal-p (a b)
  (and (eq (null a) (null b)) (= (time--cmp a b) 0)))
(defun time-convert (time &optional form)
  (let ((th (time--decode time)))
    (setq form (cond (form form) (current-time-list 'list) (t t)))
    (cond ((eq form 'list) (time--list4 (car th) (cdr th)))
          ((eq form 'integer)
           (if (integerp time) time (floor (car th) (cdr th))))
          (t
           (when (eq form t) (setq form (cdr th)))
           (if (and (consp time) (eq form (cdr time)))
               time
             (cons (time--hz-ticks th form) form))))))
;; timefns.c `Fcurrent_time_zone': (OFFSET NAME) for the whole seconds of TIME
;; (`lisp_seconds_argument') in ZONE.  NAME is `%Z'; an empty one becomes the
;; numeric `+HH[MM[SS]]' spelling of OFFSET.
(defun current-time-zone (&optional specified-time zone)
  (let* ((secs (time-convert specified-time 'integer))
         (name (format-time-string "%Z" secs zone))
         (offset (nth 8 (decode-time secs zone))))
    (when (string= name "")
      (let* ((amin-sec (abs (% offset 3600)))
             (min (/ amin-sec 60))
             (sec (% amin-sec 60)))
        (setq name (concat (if (< offset 0) "-" "+")
                           (format "%02d" (abs (/ offset 3600)))
                           (if (/= amin-sec 0) (format "%02d" min) "")
                           (if (and (/= amin-sec 0) (/= sec 0))
                               (format "%02d" sec)
                             "")))))
    (list offset name)))
;; decoded-time accessors: (sec min hour day month year weekday dst zone).
(defun decoded-time-second (dt) (nth 0 dt))
(defun decoded-time-minute (dt) (nth 1 dt))
(defun decoded-time-hour (dt) (nth 2 dt))
(defun decoded-time-day (dt) (nth 3 dt))
(defun decoded-time-month (dt) (nth 4 dt))
(defun decoded-time-year (dt) (nth 5 dt))
(defun decoded-time-weekday (dt) (nth 6 dt))
(defun decoded-time-dst (dt) (nth 7 dt))
(defun decoded-time-zone (dt) (nth 8 dt))
(defun char-displayable-p (_char &optional _display) t)
;; Feature/module system.  `features' starts as the list `emacs -Q --batch'
;; reports before it reads any argument, in its order:
;;
;;   emacs -Q --batch --eval '(prin1 features)'
;;
;; Emacs preloads (dumps) every one of these, so `(require 'FEATURE)' is a
;; no-op for each and must not go looking for a file.  The tail lists the
;; libraries elisprs implements natively; a stock Emacs provides those only once
;; they are required.  (`rx', which lisp-mode.el expands while the prelude
;; loads, is unloaded again afterwards: see `unload_rx_after_prelude'.)
(defvar features
  '(rmc iso-transl tooltip cconv eldoc paren electric uniquify ediff-hook
    vc-hooks lisp-float-type elisp-mode tabulated-list replace newcomment
    text-mode lisp-mode prog-mode register page tab-bar menu-bar rfn-eshadow
    isearch easymenu timer select mouse jit-lock font-lock syntax font-core
    term/tty-colors frame minibuffer nadvice seq simple cl-generic indonesian
    philippine cham georgian utf-8-lang misc-lang vietnamese tibetan thai
    tai-viet lao korean japanese eucjp-ms cp51932 hebrew greek romanian slovak
    czech european ethiopic indian cyrillic chinese composite emoji-zwj
    charscript charprop case-table epa-hook jka-cmpr-hook help abbrev obarray
    oclosure cl-preloaded button loaddefs theme-loaddefs faces cus-face macroexp
    files window text-properties overlay sha1 md5 base64 format env code-pages
    mule custom widget keymap hashtable-print-readable backquote threads kqueue
    multi-tty make-network-process tty-child-frames emacs
    cl-lib cl-macs cl-seq cl-extra subr-x map pcase json gv ert time-date))
(defun provide (feature &optional _subfeatures)
  (unless (memq feature features) (setq features (cons feature features)))
  feature)
(defun featurep (feature &optional _subfeature) (and (memq feature features) t))
;; Faithful port of C `Frequire' (fns.c): if FEATURE is already provided, return
;; it; otherwise `load' its file (FILENAME, else the feature's name) with a
;; recursion guard, then verify the load actually provided FEATURE. Loading uses
;; MUST-SUFFIX when FILENAME is nil (require a `.el'/`.elc', never a bare name),
;; matching `Fload (…, Qnil, Qt, Qnil, NILP (filename) ? Qt : Qnil)'.
(defvar require--nesting-list nil
  "Features whose `require' is currently in progress (recursion guard).")
(defun require (feature &optional filename noerror)
  (if (featurep feature)
      feature
    (let ((lisp-file (if filename filename (symbol-name feature))))
      (when (member lisp-file require--nesting-list)
        (error "Recursive `require' for feature `%s'" feature))
      (let ((require--nesting-list (cons lisp-file require--nesting-list)))
        (if (load lisp-file noerror t nil (if filename nil t))
            (if (featurep feature)
                feature
              (unless noerror
                (error "Loading file %s failed to provide feature `%s'"
                       lisp-file feature)))
          nil)))))
(defmacro bound-and-true-p (var) (list 'and (list 'boundp (list 'quote var)) var))
;; `make-local-variable', `make-variable-buffer-local', `local-variable-p',
;; `local-variable-if-set-p', `kill-local-variable' and `buffer-local-value' are
;; C primitives (builtins.rs) backed by the current buffer's local-binding table.
;; Faithful to the C subr `Fset_default_toplevel_value' (data.c): it runs
;; `set_default_internal' and returns nil, NOT the value.
(defun set-default-toplevel-value (sym val) (set-default sym val) nil)
(defun defalias (symbol definition &optional _docstring) (fset symbol definition) symbol)
(defalias 'string-split 'split-string)
(defalias 'search-forward-regexp (symbol-function 're-search-forward))
(defalias 'search-backward-regexp (symbol-function 're-search-backward))
;; cl-lib.el: the three- and four-letter accessors under their cl- names are
;; plain aliases, so `(symbol-function (quote cl-caddr))' is `caddr' and setf
;; reaches them by following the alias (gv.el:112).
(let ((names (quote (caaar caadr cadar caddr cdaar cdadr cddar cdddr
                     caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
                     cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr))))
  (while names
    (defalias (intern (concat "cl-" (symbol-name (car names)))) (car names))
    (setq names (cdr names))))
;; help.el: obsolete alias for `help--make-usage' (help usage helpers ported above).
(define-obsolete-function-alias 'help-make-usage #'help--make-usage "25.1")
;; with-memoization: cache BODY's value in PLACE; reuse it on later calls.
(defmacro with-memoization (place &rest body) (declare (indent 1) (debug (gv-place body))) `(or ,place (setf ,place (progn ,@body))))
;; regexp-opt: a regexp matching any of STRINGS (sorted, regexp-quoted alternation).
;; NOTE: this does NOT replicate Emacs's trie/shared-prefix optimization, so the
;; output string differs for prefix-overlapping inputs — but it matches the same
;; set of strings. Special cases (empty, single, PAREN variants) match Emacs.
(defun match-string-no-properties (n &optional string)
  ;; elisprs strings carry no text properties, so this is just match-string.
  (match-string n string))
(defun regexp-opt-depth (regexp)
  ;; Count capturing groups: bare `\\(' (not the `\\(?…' shy/numbered forms).
  (let ((count 0) (i 0) (n (length regexp)))
    (while (< i n)
      (if (and (eq (aref regexp i) ?\\) (< (1+ i) n) (eq (aref regexp (1+ i)) ?\())
          (progn
            (unless (and (< (+ i 2) n) (eq (aref regexp (+ i 2)) ??))
              (setq count (1+ count)))
            (setq i (+ i 2)))
        (setq i (1+ i))))
    count))
;; regexp-opt.el, ported. The old implementation joined the strings with `\\|',
;; which is a correct regexp but not the one Emacs builds: `regexp-opt' factors
;; common prefixes and suffixes and folds one-character alternatives into a
;; character set, so `(regexp-opt '("cat" "cot" "cut"))' is "\\(?:c\\(?:[aou]t\\)\\)"
;; and `(regexp-opt '("a" "b" "c"))' is "[abc]". That output is observable
;; wherever a caller inspects or composes the result -- `rx''s all-strings `or'
;; branch is one -- so it is the shape, not just the language, that has to match.
(defun regexp-opt--common-prefix (strings)
  "The longest common prefix of STRINGS.
`regexp-opt-group' asks `try-completion' for this, having bound
`completion-ignore-case' and `completion-regexp-list' to nil so that it means
exactly the common prefix and nothing else."
  (let ((pre (car strings)) (rest (cdr strings)))
    (while (and rest (> (length pre) 0))
      (let ((s (car rest)) (i 0))
        (while (and (< i (length pre)) (< i (length s))
                    (eq (aref pre i) (aref s i)))
          (setq i (1+ i)))
        (setq pre (substring pre 0 i)))
      (setq rest (cdr rest)))
    (or pre "")))
(defun regexp-opt-charset (chars)
  "Return a regexp matching a character in CHARS (a list of characters).
The empty list yields a regexp that never matches."
  ;; The C walks a char-table; walking the sorted, de-duplicated list is the
  ;; same traversal. A run becomes a RANGE only when it is longer than three
  ;; characters (`(> end (+ start 2))'), which is why (?a ?b ?c) is "[abc]" and
  ;; (?a ?b ?c ?d) is "[a-d]".
  (let ((bracket "") (dash "") (caret "") (plain nil) (charset "")
        (start -1) (end -2))
    (dolist (char chars)
      (cond ((eq char ?\]) (setq bracket "]"))
            ((eq char ?^) (setq caret "^"))
            ((eq char ?-) (setq dash "-"))
            (t (setq plain (cons char plain)))))
    (setq plain (sort (delete-dups (nreverse plain)) #'<))
    (dolist (c plain)
      (if (= (1- c) end)
          (setq end c)
        (if (> end (+ start 2))
            (setq charset (concat charset (string start) "-" (string end)))
          (while (>= end start)
            (setq charset (concat charset (string start)))
            (setq start (1+ start))))
        (setq start c end c)))
    (when (>= end start)
      (if (> end (+ start 2))
          (setq charset (concat charset (string start) "-" (string end)))
        (while (>= end start)
          (setq charset (concat charset (string start)))
          (setq start (1+ start)))))
    ;; `]' must come first, `^' must not, and `-' must be first or last.
    (let ((all (concat bracket charset caret dash)))
      (cond ((= (length all) 0) "\\`a\\`")
            ((= (length all) 1) (regexp-quote all))
            ((string= all "^-") "[-^]")
            (t (concat "[" all "]"))))))
(defun regexp-opt-group (strings &optional paren lax)
  "Return a regexp matching a string in the SORTED list STRINGS.
PAREN non-nil wraps the result; LAX non-nil omits the wrapping where it is not
needed. Merges keywords to avoid backtracking, as regexp-opt.el does."
  (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
         (close-group (if paren "\\)" ""))
         (open-charset (if lax "" open-group))
         (close-charset (if lax "" close-group)))
    (cond
     ((= (length strings) 0) "")
     ((= (length strings) 1)
      (if (= (length (car strings)) 1)
          (concat open-charset (regexp-quote (car strings)) close-charset)
        (concat open-group (regexp-quote (car strings)) close-group)))
     ;; An empty string: drop it and make the rest optional.
     ((= (length (car strings)) 0)
      (concat open-charset (regexp-opt-group (cdr strings) t t) "?" close-charset))
     ;; Several one-character strings: a character set beats alternation.
     ((and (= (length (car strings)) 1)
           (let ((found nil))
             (dolist (s (cdr strings)) (when (= (length s) 1) (setq found t)))
             found))
      (let ((letters nil) (rest nil))
        (dolist (s strings)
          (if (= (length s) 1)
              (setq letters (cons (aref s 0) letters))
            (setq rest (cons s rest))))
        (if rest
            ;; Longest first, so the alternation matches the longer string.
            (concat open-group (regexp-opt-group (nreverse rest))
                    "\\|" (regexp-opt-charset letters) close-group)
          (concat open-charset (regexp-opt-charset letters) close-charset))))
     (t
      (let ((prefix (regexp-opt--common-prefix strings)))
        (if (> (length prefix) 0)
            (let* ((n (length prefix))
                   (suffixes (mapcar (lambda (s) (substring s n)) strings)))
              (concat open-group (regexp-quote prefix)
                      (regexp-opt-group suffixes t t) close-group))
          (let* ((sgnirts (mapcar (lambda (s) (reverse s)) strings))
                 (xiffus (regexp-opt--common-prefix sgnirts)))
            (if (> (length xiffus) 0)
                (let* ((n (- (length xiffus)))
                       ;; Sorting matters for cases such as ("ad" "d").
                       (prefixes (sort (mapcar (lambda (s) (substring s 0 n)) strings)
                                       #'string<)))
                  (concat open-group (regexp-opt-group prefixes t t)
                          (regexp-quote (reverse xiffus)) close-group))
              ;; No shared affix: split on the first character and recurse.
              (let* ((char (substring (car strings) 0 1))
                     (half1 nil) (half2 nil))
                (dolist (s strings)
                  (if (and (null half2) (string-prefix-p char s))
                      (setq half1 (cons s half1))
                    (setq half2 (cons s half2))))
                (concat open-group (regexp-opt-group (nreverse half1))
                        "\\|" (regexp-opt-group (nreverse half2))
                        close-group))))))))))
(defun regexp-opt (strings &optional paren)
  "Return a regexp matching any string in STRINGS, each taken literally.
PAREN controls the surrounding group: a string is used as the opening bracket,
`words'/`symbols' add the word/symbol boundaries, any other non-nil value uses
`\\(', and nil uses a shy group only where one is needed."
  (let* ((open (cond ((stringp paren) paren) (paren "\\(")))
         (re (if strings
                 (regexp-opt-group (delete-dups (sort (copy-sequence strings) #'string<))
                                   (or open t) (not open))
               (concat (or open "\\(?:") "\\`a\\`" "\\)"))))
    (cond ((eq paren 'words) (concat "\\<" re "\\>"))
          ((eq paren 'symbols) (concat "\\_<" re "\\_>"))
          (t re))))

;; `looking-back' (subr.el): `looking-at' for the text BEFORE point.  The trick
;; is the `\\=' anchor -- searching backwards for "\\(?:REGEXP\\)\\=" finds a match
;; that ENDS at point.  GREEDY then walks the start backwards one character at a
;; time for as long as the match still reaches the end, which is allowed to pass
;; LIMIT.
(defun looking-back (regexp &optional limit greedy)
  "Return non-nil if the text before point matches REGEXP."
  (let ((start (point))
        (pos (save-excursion
               (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
                    (point)))))
    (if (and greedy pos)
        (save-restriction
          (narrow-to-region (point-min) start)
          (while (and (> pos (point-min))
                      (save-excursion
                        (goto-char pos)
                        (backward-char 1)
                        (looking-at (concat "\\(?:" regexp "\\)\\'"))))
            (setq pos (1- pos)))
          (save-excursion
            (goto-char pos)
            (looking-at (concat "\\(?:" regexp "\\)\\'"))))
      (not (null pos)))))

(defmacro while-let (binding &rest body)
  (declare (indent 1) (debug if-let))
  (let ((var (car (car binding))) (val (car (cdr (car binding)))))
    `(let ((,var ,val)) (while ,var ,@body (setq ,var ,val)))))

;; cl-macs.el `cl-deftype': the expander is `(cl-function (lambda (&cl-defs
;; ('*) ,@ARGLIST) ...))', so an omitted &optional or &key argument defaults to
;; `*'; calling it with no arguments at definition time computes the atomic
;; type's specifier, and a `wrong-number-of-arguments' there means NAME has no
;; atomic form (no predicate). A `(declare (parents ...))' is consumed.
(defun cl--deftype-defaulted-arglist (arglist)
  (let ((res nil) (kind nil))
    (while (consp arglist)
      (let ((a (car arglist)))
        (cond ((memq a '(&optional &key &rest &body &aux)) (setq kind a))
              ((and (memq kind '(&optional &key)) (symbolp a) (not (eq a '&allow-other-keys)))
               (setq a (list a ''*))))
        (setq res (cons a res)))
      (setq arglist (cdr arglist)))
    (nconc (nreverse res) arglist)))
(defun cl--deftype-arity (arglist)
  ;; (MIN . MAX) of a cl lambda list, MAX nil when &rest/&body/&key takes any.
  (let ((min 0) (max 0) (kind nil))
    (while (consp arglist)
      (let ((a (car arglist)))
        (cond ((memq a '(&optional &key &rest &body &aux &allow-other-keys))
               (setq kind a)
               (when (memq a '(&rest &body &key)) (setq max nil)))
              ((null kind) (setq min (1+ min)) (and max (setq max (1+ max))))
              ((eq kind '&optional) (and max (setq max (1+ max))))))
      (setq arglist (cdr arglist)))
    (when arglist (setq max nil))
    (cons min max)))
(defmacro cl-deftype (name arglist &rest body)
  (declare (debug cl-defmacro) (doc-string 3) (indent 2))
  (let ((decls nil) (forms body) (parents nil))
    (while (and forms
                (or (and (stringp (car forms)) (cdr forms))
                    (memq (car-safe (car forms)) '(:documentation declare interactive cl-declare))))
      (setq decls (cons (car forms) decls) forms (cdr forms)))
    (setq decls (nreverse decls))
    (let ((declares (assq 'declare decls)))
      (when declares
        (let ((parent-decl (assq 'parents (cdr declares))))
          (when parent-decl
            (setq parents (cdr parent-decl))
            (setcdr declares (delq parent-decl (copy-sequence (cdr declares))))
            (when (equal declares '(declare))
              (setq decls (delq declares decls)))))))
    (let* ((arity (cl--deftype-arity arglist))
           (args (make-symbol "args"))
           (expander
            `(lambda (&rest ,args)
               ,@(and (stringp (car decls)) (list (car decls)))
               (let ((n (length ,args)))
                 (when (or (< n ,(car arity)) ,(and (cdr arity) `(> n ,(cdr arity))))
                   (signal 'wrong-number-of-arguments (list ',arity n))))
               (cl-destructuring-bind ,(cl--deftype-defaulted-arglist arglist) ,args
                 ,@forms)))
           (specifier
            (condition-case nil
                (funcall (eval expander t))
              (wrong-number-of-arguments
               (and parents arglist
                    (error "Type %S with parents may be not atomic: %S"
                           name arglist)))))
           (predicate
            (cond ((and (eq (car-safe specifier) 'satisfies)
                        (consp (cdr specifier)) (null (cdr (cdr specifier))))
                   `#',(car (cdr specifier)))
                  ((null specifier) nil)
                  (t `(lambda (x) (ignore x) (cl-typep x ',specifier))))))
      `(eval-and-compile
         (cl--define-derived-type ',name ,expander ,predicate ',parents)))))
;; cl-preloaded.el `cl--define-derived-type', without the derived-type class
;; object (method dispatch on derived types is not modelled).
(defun cl--define-derived-type (name expander predicate &optional _parents)
  (define-symbol-prop name 'cl-deftype-handler expander)
  (when predicate
    (define-symbol-prop name 'cl-deftype-satisfies predicate)))
;; cl-macs.el `cl-typep' (a `define-inline'), as its function body runs.
(defun cl-typep (val type)
  "Return t if VAL is of type TYPE, nil otherwise."
  (let ((satisfies (cond ((and type (symbolp type)) (get type 'cl-deftype-satisfies))
                         ((and (consp type) (null (cdr type)))
                          (get (car type) 'cl-deftype-satisfies)))))
    (cond
     (satisfies (funcall satisfies val))
     ((and (consp type) (get (car type) 'cl-deftype-handler))
      (cl-typep val (apply (get (car type) 'cl-deftype-handler) (cdr type))))
     ((and (consp type) (memq (car type) '(integer float number)))
      ;; The compiled `(or `(,min ,max) pcase--dontcare)' keeps whatever the
      ;; failed list match bound: MIN is the first argument, MAX the second.
      (let* ((bounds (cdr type))
             (min (car-safe bounds))
             (max (car-safe (cdr-safe bounds))))
        (and (cl-typep val (car type))
             (if (memq min '(* nil)) t
               (if (consp min) (> val (car min)) (>= val min)))
             (if (memq max '(* nil)) t
               (if (consp max) (< val (car max)) (<= val max))))))
     ((and (eq (car-safe type) 'not) (consp (cdr type)) (null (cdr (cdr type))))
      (not (cl-typep val (car (cdr type)))))
     ((memq (car-safe type) '(and or))
      (let ((types (cdr type)))
        (cond ((null types) (eq (car type) 'and))
              ((null (cdr types)) (cl-typep val (car types)))
              ((eq (car type) 'and)
               (and (cl-typep val (car types)) (cl-typep val (cons 'and (cdr types)))))
              (t (or (cl-typep val (car types)) (cl-typep val (cons 'or (cdr types))))))))
     ((and (eq (car-safe type) 'eql) (consp (cdr type)) (null (cdr (cdr type))))
      (and (eql val (car (cdr type))) t))
     ((eq (car-safe type) 'member) (and (memql val (cdr type)) t))
     ((and (eq (car-safe type) 'satisfies) (consp (cdr type)) (null (cdr (cdr type))))
      (funcall (car (cdr type)) val))
     ((and type (symbolp type) (get type 'cl-deftype-handler))
      (cl-typep val (funcall (get type 'cl-deftype-handler))))
     ((memq type '(nil t)) type)
     ((symbolp type)
      (let* ((name (symbol-name type))
             (namep (intern (concat name "p"))))
        (cond ((fboundp namep) (funcall namep val))
              ((fboundp (setq namep (intern (concat name "-p")))) (funcall namep val))
              ((fboundp type) (funcall type val))
              (t (error "Unknown type %S" type)))))
     (t (error "Bad type spec: %S" type)))))

;; ---- cl-defgeneric / cl-defmethod: single/multi type-dispatch with CLOS
;; method combination — primary plus :before/:after/:around qualifiers and
;; `cl-call-next-method'/`cl-next-method-p'. Methods are kept per generic name
;; in `cl--generic-table' as (QUALIFIER SPECS . FN); a call selects the
;; applicable methods, orders them by specificity, and runs the effective method.
(defvar cl--generic-table nil)
(defvar cl--cnm-args nil)
(defvar cl--cnm-next nil)
;; cl-generic.el: the three method-lookup failures share `cl-no-method'.
(define-error 'cl-no-method "No method")
(define-error 'cl-no-next-method "No next method" 'cl-no-method)
(define-error 'cl-no-primary-method "No primary method" 'cl-no-method)
(define-error 'cl-no-applicable-method "No applicable method" 'cl-no-method)
(defun cl--spec-match (sp arg)
  (cond ((eq sp t) t)
        ((and (consp sp) (eq (car sp) 'eql)) (eql arg (car (cdr sp))))
        ((and (consp sp) (eq (car sp) 'head)) (and (consp arg) (eq (car arg) (car (cdr sp)))))
        (t (cl-typep arg sp))))
(defun cl--type-rank (sp)
  ;; Higher = more specific, so it wins ties between applicable methods.
  (cond ((eq sp t) 0)
        ((and (consp sp) (memq (car sp) '(eql head))) 100)
        ((memq sp '(number list sequence array atom integer-or-marker)) 2)
        (t 3)))
(defun cl--add-method (name qualifier specs fn)
  (let ((entry (assq name cl--generic-table)))
    (unless entry
      (setq entry (cons name nil) cl--generic-table (cons entry cl--generic-table)))
    (setcdr entry (cons (cons qualifier (cons specs fn))
                        (cl-remove-if (lambda (m) (and (eq (car m) qualifier)
                                                       (equal (car (cdr m)) specs)))
                                      (cdr entry))))))
(defun cl--sortq (app qual desc)
  ;; The FNs in APP (each (SCORE QUALIFIER FN)) whose qualifier is QUAL, ordered
  ;; by SCORE (descending when DESC).
  (let ((sel (cl-remove-if-not (lambda (e) (eq (car (cdr e)) qual)) app)))
    (setq sel (sort sel (lambda (a b) (if desc (> (car a) (car b)) (< (car a) (car b))))))
    (mapcar (lambda (e) (car (cdr (cdr e)))) sel)))
(defun cl-call-next-method (&rest newargs)
  (let ((args (if newargs newargs cl--cnm-args)))
    (if cl--cnm-next (funcall cl--cnm-next args) (signal 'cl-no-next-method nil))))
(defun cl-next-method-p () (and cl--cnm-next t))
(defun cl--chain (methods final args)
  ;; Run METHODS[0] with `cl-call-next-method' wired to the rest, ending in FINAL
  ;; (a one-arg thunk) or signaling when exhausted.
  (if (null methods)
      (if final (funcall final args) (signal 'cl-no-next-method nil))
    (let ((cl--cnm-args args)
          (cl--cnm-next (if (or (cdr methods) final)
                            (let ((rest (cdr methods)))
                              (lambda (a) (cl--chain rest final a)))
                          nil)))
      (apply (car methods) args))))
(defun cl--generic-dispatch (name args)
  (let ((methods (cdr (assq name cl--generic-table))) (app nil))
    (dolist (m methods)
      ;; m = (QUALIFIER SPECS . FN)
      (let ((specs (car (cdr m))) (score 0) (ok t) (a args))
        (while (and specs ok)
          (let ((sp (car specs)))
            (if (cl--spec-match sp (car a)) (setq score (+ score (cl--type-rank sp)))
              (setq ok nil)))
          (setq specs (cdr specs) a (cdr a)))
        (when ok (setq app (cons (list score (car m) (cdr (cdr m))) app)))))
    (let ((arounds (cl--sortq app :around t))
          (befores (cl--sortq app :before t))
          (primaries (cl--sortq app nil t))
          (afters (cl--sortq app :after nil)))
      (if (and (null primaries) (null arounds))
          (signal 'cl-no-applicable-method (cons name args))
        (let ((core (lambda (a)
                      (dolist (b befores) (apply b a))
                      (let ((result (cl--chain primaries nil a)))
                        (dolist (af afters) (apply af a))
                        result))))
          (if arounds (cl--chain arounds core args) (funcall core args)))))))
(defun cl--method-spec (sp)
  ;; Build a FORM that evaluates to the runtime specializer for arglist entry SP.
  (cond
   ;; `(eql EXPR)' evaluates EXPR (Emacs 30 lifted the literal-only rule)...
   ((and (consp sp) (eq (car sp) 'eql))
    (list 'list (list 'quote 'eql) (car (cdr sp))))
   ;; ...but `(head SYMBOL)' does NOT: it names the symbol the argument's car
   ;; must be `eq' to.  Evaluating it made `(cl-defmethod g ((x (head foo))) …)'
   ;; a `void-variable foo', and where `foo' happened to be bound it dispatched
   ;; on that value instead: `(let ((foo 'bar)) …(g '(foo 1)))' is `hf' in Emacs.
   ((and (consp sp) (eq (car sp) 'head))
    (list 'quote (list 'head (car (cdr sp)))))
   (t (list 'quote sp))))
(defmacro cl-defmethod (name &rest body)
  (declare (doc-string cl--defmethod-doc-pos) (indent defun))
  ;; (cl-defmethod NAME [QUALIFIER] ARGLIST BODY...) — QUALIFIER is an optional
  ;; :before/:after/:around keyword.
  (let ((qualifier nil) (arglist nil) (plain nil) (specs nil) (mode 'req))
    (when (keywordp (car body)) (setq qualifier (car body) body (cdr body)))
    (setq arglist (car body) body (cdr body))
    (dolist (a arglist)
      (cond
       ((memq a '(&optional &rest &key)) (setq mode a) (setq plain (cons a plain)))
       ((and (eq mode 'req) (consp a))
        (setq plain (cons (car a) plain) specs (cons (cl--method-spec (car (cdr a))) specs)))
       ((eq mode 'req) (setq plain (cons a plain) specs (cons t specs)))
       (t (setq plain (cons a plain)))))
    (setq plain (nreverse plain) specs (nreverse specs))
    (list 'progn
          (list 'cl--add-method (list 'quote name) qualifier (cons 'list specs)
                ;; cl-generic.el: `(cl-function (lambda ,plain-args ,@body))'.
                (list 'cl-function (cons 'lambda (cons plain body))))
          (list 'defun name '(&rest --args--)
                (list 'cl--generic-dispatch (list 'quote name) '--args--))
          (list 'quote name))))
(defmacro cl-defgeneric (name arglist &rest body)
  (declare (indent 2) (doc-string 3))
  ;; Establish the dispatcher; real body forms become an unspecialized default.
  (let ((real (cl-remove-if
               (lambda (f) (or (stringp f)
                               (and (consp f) (memq (car f) '(declare :documentation)))))
               body)))
    (append
     (list 'progn
           (list 'unless (list 'assq (list 'quote name) 'cl--generic-table)
                 (list 'setq 'cl--generic-table
                       (list 'cons (list 'cons (list 'quote name) nil) 'cl--generic-table))))
     (when real
       (list (list 'cl--add-method (list 'quote name) nil nil
                   (list 'cl-function (cons 'lambda (cons arglist real))))))
     ;; `cl-defgeneric' answers nil, not its own name: the trailing `defun'
     ;; would otherwise leave the symbol as the `progn''s value.
     (list (list 'defun name '(&rest --args--)
                 (list 'cl--generic-dispatch (list 'quote name) '--args--))
           nil))))
(defmacro cl-the (_type form) form)
(defmacro cl-assert (form &optional _show-args string &rest args)
  ;; With a STRING, signal a plain `error' with the formatted message; otherwise
  ;; `cl-assertion-failed' carrying the failed FORM.
  (if string
      (list 'if form nil (cons 'error (cons string args)))
    (list 'if form nil (list 'signal (list 'quote 'cl-assertion-failed) (list 'list (list 'quote form))))))
;; simple.el's `region-active-p' (with the mark subsystem above), placed after
;; the `cl-assert' it expands.
(defun region-active-p ()
  (and transient-mark-mode mark-active
       (progn (cl-assert (mark)) t)))
;; cl-macs.el: the signal DATA is (STRING-or-TYPE VALUE FORM), FORM evaluated once.
;; (`macroexp-let2' is defined further down, after this body is compiled, so its
;; expansion is spelled out.)
(defmacro cl-check-type (form type &optional string)
  (let* ((temp (if (macroexp-copyable-p form) form (make-symbol "temp")))
         (body `(progn (or (cl-typep ,temp ',type)
                           (signal 'wrong-type-argument
                                   (list ,(or string `',type) ,temp ',form)))
                       nil)))
    (if (eq temp form) body `(let ((,temp ,form)) ,body))))
;; (cl-do ((VAR INIT [STEP])...) (END RESULT...) BODY...): like CL `do', with
;; the steps computed from the previous iteration's values (parallel assignment).
(defmacro cl-do (specs endclause &rest body)
  (let ((inits nil) (steps nil) (tmps nil))
    (dolist (s specs)
      (let ((var (if (consp s) (car s) s))
            (init (if (consp s) (car (cdr s)) nil))
            (has-step (and (consp s) (cdr (cdr s)))))
        (setq inits (cons (list var init) inits))
        (when has-step
          (let ((tv (make-symbol (symbol-name var))))
            (setq tmps (cons (list tv (car (cdr (cdr s)))) tmps))
            (setq steps (cons (list var tv) steps))))))
    (setq inits (nreverse inits) tmps (nreverse tmps) steps (nreverse steps))
    (let ((setqargs nil))
      (dolist (p steps)
        (setq setqargs (cons (car p) setqargs))
        (setq setqargs (cons (car (cdr p)) setqargs)))
      (setq setqargs (nreverse setqargs))
      `(let ,inits
         (while (not ,(car endclause))
           ,@body
           (let ,tmps (setq ,@setqargs)))
         ,@(cdr endclause)))))
;; cl-do*: like cl-do but bindings and step assignments are sequential (let* and
;; an in-order setq), so each spec sees the updated earlier ones.
(defmacro cl-do* (specs endclause &rest body)
  (let ((inits nil) (steps nil))
    (dolist (s specs)
      (let ((var (if (consp s) (car s) s))
            (init (if (consp s) (car (cdr s)) nil))
            (has-step (and (consp s) (cdr (cdr s)))))
        (setq inits (cons (list var init) inits))
        (when has-step
          (setq steps (cons (car (cdr (cdr s))) (cons var steps))))))
    (setq inits (nreverse inits) steps (nreverse steps))
    `(let* ,inits
       (while (not ,(car endclause))
         ,@body
         (setq ,@steps))
       ,@(cdr endclause))))
;; cl-progv: dynamically bind the runtime lists SYMBOLS to VALUES around BODY,
;; restoring (or unbinding) each afterwards.
(defmacro cl-progv (symbols values &rest body)
  `(let* ((--pv-syms-- ,symbols)
          (--pv-saved-- (mapcar (lambda (s) (list s (boundp s) (and (boundp s) (symbol-value s))))
                                --pv-syms--)))
     (unwind-protect
         (progn
           (let ((ss --pv-syms--) (vv ,values))
             (while ss (set (car ss) (car vv)) (setq ss (cdr ss) vv (cdr vv))))
           ,@body)
       (dolist (e --pv-saved--)
         (if (nth 1 e) (set (car e) (nth 2 e)) (makunbound (car e)))))))
;; Build let* bindings that positionally destructure VALEXPR (a symbol holding a
;; list) against a flat ARGLIST, honoring &optional and &rest.
(defun cl-db--plist-get (plist key default)
  ;; plist-get with a fallback when KEY is absent (for &key defaults).
  (let ((m (plist-member plist key))) (if m (car (cdr m)) default)))
(defun cl-db--arity (arglist)
  ;; (MIN . MAX) element counts a destructuring ARGLIST accepts; MAX is nil for
  ;; no upper bound (&rest / &body / &key or a dotted tail allow extra elements).
  ;; &aux vars consume nothing, so they neither raise MIN nor lift the bound.
  (let ((min 0) (max 0) (mode 'req) (unbounded nil))
    (when (eq (car arglist) '&whole) (setq arglist (cddr arglist)))
    (while (consp arglist)
      (let ((a (car arglist)))
        (cond
         ((eq a '&optional) (setq mode 'opt))
         ((memq a '(&rest &body &key)) (setq mode 'done unbounded t))
         ((eq a '&aux) (setq mode 'done))
         ((eq mode 'done) nil)
         ((eq mode 'opt) (setq max (1+ max)))
         (t (setq min (1+ min) max (1+ max)))))
      (setq arglist (cdr arglist)))
    (when (and arglist (symbolp arglist)) (setq unbounded t))
    (cons min (if unbounded nil max))))
(defun cl-db--check (val min max arglist)
  ;; Signal `wrong-number-of-arguments' when VAL's length is outside [MIN,MAX]
  ;; (MAX nil = unbounded), reporting ARGLIST like Emacs' cl-destructuring-bind.
  (let ((n (length val)))
    (when (or (< n min) (and max (> n max)))
      (signal 'wrong-number-of-arguments (list arglist n))))
  nil)
(defun cl-db--binds (arglist v &optional check)
  ;; Supports &whole, &optional / &rest / &key with per-arg defaults `(VAR DEFAULT)`
  ;; and nested patterns in required position. &key reads the plist tail at pos i.
  ;; When CHECK (the top-level arglist to report) is non-nil, an arity guard is
  ;; emitted so cl-destructuring-bind errors on length mismatch; cl-loop passes
  ;; no CHECK and stays lenient, matching Emacs in both cases.
  (let ((binds nil) (i 0) (mode 'req)
        (haskey nil) (allow nil) (keystart 0) (keywords nil))
    ;; Leading (&whole VAR …): bind VAR to the whole value, then continue.
    (when (eq (car arglist) '&whole)
      (setq binds (cons (list (car (cdr arglist)) v) binds))
      (setq arglist (cddr arglist)))
    (when check
      (let ((ar (cl-db--arity arglist)))
        (setq binds (cons (list (make-symbol "--cl-db-chk--")
                                (list 'cl-db--check v (car ar) (cdr ar)
                                      (list 'quote check)))
                          binds))))
    (while (consp arglist)
      (let ((a (car arglist)))
        (cond
         ((eq a '&optional) (setq mode 'opt))
         ((eq a '&rest) (setq mode 'rest))
         ((eq a '&key) (setq mode 'key haskey t keystart i))
         ((eq a '&allow-other-keys) (setq allow t))
         ((eq a '&aux) (setq mode 'aux))
         ((eq mode 'rest) (setq binds (cons (list a (list 'nthcdr i v)) binds)))
         ((eq mode 'aux)
          (let ((var (if (consp a) (car a) a)) (def (and (consp a) (car (cdr a)))))
            (setq binds (cons (list var def) binds))))
         ((eq mode 'key)
          ;; cl-macs.el: VAR, (VAR DEFAULT SVAR) or ((KEYWORD VAR) DEFAULT SVAR);
          ;; SVAR is t when the keyword was supplied.
          (let* ((spec (if (consp a) (car a) a))
                 (var (if (consp spec) (car (cdr spec)) spec))
                 (def (and (consp a) (car (cdr a))))
                 (svar (and (consp a) (car (cdr (cdr a)))))
                 (kw (if (consp spec) (car spec) (intern (concat ":" (symbol-name var))))))
            (setq keywords (cons kw keywords))
            (setq binds (cons (list var (list 'cl-db--plist-get (list 'nthcdr i v)
                                              (list 'quote kw) def))
                              binds))
            (when svar
              (setq binds (cons (list svar (list 'and (list 'plist-member (list 'nthcdr i v)
                                                           (list 'quote kw))
                                                 t))
                                binds)))))
         ((eq mode 'opt)
          (let ((var (if (consp a) (car a) a)) (def (and (consp a) (car (cdr a))))
                (svar (and (consp a) (car (cdr (cdr a))))))
            (setq binds (cons (list var (list 'if (list 'nthcdr i v) (list 'nth i v) def))
                              binds))
            (when svar
              (setq binds (cons (list svar (list 'and (list 'nthcdr i v) t)) binds)))
            (setq i (1+ i))))
         ((consp a)
          ;; Nested pattern: bind a temp to the element, then destructure it.
          (let ((tv (make-symbol "db")))
            (setq binds (cons (list tv (list 'nth i v)) binds))
            (dolist (rb (cl-db--binds a tv check)) (setq binds (cons rb binds))))
          (setq i (1+ i)))
         (t (setq binds (cons (list a (list 'nth i v)) binds)) (setq i (1+ i)))))
      (setq arglist (cdr arglist)))
    ;; &key keyword validation (only under CHECK, i.e. cl-destructuring-bind).
    ;; Faithful to cl-macs.el: reject any keyword not among the &key names unless
    ;; the lambda-list has &allow-other-keys or the plist carries :allow-other-keys t.
    (when (and check haskey (not allow))
      (let ((ks (make-symbol "--cl-keys--"))
            (tail (list 'nthcdr keystart v))
            (allowed (reverse keywords)))
        (setq binds
              (cons
               (list (make-symbol "--cl-db-keychk--")
                     (list 'let (list (list ks tail))
                           (list 'while ks
                                 (list 'cond
                                       (list (list 'memq (list 'car ks)
                                                   (list 'quote (append allowed '(:allow-other-keys))))
                                             (list 'if (list 'cdr ks) nil
                                                   (list 'error "Missing argument for %s" (list 'car ks)))
                                             (list 'setq ks (list 'cddr ks)))
                                       (list (list 'car (list 'cdr (list 'memq '':allow-other-keys tail)))
                                             (list 'setq ks nil))
                                       (list t (list 'error "Keyword argument %s not one of %s"
                                                     (list 'car ks) (list 'quote allowed)))))))
               binds))))
    ;; A dotted tail — e.g. (K . V) — binds the trailing symbol to the rest.
    (when (and arglist (symbolp arglist))
      (setq binds (cons (list arglist (list 'nthcdr i v)) binds)))
    (reverse binds)))
(defmacro cl-destructuring-bind (arglist expr &rest body)
  `(let ((--cl-db-v-- ,expr))
     (let* ,(cl-db--binds arglist '--cl-db-v-- arglist) ,@body)))
;; `cl-defun' and `cl-defmacro' are cl-macs.el's, built on `cl--transform-lambda'
;; before the first top-level `cl-defstruct' (`ppss').
;; cl multiple values are just lists in this model.
(defun cl-values (&rest vals) vals)
(defun cl-values-list (l) l)
(defmacro cl-multiple-value-bind (vars form &rest body)
  `(cl-destructuring-bind ,vars ,form ,@body))
(defmacro cl-multiple-value-setq (vars form)
  (let ((tmp (make-symbol "mv")))
    `(let ((,tmp ,form))
       ,@(let ((sets nil) (i 0) (vs vars))
           (while vs
             (setq sets (cons (list 'setq (car vs) (list 'nth i tmp)) sets) i (1+ i) vs (cdr vs)))
           (reverse sets))
       ,tmp)))

;; ---- setf: generalized-variable assignment ----
;; Expands (setf PLACE VALUE) to the right mutator for PLACE. Supported places
;; (those whose setter primitives exist): a plain variable, car/cdr and the
;; two-level c[ad][ad]r accessors, nth, elt, aref, gethash, and symbol-value.
;; Each setter returns VALUE, so (setf …) yields the last assigned value, as in
;; Emacs. Backquote-pattern places (cl-struct slots, alist-get) wait on more
;; setter primitives.
;; Maps a cl-defstruct accessor symbol to its slot index (populated by
;; `cl-defstruct' when it runs, consulted by `setf--expand' when expanding later
;; top-level forms — which works because forms are processed in order).
(defvar cl-struct--slot-index nil)
;; The same, for the accessors of a `(:type list)' struct, whose setter is
;; `(setcar (nthcdr INDEX S) V)' because there is nothing to `aset'.
(defvar cl-struct--slot-list-index nil)
;; Accessors of `:read-only' cl-defstruct slots. `setf--expand' signals the same
;; "ACCESSOR is a read-only slot" error cl-macs.el:3260 raises via gv-define-expander.
(defvar cl-struct--slot-readonly nil)
(defun setf--expand (place val)
  (if (symbolp place)
      (list 'setq place val)
    ;; gv.el:80 rejects a place that is neither a symbol nor a cons with its own
    ;; condition; falling through to `(car place)' reported `listp' instead.
    (unless (consp place) (signal 'gv-invalid-place (list place)))
    (let ((head (car place)) (args (cdr place)))
      (cond
       ((eq head 'car) (list 'setcar (car args) val))
       ((eq head 'cdr) (list 'setcdr (car args) val))
       ;; c[ad]+r, two to four letters: subr.el's compiler macro rewrites each to
       ;; its car/cdr chain, so the place is set{car,cdr} of the accessor made of
       ;; the remaining letters — (setf (cadadr X) V) is (setcar (cdadr X) V).
       ((and (symbolp head)
             (string-match-p "\\`c[ad][ad][ad]?[ad]?r\\'" (symbol-name head)))
        (let ((name (symbol-name head)))
          (list (if (eq (aref name 1) ?a) 'setcar 'setcdr)
                (list (intern (concat "c" (substring name 2))) (car args))
                val)))
       ((eq head 'nth) (list 'setcar (list 'nthcdr (car args) (car (cdr args))) val))
       ;; (setf (nthcdr N L) V): N=0 replaces L; else setcdr the (N-1)th cell.
       ((eq head 'nthcdr)
        (list 'let (list (list '--setf-nc-- (car args)))
              (list 'if (list '<= '--setf-nc-- 0)
                    (setf--expand (car (cdr args)) val)
                    (list 'setcdr (list 'nthcdr (list '1- '--setf-nc--) (car (cdr args))) val))))
       ((memq head '(elt seq-elt))
        ;; Bind the sequence + index once: list → setcar, array → aset.
        (list 'let (list (list '--setf-s-- (car args)) (list '--setf-n-- (car (cdr args))))
              (list 'if (list 'listp '--setf-s--)
                    (list 'setcar (list 'nthcdr '--setf-n-- '--setf-s--) val)
                    (list 'aset '--setf-s-- '--setf-n-- val))))
       ((eq head 'aref) (list 'aset (car args) (car (cdr args)) val))
       ((eq head 'gethash) (list 'puthash (car args) val (car (cdr args))))
       ((eq head 'symbol-value) (list 'set (car args) val))
       ;; (setf (default-value SYM) V) -> (set-default SYM V) (gv.el simple setter).
       ((eq head 'default-value) (list 'set-default (car args) val))
       ((eq head 'symbol-function) (list 'fset (car args) val))
       ;; (setf (get SYM PROP) V) -> (put SYM PROP V).
       ((eq head 'get) (list 'put (car args) (car (cdr args)) val))
       ;; (setf (cl-get SYM PROP DEF) V) -> (put SYM PROP V); DEF is ignored, as in
       ;; cl-extra.el's gv-setter.
       ((eq head 'cl-get) (list 'put (car args) (car (cdr args)) val))
       ;; (setf (cl--find-class NAME) CLASS) -> (put NAME 'cl--class CLASS).
       ;; `cl--find-class' stores class descriptors on the symbol's plist, exactly
       ;; as cl-preloaded.el does; this is its gv setter.
       ((eq head 'cl--find-class)
        (list 'put (car args) (list 'quote 'cl--class) val))
       ;; cl-first..cl-tenth name list positions; cl-rest is the cdr.
       ((eq head 'cl-rest) (list 'setcdr (car args) val))
       ((memq head '(cl-first cl-second cl-third cl-fourth cl-fifth
                     cl-sixth cl-seventh cl-eighth cl-ninth cl-tenth))
        (let ((idx (cdr (assq head '((cl-first . 0) (cl-second . 1) (cl-third . 2)
                                     (cl-fourth . 3) (cl-fifth . 4) (cl-sixth . 5)
                                     (cl-seventh . 6) (cl-eighth . 7) (cl-ninth . 8)
                                     (cl-tenth . 9))))))
          (list 'setcar (list 'nthcdr idx (car args)) val)))
       ;; `decoded-time' is `(cl-defstruct (decoded-time (:type list)) ...)' in
       ;; Emacs (simple.el:11111), so its accessors are list-position places whose
       ;; setter is `(setcar (nthcdr INDEX TIME) VAL)' — the same expansion a
       ;; `:type list' struct generates.  time-date.el relies on it (e.g.
       ;; `(setf (decoded-time-month time) ...)', `(cl-incf (decoded-time-year time) ...)').
       ((assq head '((decoded-time-second . 0) (decoded-time-minute . 1)
                     (decoded-time-hour . 2) (decoded-time-day . 3)
                     (decoded-time-month . 4) (decoded-time-year . 5)
                     (decoded-time-weekday . 6) (decoded-time-dst . 7)
                     (decoded-time-zone . 8)))
        (list 'setcar
              (list 'nthcdr
                    (cdr (assq head '((decoded-time-second . 0) (decoded-time-minute . 1)
                                      (decoded-time-hour . 2) (decoded-time-day . 3)
                                      (decoded-time-month . 4) (decoded-time-year . 5)
                                      (decoded-time-weekday . 6) (decoded-time-dst . 7)
                                      (decoded-time-zone . 8))))
                    (car args))
              val))
       ;; (setf (alist-get K AL &optional DEFAULT REMOVE TESTFN) V): setcdr an
       ;; existing pair (found via TESTFN or eq), else prepend. With REMOVE, a V
       ;; equal to DEFAULT deletes the entry instead.
       ((eq head 'alist-get)
        (let* ((key (car args)) (al (nth 1 args)) (default (nth 2 args))
               (remove (nth 3 args)) (testfn (nth 4 args))
               (getter (if testfn (list 'assoc key al testfn) (list 'assq key al)))
               (eq-default (list 'eql '--ag-v-- default)))
          (if remove
              (list 'let (list (list '--ag-v-- val) (list '--ag-p-- getter))
                    (list 'if eq-default
                          (list 'when '--ag-p-- (setf--expand al (list 'delq '--ag-p-- al)))
                          (list 'if '--ag-p--
                                (list 'setcdr '--ag-p-- '--ag-v--)
                                (setf--expand al (list 'cons (list 'cons key '--ag-v--) al)))))
            (list 'let (list (list '--ag-p-- getter))
                  (list 'if '--ag-p--
                        (list 'setcdr '--ag-p-- val)
                        (setf--expand al (list 'cons (list 'cons key val) al)))))))
       ;; (setf (plist-get P K) V) / (setf (cl-getf P K) V): set an existing value
       ;; cell, else prepend (K V) to P — matching Emacs's order for a new key.
       ((memq head '(plist-get cl-getf))
        (list 'let (list (list '--pg-m-- (list 'plist-member (car args) (car (cdr args)))))
              (list 'if '--pg-m--
                    (list 'setcar (list 'cdr '--pg-m--) val)
                    (setf--expand (car args)
                                  (list 'cons (car (cdr args)) (list 'cons val (car args)))))))
       ;; A read-only cl-defstruct slot: setf is an error (cl-macs.el:3260).
       ((memq head cl-struct--slot-readonly)
        (error "%s is a read-only slot" head))
       ;; A cl-defstruct accessor: (setf (NAME-SLOT s) v) -> (aset s INDEX v).
       ((assq head cl-struct--slot-index)
        (list 'aset (car args) (cdr (assq head cl-struct--slot-index)) val))
       ;; The `(:type list)' form of the same: the slot is a list position.
       ((assq head cl-struct--slot-list-index)
        (list 'setcar
              (list 'nthcdr (cdr (assq head cl-struct--slot-list-index)) (car args))
              val))
       ;; (setf (map-elt MAP KEY [DEFAULT [TESTFN]]) V): map.el's gv-expander --
       ;; `map-put!' in place, else rebind MAP to `map-insert' when the map has to
       ;; grow (an alist, or nil).
       ((eq head 'map-elt)
        (list 'let
              (list (list '--me-v-- val))
              (list 'condition-case nil
                    (list 'map-put! (car args) (car (cdr args)) '--me-v-- (nth 3 args))
                    (list 'map-not-inplace
                          (setf--expand (car args)
                                        (list 'map-insert (car args) (car (cdr args)) '--me-v--))
                          '--me-v--))))
       ;; (setf (cl-subseq SEQ START &optional END) V): destructively copy V into
       ;; SEQ[START..END) via cl-replace, then yield V — matching cl-lib's setter.
       ((eq head 'cl-subseq)
        (list 'let (list (list '--ss-v-- val))
              (list 'cl-replace (car args) '--ss-v--
                    :start1 (car (cdr args)) :end1 (car (cddr args)))
              '--ss-v--))
       ;; Control-flow places (gv.el): setf threads into the value position of
       ;; each branch.  Only one branch runs, so VAL may appear textually more
       ;; than once without being evaluated twice.
       ;; (setf (if C THEN ELSE...) V) -> (if C (setf THEN V) (setf (progn ELSE...) V))
       ((eq head 'if)
        (list 'if (car args)
              (setf--expand (car (cdr args)) val)
              (setf--expand (cons 'progn (cdr (cdr args))) val)))
       ;; (setf (progn A B C) V) -> (progn A B (setf C V))
       ((eq head 'progn)
        (append (list 'progn) (butlast args)
                (list (setf--expand (car (last args)) val))))
       ;; (setf (cond (T A B) ...) V) -> (cond (T A (setf B V)) ...)
       ((eq head 'cond)
        (cons 'cond
              (mapcar (lambda (clause)
                        (append (list (car clause)) (butlast (cdr clause))
                                (list (setf--expand (car (last clause)) val))))
                      args)))
       ;; Unknown head: consult the gv.el registry first (gv.el:98 checks the
       ;; `gv-expander' property before anything else), so any place registered
       ;; via `gv-define-setter'/`gv-define-expander' (e.g. `gv-deref', user
       ;; places) works.  `setf' is exactly `(gv-letplace (_getter setter) place
       ;; (funcall setter val))' (gv.el:288).
       (t (let ((gf (function-get head 'gv-expander 'autoload)))
            (if gf
                (apply gf (lambda (_getter setter) (funcall setter val)) args)
              ;; No gv-expander: if PLACE is a macro call, expand it once and
              ;; retry (gv.el:103), else use the `(setf HEAD)' function setter
              ;; (installed via `(defalias (gv-setter aname) ...)').
              (let ((me (macroexpand-1 place)))
                (if (eq me place)
                    ;; Follow a function alias (gv.el:112), so `cl-caddr' is
                    ;; a place because `caddr' is.
                    (if (and (fboundp head) (symbolp (symbol-function head))
                             (symbol-function head))
                        (setf--expand (cons (symbol-function head) args) val)
                    (let ((setter (intern (format "(setf %s)" head))))
                      (if (fboundp setter)
                          (cons 'funcall (cons (list 'function setter) (cons val args)))
                        (signal 'gv-invalid-place (list place)))))
                  (setf--expand me val))))))))))
(defmacro setf (&rest pairs)
  (let ((forms nil))
    (while pairs
      (setq forms (cons (setf--expand (car pairs) (car (cdr pairs))) forms))
      (setq pairs (cdr (cdr pairs))))
    (cons 'progn (reverse forms))))

;; ---- hooks (subr.el `add-hook'; C `run-hooks'/`run-hook-with-args') ----
;; Defined after the full `setf' (add-hook's depth-alist branch uses a `get'
;; place).  add-hook is ported verbatim; the depth-alist / buffer-local branches
;; are dead in elisprs's global-only, no-buffer-local model but kept faithful.
(defun add-hook (hook function &optional depth local)
  "Add to the value of HOOK the function FUNCTION.
FUNCTION is not added if already present."
  (or (boundp hook) (set hook nil))
  (or (default-boundp hook) (set-default hook nil))
  (unless (numberp depth) (setq depth (if depth 90 0)))
  (if local (unless (local-variable-if-set-p hook)
	      (set (make-local-variable hook) (list t)))
    (when (and (local-variable-if-set-p hook)
               (not (and (consp (symbol-value hook))
                         (memq t (symbol-value hook)))))
      (setq local t)))
  (let ((hook-value (if local (symbol-value hook) (default-value hook))))
    (when (or (not (listp hook-value)) (functionp hook-value))
      (setq hook-value (list hook-value)))
    (unless (member function hook-value)
      (let ((depth-sym (get hook 'hook--depth-alist)))
        (unless (zerop depth)
          (unless depth-sym
            (setq depth-sym (make-symbol "depth-alist"))
            (set depth-sym nil)
            (setf (get hook 'hook--depth-alist) depth-sym))
          (if local (make-local-variable depth-sym))
          (setf (alist-get function
                           (if local (symbol-value depth-sym)
                             (default-value depth-sym))
                           0)
                depth))
        (setq hook-value
	      (if (< 0 depth)
		  (append hook-value (list function))
		(cons function hook-value)))
        (when depth-sym
          (let ((depth-alist (if local (symbol-value depth-sym)
                               (default-value depth-sym))))
            (when depth-alist
              (setq hook-value
                    (sort (if (< 0 depth) hook-value (copy-sequence hook-value))
                          (lambda (f1 f2)
                            (< (alist-get f1 depth-alist 0 nil #'eq)
                               (alist-get f2 depth-alist 0 nil #'eq))))))))))
    (if local
	(progn
	  (and (symbolp function)
	       (get function 'permanent-local-hook)
	       (not (get hook 'permanent-local))
	       (put hook 'permanent-local 'permanent-local-hook))
	  (set hook hook-value))
      (set-default hook hook-value))))
(defun run-hook-with-args (hook &rest args)
  "Run HOOK with the specified arguments ARGS.
HOOK should be a symbol; its value is a function or a list of functions."
  (when (boundp hook)
    (let ((value (symbol-value hook)))
      (if (functionp value)
          (apply value args)
        (dolist (f value)
          (unless (eq f t)
            (apply f args)))
        nil))))
(defun run-hooks (&rest hooks)
  "Run each hook in HOOKS, which are symbols whose values are lists of functions."
  (dolist (hook hooks)
    (run-hook-with-args hook))
  nil)
(defun run-hook-with-args-until-success (hook &rest args)
  "Run HOOK's functions with ARGS, stopping at the first non-nil result.
Return that result, or nil if every function returned nil."
  ;; C `run_hook_with_args' with `until_success' (eval.c). A hook whose value is
  ;; a single function is that one call; `t' inside a list is the buffer-local
  ;; marker and is skipped, as in `run-hook-with-args'.
  (when (boundp hook)
    (let ((value (symbol-value hook)))
      (if (functionp value)
          (apply value args)
        (let ((res nil))
          (while (and value (null res))
            (unless (eq (car value) t)
              (setq res (apply (car value) args)))
            (setq value (cdr value)))
          res)))))
(defun run-hook-with-args-until-failure (hook &rest args)
  "Run HOOK's functions with ARGS, stopping at the first nil result.
Return nil if one returned nil, t otherwise."
  ;; C `run_hook_with_args' with `until_failure'. An unbound or empty hook has
  ;; no function that can fail, so the answer is t.
  (if (not (boundp hook))
      t
    (let ((value (symbol-value hook)))
      (if (functionp value)
          (apply value args)
        (let ((ok t))
          (while (and value ok)
            (unless (eq (car value) t)
              (setq ok (apply (car value) args)))
            (setq value (cdr value)))
          (and ok t))))))
(defun run-hook-wrapped (hook wrap-function &rest args)
  "Run HOOK's functions through WRAP-FUNCTION, stopping at the first non-nil.
Each function F is invoked as (funcall WRAP-FUNCTION F ARGS...)."
  ;; C `run_hook_wrapped' (eval.c): the wrapper decides how to call F, which is
  ;; what lets a caller install a `condition-case' or a timing shim around every
  ;; hook function without rewriting the hook.
  (when (boundp hook)
    (let ((value (symbol-value hook)))
      (if (functionp value)
          (apply wrap-function value args)
        (let ((res nil))
          (while (and value (null res))
            (unless (eq (car value) t)
              (setq res (apply wrap-function (car value) args)))
            (setq value (cdr value)))
          res)))))
(defun remove-hook (hook function &optional local)
  "Remove FUNCTION from HOOK's functions.
Do nothing if HOOK does not currently contain FUNCTION."
  ;; Ported from subr.el:2186. FUNCTION is matched with `equal' (via `member'),
  ;; not `eq', so an anonymous function equal to the stored one removes it. The
  ;; depth-alist entry goes with it — leaving it behind leaks the entry and
  ;; re-orders the hook if the same function is added again (bug#46414).
  (or (boundp hook) (set hook nil))
  (or (default-boundp hook) (set-default hook nil))
  (unless (and local (not (local-variable-p hook)))
    (when (and (local-variable-p hook)
               (not (and (consp (symbol-value hook))
                         (memq t (symbol-value hook)))))
      (setq local t))
    (let ((hook-value (if local (symbol-value hook) (default-value hook)))
          (old-fun nil))
      (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
          (when (equal hook-value function)
            (setq old-fun hook-value)
            (setq hook-value nil))
        (when (setq old-fun (car (member function hook-value)))
          (setq hook-value (remq old-fun hook-value))))
      (when old-fun
        (let* ((depth-sym (get hook 'hook--depth-alist))
               (depth-alist (if depth-sym (if local (symbol-value depth-sym)
                                            (default-value depth-sym))))
               (di (assq old-fun depth-alist)))
          (when di
            (setf (if local (symbol-value depth-sym)
                    (default-value depth-sym))
                  (remq di depth-alist)))))
      (if (not local)
          (set-default hook hook-value)
        (if (equal hook-value '(t))
            (kill-local-variable hook)
          (set hook hook-value))))))

;; ---- pcase: structural `cond` (non-backquote subset) ----
;; Supported patterns (compiled to tests + bindings at macroexpansion time):
;;   _              wildcard — always matches
;;   nil / t / :kw  self-quoting literals (matched with `equal`)
;;   NUMBER STRING  self-quoting literals
;;   SYMBOL         binds SYMBOL to the value (anything not a literal above)
;;   'X / (quote X) literal X
;;   (pred FN)      matches when (FN VALUE) is non-nil; (pred (FN ARGS...)) →
;;                  (FN ARGS... VALUE), as in Emacs
;;   (guard EXPR)   matches when EXPR — which can read earlier bindings — is non-nil
;;   (and PAT...)   matches when every PAT matches (bindings accumulate)
;;   (or PAT...)    matches when any PAT matches
;;   `QPAT          pcase.el's backquote pattern: (Q1 . Q2) matches a cons,
;;                  [Q...] a vector of that length, ,PAT matches PAT, and
;;                  any other atom is compared with `equal'
;; How `pred'/`app' call FN on the value: a lambda or symbol gets VAL as its one
;; argument; a partial application (F ARGS…) appends VAL.
;; pcase.el `pcase--funcall': `_' in a call form stands for the matched value.
(defun pcase--apply (fn val)
  (cond ((symbolp fn) (list fn val))
        ((eq 'not (car-safe fn)) (list 'not (pcase--apply (car (cdr fn)) val)))
        ((or (functionp fn) (not (consp fn))) (list 'funcall (list 'function fn) val))
        ((memq '_ fn) (mapcar (lambda (x) (if (eq '_ x) val x)) fn))
        (t (append fn (list val)))))
(defconst regexp-unmatchable "\\`a\\`"
  "Standard regexp guaranteed not to match any string at all.")

(defvar tab-width 8
  "Distance between tab stops (for display of tab characters), in columns.
A buffer-local variable in Emacs; a plain global here, since elisprs has no
per-buffer display model.  `string-pixel-width' and `char-width' read it.")

;; `string-pixel-width' (lisp/emacs-lisp/subr-x.el) renders STRING in a temp
;; buffer and asks `window-text-pixel-size' for its width.  In batch every
;; character is one pixel wide per display column, so the pixel width IS the
;; display-column advance -- which is NOT `string-width': a TAB advances to the
;; next multiple of `tab-width' rather than counting a flat `tab-width' columns,
;; so `(string-pixel-width "ab\tc")' is 9 where `(string-width "ab\tc")' is 11.
;; A newline starts a new line and the widest line wins, so
;; `(string-pixel-width "a\nb")' is 1.
(defun string-pixel-width (string &optional _buffer)
  "Return the width of STRING in pixels, as `emacs -Q --batch' measures it."
  (let ((widest 0) (col 0) (i 0) (n (length string)) (c nil))
    (while (< i n)
      (setq c (aref string i))
      (cond ((eq c ?\n)
             (when (> col widest) (setq widest col))
             (setq col 0))
            ((eq c ?\t)
             (setq col (* tab-width (1+ (/ col tab-width)))))
            (t (setq col (+ col (char-width c)))))
      (setq i (1+ i)))
    (when (> col widest) (setq widest col))
    widest))

(defun pcase--literal-p (pat)
  (or (numberp pat) (stringp pat) (keywordp pat) (eq pat t) (null pat)))
;; pcase.el's `\`' pattern, as `pcase-defmacro \`' defines it: a cons is
;; (and (pred consp) (app car-safe `Q1) (app cdr-safe `Q2)), a vector
;; (and (pred vectorp) (app length LEN) (app (aref _ I) `QI)...), ,PAT is PAT,
;; and a string, number or symbol is 'QPAT. The element readers are guarded,
;; because `pcase--clause' establishes the binders before the tests run.
(defun pcase--compile-qpat (qpat val)
  (cond
   ((eq (car-safe qpat) '\,) (pcase--compile (car (cdr qpat)) val))
   ((eq (car-safe qpat) '\,@) (error "Unsupported QPAT: %S" qpat))
   ((vectorp qpat)
    (let* ((len (length qpat))
           (ok (list 'and (list 'vectorp val) (list '= (list 'length val) len)))
           (tests (list (list 'vectorp val) (list 'equal (list 'length val) len)))
           (binds nil)
           (i 0))
      (while (< i len)
        (let ((r (pcase--compile-qpat (aref qpat i)
                                      (list 'if ok (list 'aref val i)))))
          (setq tests (append tests (car r)))
          (setq binds (append binds (cdr r))))
        (setq i (1+ i)))
      (cons tests binds)))
   ((consp qpat)
    (let ((cr (pcase--compile-qpat (car qpat) (list 'car-safe val)))
          (cd (pcase--compile-qpat (cdr qpat) (list 'cdr-safe val))))
      (cons (cons (list 'consp val) (append (car cr) (car cd)))
            (append (cdr cr) (cdr cd)))))
   ((or (stringp qpat) (numberp qpat) (symbolp qpat))
    (pcase--compile (list 'quote qpat) val))
   (t (error "Unknown QPAT: %S" qpat))))
(defun pcase--compile (pat val)
  ;; Return (TESTS . BINDS): TESTS a list of boolean forms over VAL, BINDS a
  ;; list of (SYM ACCESSOR) let*-bindings. In this subset every binder captures
  ;; VAL whole, so accessors never car/cdr an atom.
  (cond
   ((eq pat '_) (cons nil nil))
   ((pcase--literal-p pat) (cons (list (list 'equal val (list 'quote pat))) nil))
   ((symbolp pat) (cons nil (list (list pat val))))
   ((consp pat)
    (let ((head (car pat)))
      (cond
       ((eq head 'quote) (cons (list (list 'equal val pat)) nil))
       ((eq head 'pred) (cons (list (pcase--apply (car (cdr pat)) val)) nil))
       ((eq head 'guard) (cons (list (car (cdr pat))) nil))
       ;; `(cl-type TYPE)': route through `cl-typep', not through a
       ;; symbol-to-predicate name mangle, so a COMPOUND specifier works --
       ;; `(pcase 3 ((cl-type (integer 0 5)) 'in) (_ 'out))' is `in', where
       ;; naming a predicate after `(integer 0 5)' was `wrong-type-argument
       ;; symbolp'.
       ((eq head 'cl-type)
        (cons (list (list 'cl-typep val (list 'quote (car (cdr pat))))) nil))
       ;; (app FN PAT): match PAT against (FN VAL).
       ((eq head 'app)
        (let* ((tv (make-symbol "app"))
               (r (pcase--compile (nth 2 pat) tv)))
          (cons (car r) (cons (list tv (pcase--apply (nth 1 pat) val)) (cdr r)))))
       ;; (let PAT EXPR): match PAT against EXPR's value (EXPR ignores VAL).
       ((eq head 'let)
        (let* ((tv (make-symbol "let"))
               (r (pcase--compile (nth 1 pat) tv)))
          (cons (car r) (cons (list tv (nth 2 pat)) (cdr r)))))
       ((eq head 'and)
        (let ((tests nil) (binds nil))
          (dolist (p (cdr pat))
            (let ((r (pcase--compile p val)))
              (setq tests (append tests (car r)))
              (setq binds (append binds (cdr r)))))
          (cons tests binds)))
       ((eq head 'or)
        (let ((alts nil) (binds nil))
          (dolist (p (cdr pat))
            (let ((r (pcase--compile p val)))
              (setq alts (append alts (list (cons 'and (car r)))))
              (setq binds (append binds (cdr r)))))
          (cons (list (cons 'or alts)) binds)))
       ((eq head '\`) (pcase--compile-qpat (car (cdr pat)) val))
       ;; (map KEY...): map.el's pattern. An element is a bare SYMBOL (bound to
       ;; the value at 'SYMBOL), a KEYWORD :k (binding k to the value at :k), or
       ;; a (KEY VAR [DEFAULT]) list whose KEY and DEFAULT are *evaluated*
       ;; forms. `map-elt' signals for anything that is not a map, and
       ;; `pcase--clause' establishes the binders before the tests run, so each
       ;; lookup is guarded by the same `mapp' the pattern tests.
       ((eq head 'map)
        (let ((tests (list (list 'mapp val))) (binds nil))
          (dolist (elt (cdr pat))
            (setq binds
                  (append binds
                          (list (cond
                                 ((consp elt)
                                  (list (nth 1 elt)
                                        (list 'if (list 'mapp val)
                                              (list 'map-elt val (nth 0 elt) (nth 2 elt)))))
                                 ((keywordp elt)
                                  (list (intern (substring (symbol-name elt) 1))
                                        (list 'if (list 'mapp val)
                                              (list 'map-elt val elt))))
                                 (t (list elt
                                          (list 'if (list 'mapp val)
                                                (list 'map-elt val (list 'quote elt))))))))))
          (cons tests binds)))
       ;; (cl-struct TYPE SLOT...): cl-lib's pattern. A SLOT is a bare name
       ;; (bound to itself) or (SLOT VAR). The slot reads are guarded by the
       ;; type test, because `pcase--clause' establishes the binders around the
       ;; tests and `cl-struct-slot-value' signals on the wrong type -- a
       ;; non-matching value has to FAIL the clause, not error out of it.
       ((eq head 'cl-struct)
        (let* ((type (nth 1 pat))
               (typed (list 'cl-typep val (list 'quote type)))
               (tests (list typed))
               (binds nil))
          (dolist (slot (cddr pat))
            (let ((name (if (consp slot) (car slot) slot))
                  (var (if (consp slot) (nth 1 slot) slot)))
              (setq binds
                    (append binds
                            (list (list var
                                        (list 'if typed
                                              (list 'cl-struct-slot-value
                                                    (list 'quote type)
                                                    (list 'quote name)
                                                    val))))))))
          (cons tests binds)))
       ;; seq.el's `(pcase-defmacro seq (&rest patterns))': `(and (pred seqp)
       ;; (app (seq--elt-safe _ I) PI)...)', the bindings in reverse order.
       ((eq head 'seq)
        (pcase--compile `(and (pred seqp) ,@(seq--make-pcase-bindings (cdr pat))) val))
       ;; A `pcase-defmacro' pattern: expand it and compile the expansion.
       ((and (symbolp head) (get head 'pcase-macroexpander))
        (pcase--compile (apply (get head 'pcase-macroexpander) (cdr pat)) val))
       (t (error "pcase: unsupported pattern %S" pat)))))
   (t (error "pcase: unsupported pattern %S" pat))))
;; pcase.el `pcase-defmacro': define the expander function NAME--pcase-macroexpander
;; and record it on NAME's `pcase-macroexpander' property.
(defmacro pcase-defmacro (name args &rest body)
  (let ((fsym (intern (format "%s--pcase-macroexpander" name))))
    (list 'progn
          (cons 'defun (cons fsym (cons args body)))
          (list 'define-symbol-prop (list 'quote name) ''pcase-macroexpander
                (list 'function fsym)))))
(defun pcase--clause (clause)
  ;; Build one `cond' clause (TEST BODY) from a pcase clause (PATTERN BODY...).
  ;; Bindings wrap BOTH the test and the body via `let*' so a `guard' in TEST
  ;; sees the binders. This `cond' shape (like `cl-case') expands cleanly when
  ;; nested in a macro-produced `defun' (e.g. an ERT `should'); a `catch'/`throw'
  ;; shape does not — it miscompiles to a "void variable" error there.
  (let* ((r (pcase--compile (car clause) '--pcase-v--))
         (tests (car r))
         (binds (cdr r))
         (conj (if tests (cons 'and tests) t))
         (test (if binds (list 'let* binds conj) conj))
         (body (cons 'progn (cdr clause))))
    (list test (if binds (list 'let* binds body) body))))
(defmacro pcase (expr &rest clauses)
  `(let ((--pcase-v-- ,expr))
     (cond ,@(mapcar (function pcase--clause) clauses))))
(defmacro pcase-exhaustive (expr &rest clauses)
  ;; Like pcase, but error if no clause matches.
  `(let ((--pcase-v-- ,expr))
     (cond ,@(mapcar (function pcase--clause) clauses)
           (t (error "No clause matching `%S'" --pcase-v--)))))
(defmacro pcase-let* (bindings &rest body)
  ;; Each binding is (PATTERN VALUE); destructure VALUE against PATTERN (reusing
  ;; `pcase--compile'), binding the pattern variables for BODY, in order.
  (let ((lets nil) (i 0))
    (dolist (b bindings)
      (let* ((tv (intern (concat "--pl-" (number-to-string i) "--")))
             (r (pcase--compile (car b) tv)))
        (setq lets (cons (list tv (car (cdr b))) lets))
        (dolist (bind (cdr r)) (setq lets (cons bind lets)))
        (setq i (1+ i))))
    `(let* ,(reverse lets) ,@body)))
;; pcase.el `pcase-let': every EXP is evaluated first (into a temporary unless
;; the pattern is a plain variable), then `pcase-let*' destructures them.
(defmacro pcase-let (bindings &rest body)
  (if (null (cdr bindings))
      `(pcase-let* ,bindings ,@body)
    (let ((matches '()))
      (dolist (binding (prog1 bindings (setq bindings nil)))
        (cond
         ((memq (car binding) '(t _ pcase--dontcare))
          (push (cons (make-symbol "_") (cdr binding)) bindings))
         ((and (symbolp (car binding)) (not (memq (car binding) '(t _ pcase--dontcare))))
          (push binding bindings))
         (t
          (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
            (push (cons tmpvar (cdr binding)) bindings)
            (push (list (car binding) tmpvar) matches)))))
      `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
(defmacro pcase-lambda (lambda-list &rest body)
  "A `lambda' whose parameters may be pcase PATTERNS instead of names.
Each pattern parameter becomes a fresh name that a `pcase-let*' destructures
around BODY, so `(funcall (pcase-lambda (`(,a ,b)) (+ a b)) (list 1 2))' is 3."
  (declare (doc-string 2) (indent defun))
  ;; As in pcase.el: a symbol (including `&optional'/`&rest') is an ordinary
  ;; parameter, anything else -- a `(\=` PAT)' form among them -- is a pattern.
  (let ((bindings nil) (parameters nil) (i 0))
    (dolist (pat lambda-list)
      (if (consp pat)
          (let ((arg (intern (concat "--pl-arg-" (number-to-string i) "--"))))
            (setq bindings (cons (list pat arg) bindings))
            (setq parameters (cons arg parameters)))
        (setq parameters (cons pat parameters)))
      (setq i (1+ i)))
    (list 'lambda (nreverse parameters)
          (cons 'pcase-let* (cons (nreverse bindings) body)))))
;; pcase.el `pcase-setq': pairs after the first become a `progn' of single
;; `pcase-setq's; a trivial pattern is a plain `setq'; otherwise each pattern
;; variable is `setq' to its value, the last assignment being the value.
(defconst pcase--dontcare-upats '(t _ pcase--dontcare))
(defun pcase--trivial-upat-p (upat)
  (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
(defmacro pcase-setq (pat val &rest args)
  (cond
   (args
    (let ((arg-length (length args)))
      (unless (evenp arg-length)
        (signal 'wrong-number-of-arguments
                (list 'pcase-setq (+ 2 arg-length)))))
    (let ((result))
      (while args
        (push `(pcase-setq ,(pop args) ,(pop args))
              result))
      `(progn
         (pcase-setq ,pat ,val)
         ,@(nreverse result))))
   ((pcase--trivial-upat-p pat)
    `(setq ,pat ,val))
   (t
    (let* ((tv (make-symbol "x"))
           (r (pcase--compile pat tv)))
      `(let ((,tv ,val))
         ,@(mapcar (lambda (b) (list 'setq (car b) (car (cdr b)))) (cdr r)))))))
(defmacro pcase-dolist (spec &rest body)
  ;; Iterate (cadr SPEC), destructuring each element against (car SPEC).
  (let ((ev (make-symbol "e")))
    (list 'dolist (list ev (car (cdr spec)))
          (cons 'pcase-let (cons (list (list (car spec) ev)) body)))))
;; help.el:2302 — defined here (after `pcase') because its body uses `pcase' and
;; elisprs expands macros when the `defun' is read, not when it is called.
(defun help-split-fundoc (docstring def &optional section)
  "Split a function DOCSTRING into the actual doc and the usage info.
Return (USAGE . DOC), where USAGE is a string describing the argument
list of DEF, such as \"(apply FUNCTION &rest ARGUMENTS)\".
DEF is the function whose usage we're looking for in DOCSTRING.
With SECTION nil, return nil if there is no usage info; conversely,
SECTION t means to return (USAGE . DOC) even if there's no usage info.
When SECTION is \\='usage or \\='doc, return only that part."
  (let* ((found (and docstring
                     (string-match "\n\n(fn\\(\\( .*\\)?)\\)\\'" docstring)))
         (doc (if found
                  (and (memq section '(t nil doc))
                       (not (zerop (match-beginning 0)))
                       (substring docstring 0 (match-beginning 0)))
                docstring))
         (usage (and found
                     (memq section '(t nil usage))
                     (let ((tail (match-string 1 docstring)))
                       (format "(%s%s"
                               (if (and (symbolp def) def)
                                   (help--docstring-quote (format "%S" def))
                                 'anonymous)
                               tail)))))
    (pcase section
      (`nil (and usage (cons usage doc)))
      (`t (cons usage doc))
      (`usage usage)
      (`doc doc))))
(defmacro seq-doseq (spec &rest body)
  (declare (indent 1) (debug ((symbolp form &optional form) body)))
  ;; (seq-doseq (VAR SEQUENCE) BODY...) — iterate VAR over any sequence's
  ;; elements. Returns the sequence (like Emacs, via seq-do).
  (let ((var (car spec)) (seq (car (cdr spec))) (sv (make-symbol "seq")))
    `(let* ((,sv ,seq) (--seq-doseq-tail-- (append ,sv nil)) (,var nil))
       (while --seq-doseq-tail--
         (setq ,var (car --seq-doseq-tail--))
         ,@body
         (setq --seq-doseq-tail-- (cdr --seq-doseq-tail--)))
       ,sv)))
;; seq.el: `seq-let' and `seq-setq' are `pcase-let' / `pcase-setq' over the
;; `seq' pattern `seq--make-pcase-patterns' builds from ARGS.
(defun seq--elt-safe (sequence n)
  (ignore-errors (seq-elt sequence n)))
(defun seq--make-pcase-bindings (args)
  (let ((bindings '())
        (index 0)
        (rest-marker nil))
    (seq-doseq (name args)
      (unless rest-marker
        (if (eq name '&rest)
            (progn (push `(app (seq-drop _ ,index)
                               ,(seq--elt-safe args (1+ index)))
                         bindings)
                   (setq rest-marker t))
          (push `(app (seq--elt-safe _ ,index) ,name) bindings)))
      (setq index (1+ index)))
    bindings))
(defun seq--make-pcase-patterns (args)
  (cons 'seq
        (seq-map (lambda (elt)
                   (if (seqp elt)
                       (seq--make-pcase-patterns elt)
                     elt))
                 args)))
(defmacro seq-let (args sequence &rest body)
  (declare (indent 2) (debug (sexp form body)))
  `(pcase-let ((,(seq--make-pcase-patterns args) ,sequence))
     ,@body))
(defmacro seq-setq (args sequence)
  `(pcase-setq ,(seq--make-pcase-patterns args) ,sequence))

;; macroexp-unprogn / macroexp-let* / macroexp-let2 (macroexp.el:560,565,601).
;; `macroexp-let2' evaluates BODY with SYM bound to an expression for EXP: if
;; EXP is copyable per TEST, SYM is EXP itself; else SYM is a fresh symbol and
;; the result wraps a `let*' that evaluates EXP once.  gv's place-expanders use
;; it to guarantee each place subform is evaluated exactly once.
(defun macroexp-unprogn (exp)
  (if (eq (car-safe exp) 'progn) (or (cdr exp) '(nil)) (list exp)))
(defun macroexp-let* (bindings exp)
  (cond ((null bindings) exp)
        ((eq 'let* (car-safe exp))
         (append (list 'let* (append bindings (car (cdr exp)))) (cdr (cdr exp))))
        (t (list 'let* bindings exp))))
;; The final test is `eql', where macroexp.el has `eq': a float is an immediate
;; here with no object identity, so `(eq 1.5 1.5)' on the SAME value is nil and
;; a copyable float EXP would be bound as a variable named `1.5'. `eql' answers
;; the same for every other value (SYM is either EXP itself or a fresh symbol).
(defmacro macroexp-let2 (test sym exp &rest body)
  (declare (indent 3))
  (let ((bodysym (make-symbol "body"))
        (expsym (make-symbol "exp")))
    `(let* ((,expsym ,exp)
            (,sym (if (funcall #',(or test 'macroexp-const-p) ,expsym)
                      ,expsym (make-symbol ,(symbol-name sym))))
            (,bodysym ,(macroexp-progn body)))
       (if (eql ,sym ,expsym) ,bodysym
         (macroexp-let* (list (list ,sym ,expsym)) ,bodysym)))))
;; macroexp-small-p (macroexp.el:678): is EXP small enough to duplicate?  gv's
;; `if'/`cond' expanders consult it (after `lexical-binding') to decide between
;; duplicating the DO code into each branch and building a runtime closure pair.
(defun macroexp--maxsize (exp size)
  (cond ((< size 0) size)
        ((symbolp exp) (1- size))
        ((stringp exp) (- size (/ (length exp) 16)))
        ((vectorp exp)
         (dotimes (i (length exp))
           (setq size (macroexp--maxsize (aref exp i) size)))
         (1- size))
        ((consp exp)
         (dolist (e exp)
           (setq size (macroexp--maxsize e size)))
         (1- size))
        (t -1)))
(defun macroexp-small-p (exp)
  (> (macroexp--maxsize exp 10) 0))

;;; ---- gv.el: generalized-variable place expanders ----
;; Faithful port of emacs-lisp/gv.el's higher-order place model.  A place-
;; expander is a function (do -> code) where DO is (getter setter -> code); it is
;; stored on the head symbol's `gv-expander' property (gv.el:71).  `gv-get' turns
;; a PLACE form into that call, `gv-letplace' is its macro sugar, `gv-ref'/
;; `gv-deref' build first-class references, and `setf' (via `setf--expand's'
;; fallback) consults this registry for any place its own cond does not handle.
(define-error 'gv-invalid-place "Invalid place expression")

(defun gv-get (place do)
  "Build the code that applies DO to PLACE (gv.el:80)."
  (cond
   ((symbolp place)
    (let ((me (macroexpand-1 place)))
      (if (eq me place)
          (funcall do place (lambda (v) (list 'setq place v)))
        (gv-get me do))))
   ((not (consp place)) (signal 'gv-invalid-place (list place)))
   (t
    (let* ((head (car place))
           (gf (function-get head 'gv-expander 'autoload)))
      (if gf (apply gf do (cdr place))
        (let ((me (macroexpand-1 place)))
          (if (and (eq me place) (get head 'compiler-macro))
              (setq me (apply (get head 'compiler-macro) place (cdr place))))
          (if (and (eq me place) (fboundp head)
                   (symbolp (symbol-function head)))
              (setq me (cons (symbol-function head) (cdr place))))
          (if (eq me place)
              (if (and (symbolp head) (get head 'setf-method))
                  (error "Incompatible place needs recompilation: %S" head)
                (let ((setter (gv-setter head)))
                  (gv--defsetter head (lambda (&rest args) (cons setter args))
                                 do (cdr place))))
            (gv-get me do))))))))

(defmacro gv-letplace (vars place &rest body)
  "Build the code manipulating the generalized variable PLACE (gv.el:133)."
  (declare (indent 2))
  `(gv-get ,place (lambda ,vars ,@body)))

(defmacro gv-define-expander (name handler)
  "Use HANDLER to handle NAME as a generalized var (gv.el:150)."
  (declare (indent 1))
  `(function-put ',name 'gv-expander ,handler))

(defun gv--defsetter (name setter do args &optional vars)
  "Helper used by code generated by `gv-define-setter' (gv.el:227)."
  (if (null args)
      (let ((vars (nreverse vars)))
        (funcall do (cons name vars) (lambda (v) (apply setter v vars))))
    (macroexp-let2 nil v (car args)
      (gv--defsetter name setter do (cdr args) (cons v vars)))))

(defmacro gv-define-setter (name arglist &rest body)
  "Define a setter method for generalized variable NAME (gv.el:242)."
  (declare (indent 2))
  `(gv-define-expander ,name
     (lambda (do &rest args)
       (gv--defsetter ',name (lambda ,arglist ,@body) do args))))

(defmacro gv-define-simple-setter (name setter &optional fix-return)
  "Define a simple setter method for generalized variable NAME (gv.el:262).
Assignments of VAL to (NAME ARGS...) become (SETTER ARGS... VAL)."
  `(gv-define-setter ,name (val &rest args)
     ,(if fix-return
          `(macroexp-let2 nil v val
             `(progn
                (,',setter ,@args ,v)
                ,v))
        ``(,',setter ,@args ,val))))

;;; The common generalized variables (gv.el:348).
(gv-define-simple-setter aref aset)
(gv-define-simple-setter char-table-range set-char-table-range)
(gv-define-simple-setter car setcar)
(gv-define-simple-setter cdr setcdr)
(gv-define-setter caar (val x) `(setcar (car ,x) ,val))
(gv-define-setter cadr (val x) `(setcar (cdr ,x) ,val))
(gv-define-setter cdar (val x) `(setcdr (car ,x) ,val))
(gv-define-setter cddr (val x) `(setcdr (cdr ,x) ,val))
(gv-define-setter elt (store seq n)
  `(if (listp ,seq) (setcar (nthcdr ,n ,seq) ,store)
     (aset ,seq ,n ,store)))
(gv-define-simple-setter get put)
(gv-define-setter gethash (val k h &optional _d) `(puthash ,k ,val ,h))
(put 'nth 'gv-expander
     (lambda (do idx list)
       (macroexp-let2 nil c `(nthcdr ,idx ,list)
         (funcall do `(car ,c) (lambda (v) `(setcar ,c ,v))))))
(gv-define-simple-setter symbol-function fset)
(gv-define-simple-setter symbol-plist setplist)
(gv-define-simple-setter symbol-value set)
(put 'nthcdr 'gv-expander
     (lambda (do n place)
       (macroexp-let2 nil idx n
         (gv-letplace (getter setter) place
           (funcall do `(nthcdr ,idx ,getter)
                    (lambda (v) `(if (<= ,idx 0) ,(funcall setter v)
                              (setcdr (nthcdr (1- ,idx) ,getter) ,v))))))))
(gv-define-simple-setter default-value set-default)

;;; Control-flow and "occasionally handy" place expanders (gv.el:459).  These
;; show up as the output of macroexpanding real places (e.g. struct accessors)
;; and, in nadvice, as literal `(gv-ref (cond ...))'.  Since elisprs's
;; `lexical-binding' is nil, the `(not lexical-binding)' branch always fires:
;; the DO code is duplicated into each branch rather than closed over at runtime.
(put 'progn 'gv-expander
     (lambda (do &rest exps)
       (let ((start (butlast exps))
             (end (car (last exps))))
         (if (null start) (gv-get end do)
           `(progn ,@start ,(gv-get end do))))))
(let ((let-expander
       (lambda (letsym)
         (lambda (do bindings &rest body)
           `(,letsym ,bindings
                     ,@(macroexp-unprogn
                        (gv-get (macroexp-progn body) do)))))))
  (put 'let 'gv-expander (funcall let-expander 'let))
  (put 'let* 'gv-expander (funcall let-expander 'let*)))
(put 'if 'gv-expander
     (lambda (do test then &rest else)
       (if (or (not lexical-binding)
               (macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy))))
           `(if ,test ,(gv-get then do)
              ,@(macroexp-unprogn (gv-get (macroexp-progn else) do)))
         (let ((v (gensym "v")))
           (macroexp-let2 nil
               gv `(if ,test ,(gv-letplace (getter setter) then
                                `(cons (lambda () ,getter)
                                       (lambda (,v) ,(funcall setter v))))
                     ,(gv-letplace (getter setter) (macroexp-progn else)
                        `(cons (lambda () ,getter)
                               (lambda (,v) ,(funcall setter v)))))
             (funcall do `(funcall (car ,gv))
                      (lambda (v) `(funcall (cdr ,gv) ,v))))))))
(put 'cond 'gv-expander
     (lambda (do &rest branches)
       (if (or (not lexical-binding)
               (macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy))))
           `(cond
             ,@(mapcar (lambda (branch)
                         (if (cdr branch)
                             (cons (car branch)
                                   (macroexp-unprogn
                                    (gv-get (macroexp-progn (cdr branch)) do)))
                           (gv-get (car branch) do)))
                       branches))
         (let ((v (gensym "v")))
           (macroexp-let2 nil
               gv `(cond
                    ,@(mapcar
                       (lambda (branch)
                         (if (cdr branch)
                             `(,(car branch)
                               ,@(macroexp-unprogn
                                  (gv-letplace (getter setter)
                                      (macroexp-progn (cdr branch))
                                    `(cons (lambda () ,getter)
                                           (lambda (,v) ,(funcall setter v))))))
                           (gv-letplace (getter setter)
                               (car branch)
                             `(cons (lambda () ,getter)
                                    (lambda (,v) ,(funcall setter v))))))
                       branches))
             (funcall do `(funcall (car ,gv))
                      (lambda (v) `(funcall (cdr ,gv) ,v))))))))
(put 'cons 'gv-expander
     (lambda (do a d)
       (gv-letplace (agetter asetter) a
         (gv-letplace (dgetter dsetter) d
           (funcall do
                    `(cons ,agetter ,dgetter)
                    (lambda (v)
                      (macroexp-let2 nil v v
                        `(progn
                           ,(funcall asetter `(car ,v))
                           ,(funcall dsetter `(cdr ,v))
                           ,v))))))))
(put 'logand 'gv-expander
     (lambda (do place &rest masks)
       (gv-letplace (getter setter) place
         (macroexp-let2 macroexp-copyable-p
             mask (if (cdr masks) `(logand ,@masks) (car masks))
           (funcall
            do `(logand ,getter ,mask)
            (lambda (v)
              (macroexp-let2 nil v v
                `(progn
                   ,(funcall setter
                             `(logior (logand ,v ,mask)
                                      (logand ,getter (lognot ,mask))))
                   ,v))))))))
;; (setf (error ...) ..) appears naturally from macroexpanding places like
;; (setf (pcase-exhaustive ...)) (gv.el:646).
(gv-define-expander error (lambda (_do &rest args) `(error . ,args)))

;;; References (gv.el:597).
(defmacro gv-ref (place)
  "Return a reference to PLACE (gv.el:600).
This is like the `&' operator of the C language."
  (gv-letplace (getter setter) place
    `(cons (lambda () ,getter)
           (lambda (gv--val) ,(funcall setter 'gv--val)))))
(defsubst gv-deref (ref)
  "Dereference REF, returning the referenced value (gv.el:621)."
  (funcall (car ref)))
(gv-define-setter gv-deref (v ref) `(funcall (cdr ,ref) ,v))

;; (setf (eq a 7) B) means (setq a 7) or (setq a nil) per B's truthiness — used
;; by define-minor-mode's :variable (gv.el:813).
(gv-define-expander eq
  (lambda (do place val)
    (gv-letplace (getter setter) place
      (macroexp-let2 nil val val
        (funcall do `(eq ,getter ,val)
                 (lambda (v)
                   `(cond
                     (,v ,(funcall setter val))
                     ((eq ,getter ,val) ,(funcall setter `(not ,val))))))))))


(defun hash-table-empty-p (h) (= 0 (hash-table-count h)))
;; Emacs 30 dropped the per-table rehash parameters from `struct
;; Lisp_Hash_Table'; both accessors survive and answer the same constant for
;; every table (measured on GNU Emacs 30.2: 1.5 and 0.8125, for a default table
;; and for `:size 99' alike).
(defun hash-table-rehash-size (_table) 1.5)
(defun hash-table-rehash-threshold (_table) 0.8125)



;;; ---- Customize declaration machinery (custom.el / cus-face.el) ----
;; Faithful port of the DECLARATION half of custom.el: `defgroup', `defcustom',
;; `defface' and the `custom-declare-*' functions they expand into, storing the
;; same observable symbol properties real Emacs stores at declaration time
;; (standard-value, custom-type, custom-requests, custom-group,
;; group-documentation, face-defface-spec, ...). This lets libraries that
;; declare options (sort.el, ansi-color.el, ...) load. The Customize *UI*
;; (widget.el, cus-edit.el, `custom-set-variables' persistence) and live face
;; objects/frames are out of scope; where a facet needs them the boundary is
;; named below.
;;
;; `lexical-binding' is nil while the prelude loads; `load' binds it to each
;; file's cookie (`file_lexical_cookie' in src/host.rs), and `*scratch*' has it
;; t from `lisp-interaction-mode'.  The `defcustom' macro branches on it to
;; decide how STANDARD is stashed: nil quotes it, so `standard-value' is
;; (DEFAULT); t wraps it in `(funcall #'(lambda () DEFAULT))', as in Emacs.
(defvar lexical-binding nil)
(defvar purify-flag nil)
(defvar custom-define-hook nil)          ; custom.el:38
(defvar custom-dont-initialize nil)      ; custom.el:42
(defvar custom-current-group-alist nil)  ; custom.el:47
;; C `current-load-list' (lread.c): `load' accumulates definitions on it. A
;; plain global is enough for `custom-declare-face' to push onto here.
(defvar current-load-list nil)

;; custom.el:52 — set SYMBOL to EXP only if it has no default binding yet.
(defun custom-initialize-default (symbol exp)
  (condition-case nil
      (default-toplevel-value symbol)
    (void-variable
     (set-default-toplevel-value
      symbol (eval (let ((sv (get symbol 'saved-value)))
                     (if sv (car sv) exp))
                   t)))))

;; custom.el:68
(defun custom-initialize-set (symbol exp)
  (condition-case nil
      (default-toplevel-value symbol)
    (error
     (funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
              symbol
              (eval (let ((sv (get symbol 'saved-value)))
                      (if sv (car sv) exp)))))))

;; custom.el:84 — the default `:initialize' every plain `defcustom' uses.
(defun custom-initialize-reset (symbol exp)
  ;; The `custom-check-value'/widget branch only fires for options previously
  ;; set via `setopt'; it never runs at declaration (custom-check-value is nil),
  ;; so `widget-convert'/`widget-apply' — part of the out-of-scope widget UI —
  ;; are never called here.
  (let ((value (get symbol 'custom-check-value)))
    (when value
      (let ((type (get symbol 'custom-type)))
        (when (and type
                   (boundp symbol)
                   (eq (car value) (symbol-value symbol))
                   (not (widget-apply (widget-convert type)
                                      :match (car value))))
          (warn "Value `%S' for `%s' does not match type %s"
                value symbol type)))))
  (funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
           symbol
           (condition-case nil
               (let ((def (default-toplevel-value symbol))
                     (getter (get symbol 'custom-get)))
                 (if getter (funcall getter symbol) def))
             (error
              (eval (let ((sv (get symbol 'saved-value)))
                      (if sv (car sv) exp)))))))

;; custom.el:117
(defun custom-initialize-changed (symbol exp)
  (condition-case nil
      (let ((def (default-toplevel-value symbol)))
        (funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
                 symbol
                 (let ((getter (get symbol 'custom-get)))
                   (if getter (funcall getter symbol) def))))
    (error
     (cond
      ((get symbol 'saved-value)
       (funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
                symbol
                (eval (car (get symbol 'saved-value)))))
      (t
       (set-default-toplevel-value symbol (eval exp)))))))

;; custom.el:137
(defvar custom-delayed-init-variables nil
  "List of variables whose initialization is pending until startup.
Once this list has been processed, this var is set to a non-list value.")

;; custom.el:141
(defun custom-initialize-delay (symbol value)
  "Delay initialization of SYMBOL to the next Emacs start.
This is used in files that are preloaded (or for autoloaded
variables), so that the initialization is done in the run-time
context rather than the build-time context."
  ;; Defvar it so as to mark it special, etc (bug#25770).
  (internal--define-uninitialized-variable symbol)
  ;; Until the var is actually initialized, it is kept unbound.
  (if (listp custom-delayed-init-variables)
      (push symbol custom-delayed-init-variables)
    ;; In case this is called after startup, there is no "later" to which to
    ;; delay it, so initialize it "normally" (bug#47072).
    (custom-initialize-reset symbol value)))

;; eval.c `internal--define-uninitialized-variable': mark SYMBOL special
;; (dynamically bound) for good and record DOC, without touching its value.
(defun internal--define-uninitialized-variable (symbol &optional doc)
  (--declare-special symbol)
  (when doc (put symbol 'variable-documentation doc))
  nil)

;; custom.el:479
(defun custom-current-group ()
  (cdr (assoc load-file-name custom-current-group-alist)))

;; custom.el:545
(defun custom-add-to-group (group option widget)
  (let ((members (get group 'custom-group))
        (entry (list option widget)))
    (unless (member entry members)
      (put group 'custom-group (nconc members (list entry))))))

;; custom.el:626
(defun custom-add-option (symbol option)
  (let ((options (get symbol 'custom-options)))
    (unless (member option options)
      (put symbol 'custom-options (cons option options)))))

;; custom.el:652
(defun custom-add-load (symbol load)
  (let ((loads (get symbol 'custom-loads)))
    (unless (member load loads)
      (put symbol 'custom-loads (cons (purecopy load) loads)))))

;; custom.el:659
(defun custom-autoload (symbol load &optional noset)
  "Mark SYMBOL as autoloaded custom variable and add dependency LOAD.
If NOSET is non-nil, don't bother autoloading LOAD when setting the variable."
  (put symbol 'custom-autoload (if noset 'noset t))
  (custom-add-load symbol load))

;; custom.el:638
(defun custom-add-link (symbol widget)
  (let ((links (get symbol 'custom-links)))
    (unless (member widget links)
      (put symbol 'custom-links (cons (purecopy widget) links)))))

;; custom.el:644
(defun custom-add-version (symbol version)
  (put symbol 'custom-version (purecopy version)))

;; custom.el:648
(defun custom-add-package-version (symbol version)
  (put symbol 'custom-package-version (purecopy version)))

;; custom.el:607
(defun custom-add-dependencies (symbol value)
  (unless (listp value)
    (error "Invalid custom dependency `%s'" value))
  (let* ((deps (get symbol 'custom-dependencies))
         (new-deps deps))
    (while value
      (let ((dep (car value)))
        (unless (symbolp dep)
          (error "Invalid custom dependency `%s'" dep))
        (unless (memq dep new-deps)
          (setq new-deps (cons dep new-deps)))
        (setq value (cdr value))))
    (unless (eq deps new-deps)
      (put symbol 'custom-dependencies new-deps))))

;; custom.el:585
(defun custom-handle-keyword (symbol keyword value type)
  (if purify-flag
      (setq value (purecopy value)))
  (cond ((eq keyword :group)
         (custom-add-to-group value symbol type))
        ((eq keyword :version)
         (custom-add-version symbol value))
        ((eq keyword :package-version)
         (custom-add-package-version symbol value))
        ((eq keyword :link)
         (custom-add-link symbol value))
        ((eq keyword :load)
         (custom-add-load symbol value))
        ((eq keyword :tag)
         (put symbol 'custom-tag value))
        ((eq keyword :set-after)
         (custom-add-dependencies symbol value))
        (t
         (error "Unknown keyword %s" keyword))))

;; custom.el:566
(defun custom-handle-all-keywords (symbol args type)
  (unless (memq :group args)
    (let ((cg (custom-current-group)))
      (when cg
        (custom-add-to-group cg symbol type))))
  (while args
    (let ((arg (car args)))
      (setq args (cdr args))
      (unless (symbolp arg)
        (error "Junk in args %S" args))
      (let ((keyword arg)
            (value (car args)))
        (unless args
          (error "Keyword %s is missing an argument" keyword))
        (setq args (cdr args))
        (custom-handle-keyword symbol keyword value type)))))

;; custom.el:161
(defun custom-declare-variable (symbol default doc &rest args)
  (put symbol 'standard-value (purecopy (list default)))
  (when (get symbol 'force-value)
    (put symbol 'force-value nil))
  (if (keywordp doc)
      (error "Doc string is missing"))
  (let ((initialize #'custom-initialize-reset)
        (requests nil)
        buffer-local)
    (unless (memq :group args)
      (let ((cg (custom-current-group)))
        (when cg
          (custom-add-to-group cg symbol 'custom-variable))))
    (while args
      (let ((keyword (pop args)))
        (unless (symbolp keyword)
          (error "Junk in args %S" args))
        (unless args
          (error "Keyword %s is missing an argument" keyword))
        (let ((value (pop args)))
          (cond ((eq keyword :initialize)
                 (setq initialize value))
                ((eq keyword :set)
                 (put symbol 'custom-set value))
                ((eq keyword :get)
                 (put symbol 'custom-get value))
                ((eq keyword :require)
                 (push value requests))
                ((eq keyword :risky)
                 (put symbol 'risky-local-variable value))
                ((eq keyword :safe)
                 (put symbol 'safe-local-variable value))
                ((eq keyword :local)
                 (when (memq value '(t permanent))
                   (setq buffer-local t))
                 (when (eq value 'permanent)
                   (put symbol 'permanent-local t)))
                ((eq keyword :type)
                 (put symbol 'custom-type (purecopy value)))
                ((eq keyword :options)
                 (if (get symbol 'custom-options)
                     (mapc (lambda (option)
                             (custom-add-option symbol option))
                           value)
                   (put symbol 'custom-options (copy-sequence value))))
                (t
                 (custom-handle-keyword symbol keyword value
                                        'custom-variable))))))
    (internal--define-uninitialized-variable symbol doc)
    (put symbol 'custom-requests requests)
    (unless custom-dont-initialize
      (funcall initialize symbol default)
      (let ((theme (caar (get symbol 'theme-value))))
        (when (and theme (not (eq theme 'user)) (get symbol 'saved-value))
          (put symbol 'saved-value nil))))
    (when buffer-local
      (make-variable-buffer-local symbol)))
  (run-hooks 'custom-define-hook)
  symbol)

;; custom.el:482
(defun custom-declare-group (symbol members doc &rest args)
  (while members
    (apply #'custom-add-to-group symbol (car members))
    (setq members (cdr members)))
  (when doc
    (put symbol 'group-documentation (purecopy doc)))
  (while args
    (let ((arg (car args)))
      (setq args (cdr args))
      (unless (symbolp arg)
        (error "Junk in args %S" args))
      (let ((keyword arg)
            (value (car args)))
        (unless args
          (error "Keyword %s is missing an argument" keyword))
        (setq args (cdr args))
        (cond ((eq keyword :prefix)
               (put symbol 'custom-prefix (purecopy value)))
              (t
               (custom-handle-keyword symbol keyword value
                                      'custom-group))))))
  (let ((elt (assoc load-file-name custom-current-group-alist)))
    (if elt (setcdr elt symbol)
      (push (cons load-file-name symbol) custom-current-group-alist)))
  (run-hooks 'custom-define-hook)
  symbol)

;; C subr: t if OBJECT can serve as a documentation string — a string, an
;; integer DOC-file offset, or a (string . offset) cons.
(defun documentation-stringp (object)
  (or (stringp object)
      (integerp object)
      (and (consp object) (stringp (car object)) (integerp (cdr object)))))

;; faces.el:647
(defun face-documentation (face)
  "Get the documentation string for FACE.
If FACE is a face-alias, get the documentation for the target face."
  (let ((alias (get face 'face-alias)))
    (if alias
        (let ((doc (documentation-property alias 'face-documentation)))
	  (format "%s is an alias for the face `%s'.%s" face alias
                  (if doc (format "\n%s" doc)
                    "")))
      (documentation-property face 'face-documentation))))

;; faces.el:662
(defun set-face-documentation (face string)
  (put face 'face-documentation (purecopy string)))

;; faces.el:1685 — declaration-scope port: store the face spec under the
;; requested property (this is the observable half). BOUNDARY: real
;; `face-spec-set' then calls `make-empty-face' and recalculates the face on
;; every frame (`face-spec-recalc'). elisprs has no display subsystem — no face
;; objects, no frames — so those are omitted; no face object is created.
;; xfaces.c — the frame-independent face table.  Batch Emacs keeps every
;; face's global attribute vector all-`unspecified' (attributes are
;; realized per frame from the specs), so that is what is modelled.

(defvar face--new-frame-defaults (make-hash-table :test 'eq)
  "Hash table of global face definitions (for internal use only.)")

(defun editfns--resolve-face-name (face)
  "resolve_face_name: a string names the interned symbol; aliases are followed."
  (when (stringp face)
    (setq face (intern face)))
  (let ((depth 0))
    (while (and (symbolp face) (get face 'face-alias) (< depth 10))
      (setq face (get face 'face-alias) depth (1+ depth))))
  face)

(defun internal-make-lisp-face (face &optional frame)
  "Make FACE, a symbol, a Lisp face with all attributes unspecified.
If FACE was not known as a face before, create a new one.
If optional argument FRAME is specified, make a frame-local face
for that frame.  Otherwise operate on the global face definition.
Value is a vector of face attributes."
  (ignore frame)
  (unless (symbolp face)
    (signal 'wrong-type-argument (list 'symbolp face)))
  (let ((entry (gethash face face--new-frame-defaults)))
    (if entry
        (cdr entry)
      (let ((vec (make-vector 20 'unspecified)))
        (aset vec 0 'face)
        (puthash face (cons (hash-table-count face--new-frame-defaults) vec)
                 face--new-frame-defaults)
        vec))))

(defun internal-lisp-face-p (face &optional frame)
  "Return non-nil if FACE names a face.
FACE should be a symbol or string.
If optional second argument FRAME is non-nil, check for the
existence of a frame-local face with name FACE on that frame.
Otherwise check for the existence of a global face."
  (ignore frame)
  (setq face (editfns--resolve-face-name face))
  (and (symbolp face)
       (cdr (gethash face face--new-frame-defaults))))

(defun make-face-x-resource-internal (face &optional frame)
  "Make FACE a face with the attributes X resources give it.
There are no X resources without a window system, so this does nothing."
  (ignore face frame)
  nil)

(defun face-font (face &optional frame character)
  "Return the font name of face FACE, or nil if it is unspecified.
On the terminal frame of batch Emacs every realized face has the font
\"tty\"; with FRAME t the global face's bold and italic attributes are
consulted, which batch Emacs leaves unspecified."
  (ignore character)
  (if (eq frame t)
      nil
    (unless (facep face)
      (signal 'error (list "Invalid face" face)))
    "tty"))
;; faces.el (Emacs 31.1), verbatim.
(defun face-list ()
  "Return a list of all defined faces."
  (let (faces)
    (maphash (lambda (face spec)
               (push `(,(car spec) . ,face) faces))
             face--new-frame-defaults)
    (mapcar #'cdr (sort faces (lambda (f1 f2) (> (car f1) (car f2)))))))

(defun make-face (face)
  "Define a new face with name FACE, a symbol.
Do not call this directly from Lisp code; use `defface' instead.

If FACE is already known as a face, leave it unmodified.  Return FACE."
  (interactive (list (read-from-minibuffer
		      "Make face: " nil nil t 'face-name-history)))
  (unless (facep face)
    ;; Make frame-local faces (this also makes the global one).
    (dolist (frame (frame-list))
      (internal-make-lisp-face face frame))
    ;; Add the face to the face menu.
    (when (fboundp 'facemenu-add-new-face)
      (facemenu-add-new-face face))
    ;; Define frame-local faces for all frames from X resources.
    (make-face-x-resource-internal face))
  face)

(defun make-empty-face (face)
  "Define a new, empty face with name FACE.
Do not call this directly from Lisp code; use `defface' instead."
  (interactive (list (read-from-minibuffer
		      "Make empty face: " nil nil t 'face-name-history)))
  (make-face face))

(defun facep (face)
  "Return non-nil if FACE is a face name; nil otherwise.
A face name can be a string or a symbol."
  (internal-lisp-face-p face))


(defun face-spec-set (face spec &optional spec-type)
  (if (get face 'face-alias)
      (setq face (get face 'face-alias)))
  (unless spec-type
    (setq spec-type 'face-override-spec))
  (if (memq spec-type '(face-defface-spec face-override-spec
                        customized-face saved-face))
      (put face spec-type spec))
  (if (memq spec-type '(reset saved-face))
      (put face 'customized-face nil))
  (if (memq spec-type '(customized-face saved-face reset))
      (put face 'face-override-spec nil))
  (unless (eq face 'face-override-spec)
    (put face 'face-modified nil))
  ;; Initialize the face if it does not exist.  (Recalculating its
  ;; attributes per frame, `face-spec-recalc', is not modelled.)
  (make-empty-face face))

;; cus-face.el:32
(defun custom-declare-face (face spec doc &rest args)
  (when (and doc
             (not (documentation-stringp doc)))
    (error "Invalid (or missing) doc string %S" doc))
  (unless (get face 'face-defface-spec)
    (face-spec-set face (purecopy spec) 'face-defface-spec)
    (push (cons 'defface face) current-load-list)
    (when doc
      (set-face-documentation face (purecopy doc)))
    (custom-handle-all-keywords face args 'custom-face)
    (run-hooks 'custom-define-hook))
  face)

;; custom.el:512 — no backquote here, matching the upstream bootstrap note.
(defmacro defgroup (symbol members doc &rest args)
  (declare (doc-string 3) (indent defun))
  (nconc (list 'custom-declare-group (list 'quote symbol) members doc) args))

;; custom.el (Emacs 31.1; 30.2 put a "" docstring in the lambda)
(defmacro defcustom (symbol standard doc &rest args)
  (declare (doc-string 3) (debug (name body)) (indent defun))
  `(custom-declare-variable
    ',symbol
    ,(if lexical-binding
         ``(funcall #',(lambda () ,standard))
       `',standard)
    ,doc
    ,@args))

;; custom.el:409
(defmacro defface (face spec doc &rest args)
  (declare (doc-string 3) (indent defun))
  (nconc (list 'custom-declare-face (list 'quote face) spec doc) args))

;;; ---- password-prompt recognition data (international/mule-conf.el) ----
;; mule-conf.el is preloaded in Emacs, so these are always bound. Both are
;; fixed, build-independent i18n data lists — captured value-for-value from GNU
;; Emacs 30.2 mule-conf.el:1681/1739. Used by comint.el/shell.el and friends to
;; build `comint-password-prompt-regexp'. Placed after `defcustom' is defined.
;; mule-conf.el:1681
(defcustom password-word-equivalents
  '("password" "passcode" "passphrase" "pass phrase" "pin"
    "decryption key" "encryption key" ; From ccrypt.
    ; These are sorted according to the GNU en_US locale.
    "암호"		; ko
    "パスワード"	; ja
    "ପ୍ରବେଶ ସଙ୍କେତ"	; or
    "ពាក្យសម្ងាត់"		; km
    "adgangskode"	; da
    "contraseña"	; es
    "contrasenya"	; ca
    "geslo"		; sl
    "hasło"		; pl
    "heslo"		; cs, sk
    "iphasiwedi"	; zu
    "jelszó"		; hu
    "lösenord"		; sv
    "lozinka"		; hr, sr
    "mật khẩu"		; vi
    "mot de passe"	; fr
    "parola"		; tr
    "pasahitza"		; eu
    "passord"		; nb
    "passwort"		; de
    "pasvorto"		; eo
    "salasana"		; fi
    "senha"		; pt
    "slaptažodis"	; lt
    "wachtwoord"	; nl
    "كلمة السر"		; ar
    "ססמה"		; he
    "лозинка"		; sr
    "пароль"		; kk, ru, uk
    "गुप्तशब्द"		; mr
    "शब्दकूट"		; hi
    "પાસવર્ડ"		; gu
    "సంకేతపదము"		; te
    "ਪਾਸਵਰਡ"		; pa
    "ಗುಪ್ತಪದ"		; kn
    "கடவுச்சொல்"		; ta
    "അടയാളവാക്ക്"		; ml
    "গুপ্তশব্দ"		; as
    "পাসওয়ার্ড"		; bn_IN
    "රහස්පදය"		; si
    "密码"		; zh_CN
    "密碼"		; zh_TW
    )
  "List of words equivalent to \"password\".
This is used by Shell mode and other parts of Emacs to recognize
password prompts, including prompts in languages other than
English.  Different case choices should not be assumed to be
included; callers should bind `case-fold-search' to t."
  :type '(repeat string)
  :version "27.1"
  :group 'processes)
;; mule-conf.el:1739
(defcustom password-colon-equivalents
  '(?: ; ?\N{COLON}
    ?: ; ?\N{FULLWIDTH COLON}
    ?﹕ ; ?\N{SMALL COLON}
    ?︓ ; ?\N{PRESENTATION FORM FOR VERTICAL COLON}
    ?៖ ; ?\N{KHMER SIGN CAMNUC PII KUUH}
    )
  "List of characters equivalent to trailing colon in \"password\" prompts."
  :type '(repeat character)
  :version "30.1"
  :group 'processes)

;;; ---- files.el pure-data regexps ----
;; files.el:1180 `locate-dominating-stop-dir-regexp': a plain `defvar' whose
;; value is a fixed, build-independent regexp string (purecopy'd in the C tree).
;; Read by `locate-dominating-file' to decide which directory names terminate an
;; upward search. Ported value-for-value from GNU Emacs 30.2 files.el.
(defvar locate-dominating-stop-dir-regexp
  (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
  "Regexp of directory names that stop the search in `locate-dominating-file'.
Any directory whose name matches this regexp will be treated like
a kind of root directory by `locate-dominating-file', which will stop its
search when it bumps into it.
The default regexp prevents fruitless and time-consuming attempts to find
special files in directories in which file names are interpreted as host names,
or mount points potentially requiring authentication as a different user.")
;; files.el:1722 `mounted-file-systems': a `defcustom' regexp. The standard
;; value is platform-conditional; the `if' is kept intact so the value is
;; correct on any `system-type' (Windows/Cygwin get "^//[^/]+/", the rest get
;; the regexp-opt-precomputed alternation). Ported value-for-value; oracle on
;; darwin yields the else branch. `:require 'regexp-opt' is honored by
;; `custom-declare-variable' (pushed onto its requests list).
(defcustom mounted-file-systems
  (if (memq system-type '(windows-nt cygwin))
      "^//[^/]+/"
    "^\\(?:/\\(?:afs/\\|m\\(?:edia/\\|nt\\)\\|\\(?:ne\\|tmp_mn\\)t/\\)\\)")
  "File systems that ought to be mounted."
  :group 'files
  :version "26.1"
  :require 'regexp-opt
  :type 'regexp)

;;; ---- per-user Emacs file location (files.el / startup.el) ----
;; startup.el:597 sets `user-emacs-directory' at startup; the defvar itself is
;; nil ("The value does not matter since Emacs sets this at startup").  elisprs
;; does not run the C/startup init path, so we seed the documented runtime value
;; "~/.emacs.d/" -- oracle-confirmed against emacs -Q --batch (30.2).
;; startup.el
(defvar init-file-user nil
  "Identity of user whose init file is or was read.")
;; startup.el (effective runtime value; Emacs sets this at startup)
(defvar user-emacs-directory "~/.emacs.d/"
  "Directory beneath which additional per-user Emacs-specific files are placed.")
;; emacs.c C variable (nil outside the dump/pdump build path)
(defvar dump-mode nil
  "Non-nil means Emacs is dumping or bootstrapping.")
;; files.el
(defcustom user-emacs-directory-warning t
  "Non-nil means warn if unable to access or create `user-emacs-directory'."
  :type 'boolean
  :group 'initialization
  :version "24.4")

;; files.el: faithful port of `locate-user-emacs-file'.
(defun locate-user-emacs-file (new-name &optional old-name)
  "Return an absolute per-user Emacs-specific file name.
If NEW-NAME exists in `user-emacs-directory', return it.
Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
Else return NEW-NAME in `user-emacs-directory', creating the
directory if it does not exist."
  (convert-standard-filename
   (let* ((home (concat "~" (or init-file-user "")))
	  (at-home (and old-name (expand-file-name old-name home)))
          (bestname (abbreviate-file-name
                     (expand-file-name new-name user-emacs-directory))))
     (if (and at-home (not (file-readable-p bestname))
              (file-readable-p at-home))
	 at-home
       ;; Make sure `user-emacs-directory' exists,
       ;; unless we're in batch mode or dumping Emacs.
       (or noninteractive
           dump-mode
	   (let (errtype)
	     (if (file-directory-p user-emacs-directory)
		 (or (file-accessible-directory-p user-emacs-directory)
		     (setq errtype "access"))
               ;; We don't want to create HOME if it doesn't exist.
               (if (and (not (file-exists-p "~"))
                        (string-prefix-p
                         (expand-file-name "~")
                         (expand-file-name user-emacs-directory)))
                   (setq errtype "create")
                 ;; Create `user-emacs-directory'.
	         (with-file-modes ?\700
		   (condition-case nil
		       (make-directory user-emacs-directory t)
		     (error (setq errtype "create"))))))
	     (when (and errtype
			user-emacs-directory-warning
			(not (get 'user-emacs-directory-warning 'this-session)))
	       ;; Warn only once per Emacs session.
	       (put 'user-emacs-directory-warning 'this-session t)
	       (display-warning 'initialization
				(format "\
Unable to %s `user-emacs-directory' (%s).
Any data that would normally be written there may be lost!
If you never want to see this message again,
customize the variable `user-emacs-directory-warning'."
					errtype user-emacs-directory)))))
       bestname))))

;;; ---- keymaps (data subsystem: keymap.c primitives + keymap.el string API) ----
;; A keymap is a list whose car is the symbol `keymap'.  Bindings follow as
;; (EVENT . DEFINITION) conses; a bare `keymap' element in the tail begins the
;; PARENT keymap (shared structure).  These are faithful ports of the DOCUMENTED
;; behavior of the C primitives in keymap.c, verified value-for-value against the
;; Emacs 30.2 binary.  make-keymap (full char-table keymap) is NOT implemented:
;; it needs a char-table Value type elisprs lacks -- see report.  command-remapping
;; returns nil (correct with no active global/local remap keymaps).

;; With no buffer-local/global remap keymaps in effect, no command is remapped.

(defun make-sparse-keymap (&optional string)
  "Construct and return a new sparse keymap.
Optional STRING is a menu name for the keymap."
  (if string (list 'keymap string) (list 'keymap)))

(defun keymapp (object)
  "Return t if OBJECT is a keymap.
A keymap is a list (keymap . ALIST), or a symbol whose function
definition is itself a keymap."
  (if (symbolp object)
      (and object (keymapp (symbol-function object)))
    (and (consp object) (eq (car object) 'keymap))))

;; Resolve a keymap that may be a symbol standing for a keymap (a prefix command).
(defun keymap--get (object)
  (if (symbolp object) (symbol-function object) object))

(defun make-composed-keymap (maps &optional parent)
  "Construct a new keymap composed of MAPS and inheriting from PARENT.
MAPS can be a single keymap or a list of keymaps.  PARENT, if non-nil,
should be a keymap."
  (cons 'keymap (append (if (keymapp maps) (list maps) maps) parent)))

;; Return the (EVENT . DEF) cons in KM's own bindings (before the parent), or nil.
(defun keymap--own-binding (km event)
  (let ((tail (cdr km)) (res nil))
    (while (and (consp tail) (not res))
      (let ((el (car tail)))
        (cond ((eq el 'keymap) (setq tail nil))
              ((and (consp el) (equal (car el) event)) (setq res el))
              (t (setq tail (cdr tail))))))
    res))

;; Replace or prepend a binding for EVENT in KM's own bindings.
(defun keymap--set-binding (km event def)
  (let ((cell (keymap--own-binding km event)))
    (if cell
        (setcdr cell def)
      (setcdr km (cons (cons event def) (cdr km))))))

;; Delete EVENT's own binding from KM.
(defun keymap--remove-binding (km event)
  (let ((cell (keymap--own-binding km event)))
    (when cell (setcdr km (delq cell (cdr km))))))

;; Expand meta-modified integer events (bit 2^27) into ESC (27) + base char,
;; matching how keymap.c stores/looks up meta bindings.  Symbol events (e.g.
;; `M-left') are stored verbatim and are not expanded.
(defun keymap--expand-meta (events)
  (let ((res nil))
    (dolist (e events)
      (if (and (integerp e) (/= 0 (logand e (ash 1 27))))
          (progn (push 27 res) (push (logand e (lognot (ash 1 27))) res))
        (push e res)))
    (nreverse res)))

;; `Fdefine_key' / `Flookup_key' read a unibyte string key's characters 128-255
;; as meta characters (`c ^= 0200 | meta_modifier').  Strings here carry no
;; unibyte flag, so a string whose characters all fit in a byte and include one
;; above 127 is read that way.
(defun keymap--key-events (key)
  (if (and (stringp key)
           (let ((hi nil) (ok t))
             (mapc (lambda (c)
                     (cond ((> c 255) (setq ok nil))
                           ((> c 127) (setq hi t))))
                   key)
             (and ok hi)))
      (mapcar (lambda (c)
                (if (> c 127) (logxor c (logior #o200 #x8000000)) c))
              key)
    (append key nil)))

(defun define-key (keymap key def &optional remove)
  "In KEYMAP, define key sequence KEY as DEF.
KEY is a string or vector of events.  DEF is anything that can be a
key definition (a command symbol, a keymap for a prefix key, nil, etc.).
If optional REMOVE is non-nil, remove the binding instead.
Returns DEF."
  (let ((events (keymap--expand-meta (keymap--key-events key)))
        (km keymap)
        (consumed nil))
    (while (cdr events)
      (setq consumed (cons (car events) consumed))
      (let* ((raw (cdr (or (keymap--own-binding km (car events))
                           (cons nil nil))))
             (sub (keymap--get raw)))
        (cond
         ((keymapp sub) (setq km (keymap--get sub)))
         ;; A bound non-prefix key cannot start a longer sequence.
         (raw
          (error "Key sequence %s starts with non-prefix key %s"
                 (key-description key)
                 (key-description (vconcat (reverse consumed)))))
         (t
          (let ((new (make-sparse-keymap)))
            (keymap--set-binding km (car events) new)
            (setq km new)))))
      (setq events (cdr events)))
    (if remove
        (keymap--remove-binding km (car events))
      (keymap--set-binding km (car events) def))
    def))

;; Look up EVENT in KM's own bindings, then (transparently) its parent chain.
;; ACCEPT-DEFAULT recognizes a (t . DEF) default binding.
(defun lookup-key--event (km event accept-default)
  (let ((tail (cdr km)) (res nil) (deflt nil) (done nil))
    (while (and (consp tail) (not done))
      (let ((el (car tail)))
        (cond
         ((eq el 'keymap)
          (setq res (lookup-key--event tail event accept-default) done t))
         ((and (consp el) (eq (car el) 'keymap))
          (let ((r (lookup-key--event el event accept-default)))
            (when r (setq res r done t))))
         ((and (consp el) (equal (car el) event))
          (setq res (cdr el) done t))
         ((and (consp el) (eq (car el) t))
          (setq deflt (cdr el)))))
      (unless done (setq tail (cdr tail))))
    (or res (and accept-default deflt))))

(defun lookup-key (keymap key &optional accept-default)
  "Look up key sequence KEY in KEYMAP; return the definition.
KEY is a string or vector.  Returns nil if undefined.  If KEY is longer
than needed to reach a non-prefix binding, returns the number of events
at the front of KEY that were used.  ACCEPT-DEFAULT recognizes default
(t) bindings."
  (let ((events (keymap--expand-meta (keymap--key-events key)))
        (km (keymap--get keymap)) (i 0) (res nil) (done nil))
    (if (null events)
        keymap
      (while (and events (not done))
        (setq res (lookup-key--event km (car events) accept-default))
        (setq events (cdr events))
        (setq i (1+ i))
        (cond
         ((null events) (setq done t))
         ((keymapp res) (setq km (keymap--get res)))
         (t (setq res i done t))))
      res)))

(defun keymap-parent (keymap)
  "Return the parent keymap of KEYMAP, or nil if it has none."
  (let ((tail (cdr keymap)) (res nil))
    (while (and (consp tail) (not res))
      (if (eq (car tail) 'keymap)
          (setq res tail)
        (setq tail (cdr tail))))
    res))

(defun set-keymap-parent (keymap parent)
  "Modify KEYMAP to set its parent keymap to PARENT.  Return PARENT."
  (let ((prev keymap) (tail (cdr keymap)))
    (while (and (consp tail) (not (eq (car tail) 'keymap)))
      (setq prev tail tail (cdr tail)))
    (setcdr prev parent)
    parent))

(defun define-prefix-command (command &optional mapvar _name)
  "Define COMMAND as a prefix command with a new sparse keymap.
Set COMMAND's function cell to the keymap, and its value cell (or MAPVAR
if given and not t) to the same keymap.  Return COMMAND."
  (let ((map (make-sparse-keymap)))
    (fset command map)
    (if (and mapvar (not (eq mapvar t)))
        (set mapvar map)
      (set command map))
    command))

(defun suppress-keymap (map &optional nodigits)
  "Make MAP override all normally self-inserting keys to be undefined.
Normally, as an exception, digits and minus-sign are set to make prefix
args, but optional second arg NODIGITS non-nil treats them like other chars."
  (define-key map [remap self-insert-command] #'undefined)
  (or nodigits
      (let (loop)
        (define-key map "-" #'negative-argument)
        (setq loop ?0)
        (while (<= loop ?9)
          (define-key map (char-to-string loop) #'digit-argument)
          (setq loop (1+ loop))))))

;; ---- keymap.el: the string-based key API (faithful ports) ----

(defun key-parse (keys)
  "Convert KEYS to the internal Emacs key representation.
KEYS should be a string describing a key sequence in the format
returned by \\[describe-key] (`describe-key')."
  (save-match-data
    (let ((case-fold-search nil)
          (len (length keys))
          (pos 0)
          (res []))
      (while (and (< pos len)
                  (string-match "[^ \t\n\f]+" keys pos))
        (let* ((word-beg (match-beginning 0))
               (word-end (match-end 0))
               (word (substring keys word-beg len))
               (times 1)
               key)
          (if (string-match "\\`<[^ <>\t\n\f][^>\t\n\f]*>" word)
              (setq word (match-string 0 word)
                    pos (+ word-beg (match-end 0)))
            (setq word (substring keys word-beg word-end)
                  pos word-end))
          (when (string-match "\\([0-9]+\\)\\*." word)
            (setq times (string-to-number (substring word 0 (match-end 1))))
            (setq word (substring word (1+ (match-end 1)))))
          (cond ((string-match "^<<.+>>$" word)
                 (setq key (vconcat (if (eq (key-binding [?\M-x])
                                            'execute-extended-command)
                                        [?\M-x]
                                      (or (car (where-is-internal
                                                'execute-extended-command))
                                          [?\M-x]))
                                    (substring word 2 -2) "\r")))
                ((and (string-match "^\\(\\([ACHMsS]-\\)*\\)<\\(.+\\)>$" word)
                      (progn
                        (setq word (concat (match-string 1 word)
                                           (match-string 3 word)))
                        (not (string-match
                              "\\<\\(NUL\\|RET\\|LFD\\|TAB\\|ESC\\|SPC\\|DEL\\)$"
                              word))))
                 (setq key (list (intern word))))
                ((or (equal word "REM") (string-match "^;;" word))
                 (setq pos (string-match "$" keys pos)))
                (t
                 (let ((orig-word word) (prefix 0) (bits 0))
                   (while (string-match "^[ACHMsS]-." word)
                     (setq bits (+ bits
                                   (cdr
                                    (assq (aref word 0)
                                          '((?A . ?\A-\0) (?C . ?\C-\0)
                                            (?H . ?\H-\0) (?M . ?\M-\0)
                                            (?s . ?\s-\0) (?S . ?\S-\0))))))
                     (setq prefix (+ prefix 2))
                     (setq word (substring word 2)))
                   (when (string-match "^\\^.$" word)
                     (setq bits (+ bits ?\C-\0))
                     (setq prefix (1+ prefix))
                     (setq word (substring word 1)))
                   (let ((found (assoc word '(("NUL" . "\0") ("RET" . "\r")
                                              ("LFD" . "\n") ("TAB" . "\t")
                                              ("ESC" . "\e") ("SPC" . " ")
                                              ("DEL" . "\177")))))
                     (when found (setq word (cdr found))))
                   (when (string-match "^\\\\[0-7]+$" word)
                     (let ((n 0))
                       (dolist (ch (cdr (string-to-list word)))
                         (setq n (+ (* n 8) ch -48)))
                       (setq word (vector n))))
                   (cond ((= bits 0)
                          (setq key word))
                         ((and (= bits ?\M-\0) (stringp word)
                               (string-match "^-?[0-9]+$" word))
                          (setq key (mapcar (lambda (x) (+ x bits))
                                            (append word nil))))
                         ((/= (length word) 1)
                          (error "%s must prefix a single character, not %s"
                                 (substring orig-word 0 prefix) word))
                         ((and (/= (logand bits ?\C-\0) 0) (stringp word)
                               (string-match "[@-_a-z]" word))
                          (setq key (list (+ bits (- ?\C-\0)
                                             (logand (aref word 0) 31)))))
                         (t
                          (setq key (list (+ bits (aref word 0)))))))))
          (when key
            (dolist (_ (number-sequence 1 times))
              (setq res (vconcat res key))))))
      res)))

(defun key-valid-p (keys)
  "Return non-nil if KEYS, a string, is a valid key sequence.
KEYS should be a string consisting of one or more key strokes, with a
single space character separating one key stroke from another."
  (let ((case-fold-search nil))
    (and
     (stringp keys)
     (string-match-p "\\`[^ ]+\\( [^ ]+\\)*\\'" keys)
     (save-match-data
       (catch 'exit
         (let ((prefixes
                "\\(A-\\)?\\(C-\\)?\\(H-\\)?\\(M-\\)?\\(S-\\)?\\(s-\\)?"))
           (dolist (key (split-string keys " "))
             (when (string-match (concat "\\`" prefixes) key)
               (setq key (substring key (match-end 0))))
             (unless (or (and (= (length key) 1)
                              (not (< (aref key 0) ?\s))
                              (or (multibyte-string-p key)
                                  (not (<= 127 (aref key 0) 255))))
                         (and (string-match-p "\\`<[-_A-Za-z0-9]+>\\'" key)
                              (= (progn
                                   (string-match
                                    (concat "\\`<" prefixes) key)
                                   (match-end 0))
                                 1))
                         (string-match-p
                          "\\`\\(NUL\\|RET\\|TAB\\|LFD\\|ESC\\|SPC\\|DEL\\)\\'"
                          key))
               (throw 'exit nil)))
           t))))))

(defun keymap--check (key)
  "Signal an error if KEY doesn't have a valid syntax."
  (unless (key-valid-p key)
    (error "%S is not a valid key definition; see `key-valid-p'" key)))

(defun keymap-set (keymap key definition)
  "Set KEY to DEFINITION in KEYMAP.
KEY is a string that satisfies `key-valid-p'."
  (keymap--check key)
  (when (stringp definition)
    (keymap--check definition)
    (setq definition (key-parse definition)))
  (define-key keymap (key-parse key) definition))

(defun keymap-unset (keymap key &optional remove)
  "Remove KEY from KEYMAP.
If REMOVE is non-nil, remove the binding instead of setting it to nil."
  (keymap--check key)
  (define-key keymap (key-parse key) nil remove))

(defun keymap-lookup (keymap key &optional accept-default no-remap position)
  "Return the binding for command KEY in KEYMAP.
KEY is a string that satisfies `key-valid-p'.  KEYMAP must be non-nil
here: looking up in the current buffer-local/global keymaps (KEYMAP nil)
needs live buffer state that elisprs does not provide."
  (keymap--check key)
  (when (and keymap position)
    (error "Can't pass in both keymap and position"))
  (if keymap
      (let ((value (lookup-key keymap (key-parse key) accept-default)))
        (if (and (not no-remap)
                 (symbolp value))
            (or (command-remapping value) value)
          value))
    (error "keymap-lookup with no keymap needs buffer-local current keymaps (unsupported)")))

(defun define-keymap (&rest definitions)
  "Create a new keymap and define KEY/DEFINITION pairs as key bindings.
Return the new keymap.  Options may be given as keywords before the
pairs: :full :suppress :parent :keymap :name :prefix."
  (declare (indent defun))
  (let (full suppress parent name prefix keymap)
    (while (and definitions
                (keywordp (car definitions))
                (not (eq (car definitions) :menu)))
      (let ((keyword (pop definitions)))
        (unless definitions
          (error "Missing keyword value for %s" keyword))
        (let ((value (pop definitions)))
          (pcase keyword
            (:full (setq full value))
            (:keymap (setq keymap value))
            (:parent (setq parent value))
            (:suppress (setq suppress value))
            (:name (setq name value))
            (:prefix (setq prefix value))
            (_ (error "Invalid keyword: %s" keyword))))))

    (when (and prefix
               (or full parent suppress keymap))
      (error "A prefix keymap can't be defined with :full/:parent/:suppress/:keymap keywords"))

    (when (and keymap full)
      (error "Invalid combination: :keymap with :full"))

    (let ((keymap (cond
                   (keymap keymap)
                   (prefix (define-prefix-command prefix nil name))
                   (full (make-keymap name))
                   (t (make-sparse-keymap name))))
          seen-keys)
      (when suppress
        (suppress-keymap keymap (eq suppress 'nodigits)))
      (when parent
        (set-keymap-parent keymap parent))

      (while definitions
        (let ((key (pop definitions)))
          (unless definitions
            (error "Uneven number of key/definition pairs"))
          (let ((def (pop definitions)))
            (if (eq key :menu)
                (easy-menu-define nil keymap "" def)
              (when (member key seen-keys)
                (message "Duplicate definition for key: %S %s" key keymap))
              (push key seen-keys)
              (keymap-set keymap key def)))))
      keymap)))

(defmacro defvar-keymap (variable-name &rest defs)
  "Define VARIABLE-NAME as a variable with a keymap definition.
See `define-keymap' for an explanation of the keywords and KEY/DEFINITION.
Also accepts a `:doc' keyword for the variable documentation string, and
a `:repeat' keyword controlling `repeat-mode' behavior."
  (declare (indent 1))
  (let ((opts nil)
        doc repeat props)
    (while (and defs
                (keywordp (car defs))
                (not (eq (car defs) :menu)))
      (let ((keyword (pop defs)))
        (unless defs
          (error "Uneven number of keywords"))
        (cond
         ((eq keyword :doc) (setq doc (pop defs)))
         ((eq keyword :repeat) (setq repeat (pop defs)))
         (t (push keyword opts)
            (push (pop defs) opts)))))
    (unless (zerop (% (length defs) 2))
      (error "Uneven number of key/definition pairs: %s" defs))

    (let ((defs defs)
          key seen-keys)
      (while defs
        (setq key (pop defs))
        (pop defs)
        (when (not (eq key :menu))
          (if (member key seen-keys)
              (error "Duplicate definition for key '%s' in keymap '%s'"
                     key variable-name)
            (push key seen-keys)))))

    (when repeat
      (let ((defs defs)
            def)
        (dolist (def (plist-get repeat :enter))
          (push (list 'put (list 'quote def) ''repeat-map (list 'quote variable-name)) props))
        (while defs
          (pop defs)
          (setq def (pop defs))
          (when (and (memq (car def) '(function quote))
                     (not (memq (cadr def) (plist-get repeat :exit))))
            (push (list 'put def ''repeat-map (list 'quote variable-name)) props)))
        (dolist (def (plist-get repeat :hints))
          (push (list 'put (list 'quote (car def)) ''repeat-hint (list 'quote (cdr def))) props))))

    (let ((defvar-form
           (append (list 'defvar variable-name
                         (append (list 'define-keymap) (nreverse opts) defs))
                   (and doc (list doc)))))
      (if props
          (append (list 'progn defvar-form) (nreverse props))
        defvar-form))))

;; button-buffer-map (button.el) and special-mode-map (simple.el) are pure
;; keymap data that tabulated-list-mode-map inherits from via :parent.  Ported
;; from their upstream defvar-keymap forms.
(defvar-keymap button-buffer-map
  :doc "Keymap useful for buffers containing buttons.
Mode-specific keymaps may want to use this as their parent keymap."
  "TAB" #'forward-button
  "ESC TAB" #'backward-button
  "<backtab>" #'backward-button)

;;; ---- button types (button.el) ----
;; Faithful port of button.el's button-type system (define-button-type and the
;; button-type-{put,get,subtype-p} accessors).  Button types hold default
;; properties for buttons; each type NAME stores them on a separate uninterned
;; `-button' symbol (its `button-category-symbol'), so `category' text/overlay
;; properties can point at it without name clashes.  Overlay/text-property
;; button placement (make-button, insert-button, push-button navigation) is not
;; modeled here — only the type registry, which is what init files exercise at
;; load time.  Value-for-value against Emacs 30.2 button.el.

;; `(defface button ...)' is in src/lisp/faces-31.el, which makes every face
;; batch Emacs has in its face-id order.

(defvar-keymap button-map
  :doc "Keymap used by buttons."
  :parent button-buffer-map
  "RET" #'push-button
  "<mouse-2>" #'push-button
  "<follow-link>" 'mouse-face
  ;; FIXME: You'd think that for keymaps coming from text-properties on the
  ;; mode-line or header-line, the `mode-line' or `header-line' prefix
  ;; shouldn't be necessary!
  "<mode-line> <mouse-2>" #'push-button
  "<header-line> <mouse-2>" #'push-button
  ;; `push-button' will automatically dispatch to
  ;; `touch-screen-track-tap'.
  "<mode-line> <touchscreen-down>" #'push-button
  "<header-line> <touchscreen-down>" #'push-button
  "<touchscreen-down>" #'push-button)

;; `button-mode' (the TAB-navigation minor mode) is intentionally omitted: it is
;; button UI, not part of the type registry, and the prelude already omits it
;; while keeping button-buffer-map.  The type machinery below is self-contained.

;; Default properties for buttons.
(put 'default-button 'face 'button)
(put 'default-button 'mouse-face 'highlight)
(put 'default-button 'keymap button-map)
(put 'default-button 'type 'button)
;; `action' may be either a function to call, or a marker to go to.
(put 'default-button 'action #'ignore)
(put 'default-button 'help-echo (purecopy "mouse-2, RET: Push this button"))
;; Make overlay buttons go away if their underlying text is deleted.
(put 'default-button 'evaporate t)
;; Prevent insertions adjacent to text-property buttons from
;; inheriting their properties.
(put 'default-button 'rear-nonsticky t)

;; A `category-symbol' property for the default button type.
(put 'button 'button-category-symbol 'default-button)

;; [this is an internal function]
(defsubst button-category-symbol (type)
  "Return the symbol used by `button-type' TYPE to store properties.
Buttons inherit them by setting their `category' property to that symbol."
  (or (get type 'button-category-symbol)
      (error "Unknown button type `%s'" type)))

(defun define-button-type (name &rest properties)
  "Define a `button type' called NAME (a symbol).
The remaining PROPERTIES arguments form a plist of PROPERTY VALUE
pairs, specifying properties to use as defaults for buttons with
this type (a button's type may be set by giving it a `type'
property when creating the button, using the :type keyword
argument).

In addition, the keyword argument :supertype may be used to specify a
`button-type' from which NAME inherits its default property values
\(however, the inheritance happens only when NAME is defined; subsequent
changes to a supertype are not reflected in its subtypes)."
  (declare (indent defun))
  (let ((catsym (make-symbol (concat (symbol-name name) "-button")))
	(super-catsym
	 (button-category-symbol
	  (or (plist-get properties 'supertype)
	      (plist-get properties :supertype)
	      'button))))
    ;; Provide a link so that it's easy to find the real symbol.
    (put name 'button-category-symbol catsym)
    ;; Initialize NAME's properties using the global defaults.
    (let ((default-props (symbol-plist super-catsym)))
      (while default-props
	(put catsym (pop default-props) (pop default-props))))
    ;; Add NAME as the `type' property, which will then be returned as
    ;; the type property of individual buttons.
    (put catsym 'type name)
    ;; Add the properties in PROPERTIES to the real symbol.
    (while properties
      (let ((prop (pop properties)))
	(when (eq prop :supertype)
	  (setq prop 'supertype))
	(put catsym prop (pop properties))))
    ;; Make sure there's a `supertype' property.
    (unless (get catsym 'supertype)
      (put catsym 'supertype 'button))
    name))

(defun button-type-put (type prop val)
  "Set the `button-type' TYPE's PROP property to VAL."
  (put (button-category-symbol type) prop val))

(defun button-type-get (type prop)
  "Get the property of `button-type' TYPE named PROP."
  (get (button-category-symbol type) prop))

(defun button-type-subtype-p (type supertype)
  "Return non-nil if `button-type' TYPE is a subtype of SUPERTYPE."
  (or (eq type supertype)
      (and type
	   (button-type-subtype-p (button-type-get type 'supertype)
				  supertype))))

;; Mark `button' as provided so `(require 'button)' in init files no-ops onto
;; the preloaded type machinery instead of trying to open a file (button.el:672).
(provide 'button)

;;; ---- widget types (widget.el) ----
;; Faithful port of widget.el, the bootstrap half of the widget system that only
;; defines new widget types (everything else is autoloaded from wid-edit.el).
;; `define-widget' registers a type by storing (CLASS . ARGS) on the NAME
;; symbol's `widget-type' property and the doc string on `widget-documentation';
;; that registry is what init files touch at load time. The widget UI itself
;; (widget-create/widget-convert/widget-apply, the wid-edit.el layer) is not
;; modeled here. Value-for-value against Emacs 30.2 widget.el.

;; `define-widget-keywords' is a dummy kept only so external libraries that still
;; call it don't error; it expands to nil (obsolete since 27.1).
(defmacro define-widget-keywords (&rest _keys)
  (declare (obsolete nil "27.1") (indent defun))
  nil)

(defun define-widget (name class doc &rest args)
  "Define a new widget type named NAME from CLASS.

NAME and CLASS should both be symbols, CLASS should be one of the
existing widget types, or nil to create the widget from scratch.

After the new widget has been defined, the following two calls will
create identical widgets:

* (widget-create NAME)

* (apply #\\='widget-create CLASS ARGS)

The third argument DOC is a documentation string for the widget."
  (declare (doc-string 3) (indent defun))
  ;;
  (unless (or (null doc) (stringp doc))
    (error "Widget documentation must be nil or a string"))
  (put name 'widget-type (cons class args))
  (put name 'widget-documentation (purecopy doc))
  name)

(define-obsolete-function-alias 'widget-plist-member #'plist-member "26.1")

;; Mark `widget' as provided so `(require 'widget)' no-ops onto the preloaded
;; type registry instead of trying to open a file (widget.el:139).
(provide 'widget)

(defvar-keymap special-mode-map
  :suppress t
  "q" #'quit-window
  "SPC" #'scroll-up-command
  "S-SPC" #'scroll-down-command
  "DEL" #'scroll-down-command
  "?" #'describe-mode
  "h" #'describe-mode
  ">" #'end-of-buffer
  "<" #'beginning-of-buffer
  "g" #'revert-buffer)

;;; ---- major/minor mode machinery (derived.el, easy-mmode.el, subr.el) ----
;; Real text editing (point/insert, multiple named live buffers, narrowing,
;; marker-based save-excursion, first-class markers, and string/buffer text
;; properties) is modeled by the text-editing subsystem (builtins.rs). Overlays
;; and redisplay are not. Syntax tables and abbrev tables are separate subsystems:
;; the constructors below
;; are placeholders sufficient for `define-derived-mode' to expand and load; they
;; do not model syntax/abbrev semantics.

;; `interactive' is a special form the compiler lowers to nil (eval.c
;; `Finteractive' returns nil without evaluating its arguments); keeping it a
;; form rather than a macro leaves the spec in the closure, where
;; `make-interpreted-closure' stores it.

;; `current-buffer'/`set-buffer'/`get-buffer-create' and the rest of the buffer
;; registry are C-level primitives (see builtins.rs). Buffers are not associated
;; with files in this model, so `buffer-file-name' is always nil.
(defun buffer-file-name (&optional _buffer) nil)

;;; ---- char-tables (public make-char-table over the make-char-table--new subr) ----
;; make-char-table reads SUBTYPE's `char-table-extra-slots' property (0..10) to
;; size the extra slots, then calls the low-level allocator.  Faithful to
;; chartab.c `Fmake_char_table'.
(defun make-char-table (subtype &optional init)
  "Return a newly created char-table, with purpose SUBTYPE.
Each element is initialized to INIT, which defaults to nil.

The property `char-table-extra-slots' of SUBTYPE controls the number of
extra slots to reserve in this char-table.  This slot number is an
integer between 0 and 10, or nil, meaning 0."
  (let ((n (get subtype 'char-table-extra-slots)))
    ;; chartab.c rejects an out-of-range slot count with `args_out_of_range',
    ;; naming the property value and INIT -- not with an `error' of its own.
    (setq n (cond ((null n) 0)
                  ((and (integerp n) (>= n 0) (<= n 10)) n)
                  (t (signal 'args-out-of-range (list n init)))))
    (make-char-table--new subtype init n)))

;;; ---- syntax tables (syntax.c documented behavior, over char-tables) ----
;; A syntax table is a char-table with subtype `syntax-table'.  Each element is
;; a cons (SYNTAX-CODE . MATCHING-CHAR) where SYNTAX-CODE encodes the syntax
;; class in its low 16 bits plus flag bits; MATCHING-CHAR is the paired paren
;; (nil if none).  Verified value-for-value against the Emacs 30.2 binary.

;; syntax_code_spec (syntax.c): class index -> designator character.
(defconst --syntax-code-spec-- " .w_()'\"$\\/<>@!|"
  "Char at index N is the designator for syntax class N (see `string-to-syntax').")

(defun syntax-class-to-char (syntax-class)
  "Return the designator character for SYNTAX-CLASS (an integer 0..15)."
  (aref --syntax-code-spec-- syntax-class))

;; The flag descriptor characters and the bit each sets in the syntax code.
;; `c' (bit 23) is the third comment style, added for modes that need a third
;; two-character comment delimiter; it is in `Fstring_to_syntax' alongside the
;; other seven and was the only one missing here.
(defconst --syntax-flag-alist--
  '((?1 . 16) (?2 . 17) (?3 . 18) (?4 . 19) (?p . 20) (?b . 21) (?n . 22)
    (?c . 23))
  "Maps a `modify-syntax-entry' flag char to the bit it sets in the syntax code.")

;; syntax.c `Vsyntax_code_object': one shared `(CODE)' cons per bare class, so
;; that two descriptors naming the same class with no match char and no flags
;; are `eq'.  `init_syntax_once' builds it and `Fstring_to_syntax' returns from
;; it whenever `val < Smax' and MATCH is nil; freshly consing instead makes
;; `(eq (string-to-syntax "w") (string-to-syntax "w"))' nil where Emacs says t.
(defconst --syntax-code-object--
  (let ((v (make-vector 16 nil)) (i 0))
    (while (< i 16) (aset v i (list i)) (setq i (1+ i)))
    v)
  "Vector of the shared (CODE) conses, indexed by syntax class.")

(defun string-to-syntax (descriptor)
  "Convert syntax DESCRIPTOR string into the internal (CODE . MATCH) form.
DESCRIPTOR's first char names the class, the second the matching char
\(a space or missing means none), and any remaining chars are flags."
  (unless (stringp descriptor)
    (signal 'wrong-type-argument (list 'stringp descriptor)))
  ;; `Fstring_to_syntax' indexes `syntax_spec_code' with the first BYTE, and the
  ;; empty string's is the terminating NUL -- which is why Emacs reports the
  ;; letter as an unprintable character rather than rejecting the string.
  (let* ((c (if (= (length descriptor) 0) 0 (aref descriptor 0)))
         ;; `-' is an alias for whitespace; otherwise look C up in the spec.
         (class (if (eq c ?-) 0
                  (let ((i 0) (found nil) (len (length --syntax-code-spec--)))
                    (while (and (not found) (< i len))
                      (when (eq (aref --syntax-code-spec-- i) c) (setq found i))
                      (setq i (1+ i)))
                    (or found
                        (error "Invalid syntax description letter: %c" c))))))
    ;; Sinherit ("@") means "use the standard table here", which is spelled as a
    ;; nil descriptor -- not as class 13.
    (if (= class 13)
        nil
      (let ((match (and (> (length descriptor) 1)
                        (let ((m (aref descriptor 1)))
                          (unless (eq m ?\s) m))))
            (code class)
            (i 2) (len (length descriptor)))
        (while (< i len)
          (let ((bit (cdr (assq (aref descriptor i) --syntax-flag-alist--))))
            (when bit (setq code (logior code (ash 1 bit)))))
          (setq i (1+ i)))
        (if (and (< code 16) (null match))
            (aref --syntax-code-object-- code)
          (cons code match))))))

(defun syntax-class (syntax)
  "Return the syntax class part of the syntax code SYNTAX (a (CODE . MATCH) cons).
Return nil if SYNTAX is nil."
  (and syntax (logand (car syntax) 65535)))

;; The standard syntax table, built once to mirror syntax.c `init_syntax_once'
;; plus the Latin-1 block of lisp/international/characters.el.
;;
;; ASCII entries reproduce the binary's `standard-syntax-table' exactly.  So does
;; the Latin-1 supplement (U+0080-U+00FF): syntax.c defaults every character at
;; or above U+0080 to word, characters.el then gives the Latin-1 punctuation and
;; symbols `.'/`_' classes, and the two lists below are that result, verified
;; character by character against Emacs 30.2.  It is not a rule anyone can
;; re-derive from Unicode's general categories -- U+00A5 YEN SIGN keeps word
;; syntax while U+00A2..U+00A4 (the same Sc category) do not, and U+00B2/B3/B9
;; keep it while U+00BC..U+00BE (the same No category) do not -- so it is carried
;; as data.  Above U+00FF the same classification is carried by the (LO HI CODE) list below.
(defvar --standard-syntax-table-- nil
  "The standard syntax table (see `standard-syntax-table').")

(defun --init-standard-syntax-table-- ()
  (let* ((word (string-to-syntax "w"))
         (space (string-to-syntax " "))
         (punct (string-to-syntax "."))
         (symbol (string-to-syntax "_"))
         ;; syntax.c `init_syntax_once': whitespace is the table's initial
         ;; value and its default; everything else is set over it.
         (tbl (make-char-table 'syntax-table space)))
    ;; Word: letters, digits, `$' and `%', and every non-ASCII character.
    (set-char-table-range tbl '(?a . ?z) word)
    (set-char-table-range tbl '(?A . ?Z) word)
    (set-char-table-range tbl '(?0 . ?9) word)
    (aset tbl ?$ word)
    (aset tbl ?% word)
    (set-char-table-range tbl '(128 . #x3FFFFF) word)
    ;; Control chars 0..31 and DEL are PUNCTUATION here, and `?\n'/`?\r' are
    ;; whitespace -- syntax.c `init_syntax_once' sets exactly that, and
    ;;   emacs -Q --batch --eval '(with-syntax-table (standard-syntax-table) \
    ;;                              (prin1 (list (char-syntax 1) (char-syntax ?\n) \
    ;;                                           (char-syntax ?\r) (char-syntax 127))))'
    ;;   => (46 32 32 46)
    ;; confirms it on 30.2.  The `_'/`>' classes those characters are usually
    ;; SEEN with -- `(char-syntax 1)' => 95, `(char-syntax ?\n)' => 62 -- come
    ;; from the *buffer's* table, not this one: `emacs -Q --batch' starts in
    ;; `*scratch*' under `lisp-interaction-mode', whose table reclassifies every
    ;; non-alphanumeric ASCII.  That is installed below as the initial buffer's
    ;; table; putting it here instead would make `(standard-syntax-table)' wrong
    ;; for all 31 of those characters.
    (set-char-table-range tbl '(0 . 31) punct)
    (dolist (c '(?\t ?\n ?\f ?\r ?\s 160)) (aset tbl c space))
    (aset tbl 127 punct)
    ;; ASCII punctuation.
    (dolist (c '(?! ?# ?' ?, ?. ?: ?\; ?? ?@ ?^ ?` ?~)) (aset tbl c punct))
    ;; ASCII symbol constituents.
    (dolist (c '(?& ?* ?+ ?- ?/ ?< ?= ?> ?_ ?|)) (aset tbl c symbol))
    ;; Latin-1 supplement: ¡ § « » ¿ are punctuation, ...
    (dolist (c '(161 167 171 187 191)) (aset tbl c punct))
    ;; ... and the currency/modifier/math/other symbols are symbol constituents.
    (dolist (c '(162 163 164 166 168 169 170 172 173 174 175 176 177
                 180 182 183 184 186 188 189 190 215 247))
      (aset tbl c symbol))
    ;; Above U+00FF: characters.el's classification of the rest of the Unicode
    ;; space, carried as data for the same reason as the Latin-1 lists (it
    ;; follows the general-category tables, not a rule).  Each entry is
    ;; (LO HI CODE [MATCH]) over the word default; CODE is the syntax code
    ;; (0 whitespace, 1 punctuation, 3 symbol, 4/5 open/close with MATCH).
    ;; Dumped from `(standard-syntax-table)' of GNU Emacs 31.1.
    (dolist (r '(
    (#x2C7 #x2C7 3) (#x2C9 #x2C9 3) (#x2D0 #x2D0 3) (#x2D8 #x2DB 3)
    (#x2DD #x2DD 3) (#x384 #x385 3) (#x5BE #x5BE 1) (#x5C0 #x5C0 1)
    (#x5C3 #x5C3 1) (#x5C6 #x5C6 1) (#x5F3 #x5F4 1) (#xE2F #xE2F 3)
    (#xE3F #xE3F 3) (#xE46 #xE46 3) (#xE4F #xE4F 3) (#xE5A #xE5B 3)
    (#xEAF #xEAF 3) (#xEC6 #xEC6 3) (#xF00 #xF0B 1) (#xF0D #xF18 1)
    (#xF1A #xF1F 1) (#xF34 #xF34 1) (#xF36 #xF36 1) (#xF38 #xF3F 1)
    (#xF7F #xF7F 1) (#xF85 #xF85 1) (#xFBE #xFCF 1) (#x1361 #x1368 1)
    (#x1800 #x180A 1) (#x2000 #x200B 0) (#x200C #x2027 1) (#x202F #x202F 0)
    (#x2030 #x2038 1) (#x2039 #x203A 3) (#x203B #x2043 1) (#x2044 #x2044 3)
    (#x2045 #x2045 4 #x2046) (#x2046 #x2046 5 #x2045) (#x2047 #x2051 1)
    (#x2052 #x2052 3) (#x2053 #x205E 1) (#x205F #x205F 0)
    (#x207D #x207D 4 #x207E) (#x207E #x207E 5 #x207D)
    (#x208D #x208D 4 #x208E) (#x208E #x208E 5 #x208D) (#x20AC #x20AC 3)
    (#x2103 #x2103 3) (#x2109 #x2109 3) (#x2116 #x2116 1) (#x2121 #x2122 3)
    (#x2153 #x2154 3) (#x215B #x215E 3) (#x2190 #x2328 3)
    (#x2329 #x2329 4 #x232A) (#x232A #x232A 5 #x2329) (#x232B #x23B3 3)
    (#x23B4 #x23B4 4 #x23B5) (#x23B5 #x23B5 5 #x23B4) (#x23B6 #x244F 3)
    (#x2460 #x246E 3) (#x2474 #x24B5 3) (#x2500 #x254B 3) (#x2592 #x2592 3)
    (#x25A0 #x25A1 3) (#x25A3 #x25A9 3) (#x25B2 #x25B3 3) (#x25B6 #x25B7 3)
    (#x25BC #x25BD 3) (#x25C0 #x25C1 3) (#x25C6 #x25C8 3) (#x25CB #x25CB 3)
    (#x25CE #x25D1 3) (#x25EF #x25EF 3) (#x2605 #x2606 3) (#x260E #x260F 3)
    (#x261C #x261C 3) (#x261E #x261E 3) (#x2640 #x2640 3) (#x2642 #x2642 3)
    (#x2660 #x2661 3) (#x2663 #x2665 3) (#x2667 #x266A 3) (#x266C #x266D 3)
    (#x266F #x266F 3) (#x2768 #x2768 4 #x2769) (#x2769 #x2769 5 #x2768)
    (#x276A #x276A 4 #x276B) (#x276B #x276B 5 #x276A)
    (#x276C #x276C 4 #x276D) (#x276D #x276D 5 #x276C)
    (#x2770 #x2770 4 #x2771) (#x2771 #x2771 5 #x2770)
    (#x2772 #x2772 4 #x2773) (#x2773 #x2773 5 #x2772)
    (#x2774 #x2774 4 #x2775) (#x2775 #x2775 5 #x2774)
    (#x27E6 #x27E6 4 #x27E7) (#x27E7 #x27E7 5 #x27E6)
    (#x27E8 #x27E8 4 #x27E9) (#x27E9 #x27E9 5 #x27E8)
    (#x27EA #x27EA 4 #x27EB) (#x27EB #x27EB 5 #x27EA)
    (#x2983 #x2983 4 #x2984) (#x2984 #x2984 5 #x2983)
    (#x2985 #x2985 4 #x2986) (#x2986 #x2986 5 #x2985)
    (#x2987 #x2987 4 #x2988) (#x2988 #x2988 5 #x2987)
    (#x2989 #x2989 4 #x298A) (#x298A #x298A 5 #x2989)
    (#x298B #x298B 4 #x298C) (#x298C #x298C 5 #x298B)
    (#x298D #x298D 4 #x298E) (#x298E #x298E 5 #x298D)
    (#x298F #x298F 4 #x2990) (#x2990 #x2990 5 #x298F)
    (#x2991 #x2991 4 #x2992) (#x2992 #x2992 5 #x2991)
    (#x2993 #x2993 4 #x2994) (#x2994 #x2994 5 #x2993)
    (#x2995 #x2995 4 #x2996) (#x2996 #x2996 5 #x2995)
    (#x2997 #x2997 4 #x2998) (#x2998 #x2998 5 #x2997)
    (#x29FC #x29FC 4 #x29FD) (#x29FD #x29FD 5 #x29FC) (#x2A00 #x2BFF 3)
    (#x2E00 #x2E7F 1) (#x3000 #x3000 0) (#x3001 #x3003 1)
    (#x3008 #x3008 4 #x3009) (#x3009 #x3009 5 #x3008)
    (#x300A #x300A 4 #x300B) (#x300B #x300B 5 #x300A)
    (#x300C #x300C 4 #x300D) (#x300D #x300D 5 #x300C)
    (#x300E #x300E 4 #x300F) (#x300F #x300F 5 #x300E)
    (#x3010 #x3010 4 #x3011) (#x3011 #x3011 5 #x3010) (#x3012 #x3013 3)
    (#x3014 #x3014 4 #x3015) (#x3015 #x3015 5 #x3014)
    (#x3016 #x3016 4 #x3017) (#x3017 #x3017 5 #x3016)
    (#x3018 #x3018 4 #x3019) (#x3019 #x3019 5 #x3018)
    (#x301A #x301A 4 #x301B) (#x301B #x301B 5 #x301A) (#x301C #x301C 3)
    (#x30FB #x30FB 1) (#x3200 #x321C 3) (#x3220 #x3229 3) (#x3260 #x327B 3)
    (#x327E #x327F 3) (#x3380 #x3384 3) (#x3388 #x33CA 3) (#x33CF #x33D0 3)
    (#x33D3 #x33D3 3) (#x33D6 #x33D6 3) (#x33D8 #x33D8 3) (#x33DB #x33DD 3)
    (#xAADB #xAADF 3) (#xFD3E #xFD3E 4 #xFD3F) (#xFD3F #xFD3F 5 #xFD3E)
    (#xFE35 #xFE35 4 #xFE36) (#xFE36 #xFE36 5 #xFE35)
    (#xFE37 #xFE37 4 #xFE38) (#xFE38 #xFE38 5 #xFE37)
    (#xFE39 #xFE39 4 #xFE3A) (#xFE3A #xFE3A 5 #xFE39)
    (#xFE3B #xFE3B 4 #xFE3C) (#xFE3C #xFE3C 5 #xFE3B)
    (#xFE3D #xFE3D 4 #xFE3E) (#xFE3E #xFE3E 5 #xFE3D)
    (#xFE3F #xFE3F 4 #xFE40) (#xFE40 #xFE40 5 #xFE3F)
    (#xFE41 #xFE41 4 #xFE42) (#xFE42 #xFE42 5 #xFE41)
    (#xFE43 #xFE43 4 #xFE44) (#xFE44 #xFE44 5 #xFE43)
    (#xFE59 #xFE59 4 #xFE5A) (#xFE5A #xFE5A 5 #xFE59)
    (#xFE5B #xFE5B 4 #xFE5C) (#xFE5C #xFE5C 5 #xFE5B)
    (#xFE5D #xFE5D 4 #xFE5E) (#xFE5E #xFE5E 5 #xFE5D) (#xFF01 #xFF03 1)
    (#xFF04 #xFF04 3) (#xFF05 #xFF07 1) (#xFF08 #xFF08 4 #xFF09)
    (#xFF09 #xFF09 5 #xFF08) (#xFF0A #xFF0A 1) (#xFF0B #xFF0B 3)
    (#xFF0C #xFF0F 1) (#xFF1A #xFF1B 1) (#xFF1C #xFF1E 3) (#xFF1F #xFF20 1)
    (#xFF3B #xFF3B 4 #xFF3D) (#xFF3C #xFF3C 3) (#xFF3D #xFF3D 5 #xFF3B)
    (#xFF3E #xFF40 3) (#xFF5B #xFF5B 4 #xFF5D) (#xFF5C #xFF5C 3)
    (#xFF5D #xFF5D 5 #xFF5B) (#xFF5E #xFF5E 3) (#xFF5F #xFF5F 4 #xFF60)
    (#xFF60 #xFF60 5 #xFF5F) (#xFF61 #xFF61 1) (#xFF62 #xFF62 4 #xFF63)
    (#xFF63 #xFF63 5 #xFF62) (#xFF64 #xFF65 1) (#xFFE0 #xFFE3 3)
    (#xFFE5 #xFFE5 3) (#x11660 #x1166C 1) (#x1FB00 #x1FBCA 3)
    (#x1FBCB #x1FBFF 1) (#x110000 #x1100BB 3) (#x1102F0 #x11034D 3)
    (#x140000 #x1400BB 3) (#x140292 #x1402EF 3) (#x148000 #x148119 3)
    (#x279F94 #x27A04F 3) (#x27A16A #x27A225 3) (#x27A235 #x27A283 3)
    (#x27A293 #x27A2D8 3)
                 ))
      (set-char-table-range
       tbl (cons (nth 0 r) (nth 1 r))
       (if (nth 3 r) (cons (nth 2 r) (nth 3 r)) (list (nth 2 r)))))
    ;; String quote and escape.
    (aset tbl ?\" (string-to-syntax "\""))
    (aset tbl ?\\ (string-to-syntax "\\"))
    ;; Balanced pairs: open matches close and vice versa.
    (aset tbl ?\( (string-to-syntax "()"))
    (aset tbl ?\) (string-to-syntax ")("))
    (aset tbl ?\[ (string-to-syntax "(]"))
    (aset tbl ?\] (string-to-syntax ")["))
    (aset tbl ?\{ (string-to-syntax "(}"))
    (aset tbl ?\} (string-to-syntax "){"))
    tbl))

(setq --standard-syntax-table-- (--init-standard-syntax-table--))

(defun standard-syntax-table ()
  "Return the standard syntax table.
This is the one used for new buffers."
  --standard-syntax-table--)

;; The current buffer's syntax table is a buffer-local slot defaulting to the
;; standard table (Emacs keeps it in the buffer object; buffer-local var here).
(defvar-local --current-syntax-table-- nil
  "The current buffer's syntax table (see `syntax-table').")

(defun syntax-table ()
  "Return the current syntax table.
This is the one specified by the current buffer."
  (or --current-syntax-table-- --standard-syntax-table--))

(defun set-syntax-table (table)
  "Select TABLE as the syntax table for the current buffer."
  (setq --current-syntax-table-- table)
  table)

(defun copy-syntax-table (&optional table)
  "Construct a new syntax table and return it.
It is a copy of TABLE, which defaults to the standard syntax table."
  (let* ((src (or table --standard-syntax-table--))
         (new (make-char-table 'syntax-table)))
    (set-char-table-parent new (char-table-parent src))
    ;; Copy every set char over the char range.  Non-ASCII beyond the modeled
    ;; range shares the source's word default via the range copy of ascii+.
    (dotimes (c 128) (aset new c (char-table-range src c)))
    (set-char-table-range new '(128 . #x3FFFFF) (char-table-range src 128))
    new))

(defun make-syntax-table (&optional parent)
  "Return a new syntax table.
Create a syntax table that inherits from PARENT (which defaults to the
standard syntax table)."
  (let ((table (make-char-table 'syntax-table)))
    (set-char-table-parent table (or parent --standard-syntax-table--))
    table))

(defun syntax-table-p (object)
  "Return t if OBJECT is a syntax table."
  (and (char-table-p object) (eq (char-table-subtype object) 'syntax-table)))

(defun modify-syntax-entry (char newentry &optional syntax-table)
  "Set syntax for the characters CHAR to the string NEWENTRY.
CHAR may be a cons (MIN . MAX), in which case, syntaxes of all characters
in the range between MIN and MAX, inclusive, are set.  SYNTAX-TABLE
defaults to the current buffer's syntax table."
  (interactive "cSet syntax for character: \nsSet syntax for %s to: ")
  (set-char-table-range (or syntax-table (syntax-table))
                        char (string-to-syntax newentry))
  nil)

(defun char-syntax (character)
  "Return the syntax class of CHARACTER, described by a character.
For example, if CHARACTER is a word constituent, the character `?w' is
returned.  The characters that correspond to various syntax codes are
listed in the documentation of `modify-syntax-entry'."
  (syntax-class-to-char (syntax-class (aref (syntax-table) character))))

;; ---- capitalize / upcase-initials (casefiddle.c) ----
;; These live here, after `char-syntax', because the word test is the SYNTAX
;; TABLE's -- `case_ch_is_word (SYNTAX (ch))' -- not "is this a cased letter or
;; a digit", which is what elisprs used to ask. The difference is observable:
;; `fi' has no one-to-one upper case, so the old test called it a non-word
;; character, which made the *next* character a word start:
;; `(capitalize "find")' answered "fiNd" where Emacs answers "Find".
;;
;; The other half is that a word's first character is TITLE-cased, not
;; upper-cased. `case_character_impl' consults `special-titlecase' (one-to-many)
;; before the `titlecase' char-table and only then `upcase', which is why
;; `(capitalize "ßäöü")' is "Ssäöü" (not "ẞäöü") and `(capitalize "dza")' is
;; "Dza" (not "DZa"): Dz is the title-case digraph, distinct from DZ.
(defvar case-symbols-as-words nil
  "Non-nil means the case functions treat symbol constituents as word ones.")

(defun --char-titlecase-1-- (c)
  "The one-to-one title case of character C.
`case_character_impl' with a NULL buffer skips the one-to-many
`special-titlecase' table and consults the `titlecase' char-table, falling
back to `upcase' -- so `(capitalize ?\u01f3)' is the title digraph
\u01f2, while `(capitalize ?\u00df)', whose title case is two characters,
is the upper-case \u1e9e."
  ;; Out-of-range integers keep `upcase''s own casefiddle.c handling: a negative
  ;; fixnum is not a character (`char-or-string-p'), and one above the character
  ;; range comes back unchanged because Emacs reads the high bits as event
  ;; modifiers. Asking for a title case first would report `characterp' instead.
  (if (or (< c 0) (> c #x3FFFFF))
      (upcase c)
    (let ((tc (--char-titlecase-- c)))
      (if (= (length tc) 1) (aref tc 0) (upcase c)))))

(defun --case-ch-is-word-- (c)
  "casefiddle.c `case_ch_is_word': is C a word constituent for casing?"
  (let ((sy (--syntax-code-at-- nil c)))
    (or (= sy 2) (and case-symbols-as-words (= sy 3)))))

(defun --casify-capitalize-- (s up-only)
  "casefiddle.c `do_casify_multibyte_string' for the two capitalizing flags.
UP-ONLY non-nil is CASE_CAPITALIZE_UP (`upcase-initials'), which leaves the
rest of each word alone; nil is CASE_CAPITALIZE (`capitalize'), which
down-cases it."
  (let ((chars (string-to-list s)) (out nil) (was nil) (in-word nil) c rest)
    (while chars
      (setq c (car chars))
      (setq rest (cdr chars))
      (setq was in-word)
      (setq in-word (--case-ch-is-word-- c))
      (cond
       ((not was) (push (--char-titlecase-- c) out))
       (up-only (push (string c) out))
       ;; CASE_DOWN, plus `case_character''s Greek rule: a capital sigma that
       ;; ends a word down-cases to the FINAL sigma ς, not to σ.
       ((and (eq c 931) (or (null rest) (not (--case-ch-is-word-- (car rest)))))
        (push (string 962) out))
       (t (push (downcase (string c)) out)))
      (setq chars rest))
    (let ((res (apply (function concat) (reverse out))))
      ;; Text properties can only be carried straight across when no character
      ;; expanded, which the one-to-many title/lower mappings can break.
      (if (= (length res) (length s))
          (elisprs--carry-text-properties s res)
        res))))

;; ---- skip-syntax-forward / skip-syntax-backward (syntax.c `skip_syntaxes') ----
;; The C builds a 256-entry fastmap over syntax CLASS CODES:
;;
;;   if (i_byte < size_byte && SREF (string, 0) == '^') { negate = 1; i_byte++; }
;;   while (i_byte < size_byte) { c = str[i_byte++]; fastmap[syntax_spec_code[c]] = 1; }
;;   if (negate) for (i = 0; i < sizeof fastmap; i++) fastmap[i] ^= 1;
;;
;; then walks while `fastmap[SYNTAX (c)]' holds, stopping at LIM, and returns
;; `PT - start_point'.  Here the set of accepted classes is carried as a list of
;; class indices instead of a 256-byte array; `negate' flips the membership test,
;; which is the same thing without the array.
;;
;; `syntax_spec_code' is the inverse of `--syntax-code-spec--' with one extra
;; entry: `-' is an alias for whitespace.  Every other unlisted spec character
;; maps to 0377, a code no real class has -- so `(skip-syntax-forward "Z")' skips
;; nothing rather than signalling, and `(skip-syntax-forward "wZ")' behaves like
;; `"w"'.  That is exactly what dropping the character from the list does.
(defun --syntax-spec-classes-- (spec)
  "The list of syntax class indices SPEC's characters name (see `syntax_spec_code').
Characters that name no class contribute nothing, as in the C, where they
address a fastmap slot that no real syntax class can match."
  (let ((i 0) (len (length spec)) (out nil) c class)
    (while (< i len)
      (setq c (aref spec i))
      (setq class (if (eq c ?-) 0
                    (let ((j 0) (found nil) (n (length --syntax-code-spec--)))
                      (while (and (not found) (< j n))
                        (when (eq (aref --syntax-code-spec-- j) c) (setq found j))
                        (setq j (1+ j)))
                      found)))
      (when class (push class out))
      (setq i (1+ i)))
    out))

(defun --skip-syntaxes-- (forwardp syntax lim)
  "Common body of `skip-syntax-forward' and `skip-syntax-backward'."
  (unless (stringp syntax) (signal 'wrong-type-argument (list 'stringp syntax)))
  (let* ((negate (and (> (length syntax) 0) (eq (aref syntax 0) ?^)))
         (spec (if negate (substring syntax 1) syntax))
         (classes (--syntax-spec-classes-- spec))
         (start (point))
         ;; "In any case, don't allow scan outside bounds of buffer."
         (lim (max (point-min) (min (point-max)
                                    (cond ((null lim) (if forwardp (point-max) (point-min)))
                                          ((markerp lim) (marker-position lim))
                                          (t lim)))))
         (ch nil))
    (if forwardp
        (while (and (< (point) lim)
                    (setq ch (char-after))
                    (let ((in (and (memq (syntax-class (aref (syntax-table) ch)) classes) t)))
                      (if negate (not in) in)))
          (goto-char (1+ (point))))
      (while (and (> (point) lim)
                  (setq ch (char-before))
                  (let ((in (and (memq (syntax-class (aref (syntax-table) ch)) classes) t)))
                    (if negate (not in) in)))
        (goto-char (1- (point)))))
    (- (point) start)))

(defun skip-syntax-forward (syntax &optional lim)
  "Move point forward across chars in specified syntax classes.
SYNTAX is a string of syntax code characters.
Stop before a char whose syntax is not in SYNTAX, or at position LIM.
If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.
This function returns the distance traveled, either zero or positive."
  (--skip-syntaxes-- t syntax lim))

(defun skip-syntax-backward (syntax &optional lim)
  "Move point backward across chars in specified syntax classes.
SYNTAX is a string of syntax code characters.
Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.
If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.
This function returns either zero or a negative number, and the absolute value
of this is the distance traveled."
  (--skip-syntaxes-- nil syntax lim))

(defmacro with-syntax-table (table &rest body)
  "Evaluate BODY with syntax table TABLE as the current syntax table.
The syntax table of the current buffer is saved, BODY is evaluated, and
the saved table is restored.  (Single-buffer model: the save/restore is
over the one current buffer's syntax-table slot.)"
  (declare (indent 1) (debug t))
  (let ((old-table (make-symbol "table")))
    `(let ((,old-table (syntax-table)))
       (unwind-protect
           (progn
             (set-syntax-table ,table)
             ,@body)
         (set-syntax-table ,old-table)))))

;;; ---- syntax.c's sexp/comment scanner ----
;; `scan-lists', `parse-partial-sexp' and everything built on them are one
;; port, not seven: `Fforward_sexp' is `scan_lists', and `scan_lists' and
;; `Fparse_partial_sexp' share the comment/string state machine
;; (`scan_sexps_forward', `forw_comment', `back_comment', `char_quoted'),
;; including two-character comment delimiters, nested comments, the
;; `syntax-table' text property and `parse-sexp-ignore-comments'.  A
;; parens-only subset would answer plausibly on the common case and wrongly
;; inside a string or a comment, so the whole machine is ported.

(defun buffer-end (arg)
  "Return the \"far end\" position of the buffer, in direction ARG."
  (if (> arg 0) (point-max) (point-min)))

;; ---- variables the scanner consults (syntax.c DEFVARs) ----
(defvar parse-sexp-ignore-comments nil
  "Non-nil means `forward-sexp', etc., should treat comments as whitespace.")
(defvar parse-sexp-lookup-properties nil
  "Non-nil means `forward-sexp', etc., obey the `syntax-table' text property.")
(defvar-local comment-end-can-be-escaped nil
  "Non-nil means an escaped ender doesn't end the comment.")
(defvar multibyte-syntax-as-symbol nil
  "Non-nil means `scan-sexps' treats all multibyte characters as symbol.")
(defvar open-paren-in-column-0-is-defun-start t
  "Non-nil means an open paren in column 0 denotes the start of a defun.")
(defvar words-include-escapes nil
  "Non-nil means `forward-word', etc., should treat escape chars part of words.")
(defvar comment-use-syntax-ppss t
  "Non-nil means `forward-comment' can use `syntax-ppss' internally.")

;; ST_COMMENT_STYLE / ST_STRING_STYLE (syntax.c): sentinels for the styles that
;; the comment-fence and string-fence classes start, which no `b'/`c' flag
;; combination can name.
(defconst --st-comment-style-- 257)
(defconst --st-string-style-- 258)
;; enum syntaxcode.  Smax doubles as "this position's syntax is used up".
(defconst --syn-smax-- 16)

;; ---- syntax lookup (syntax.h SYNTAX_ENTRY / SYNTAX_WITH_FLAGS / SYNTAX) ----
;; The C reads the entry through gl_state, which UPDATE_SYNTAX_TABLE_* keeps in
;; step with the `syntax-table' text property when `parse-sexp-lookup-properties'
;; is on.  Here the position travels with the character instead, so the property
;; is consulted at the point of use and there is no cache to keep valid.  A
;; property whose value is a syntax table selects that table for the character;
;; a cons is the raw descriptor itself, exactly as update_syntax_table does.
(defun --syntax-raw-at-- (pos c)
  "The raw syntax descriptor (CODE . MATCH) for character C at POS."
  (let ((prop (and parse-sexp-lookup-properties pos
                   (get-char-property pos 'syntax-table))))
    (cond ((consp prop) prop)
          ((syntax-table-p prop) (aref prop c))
          (t (aref (syntax-table) c)))))

(defun --syntax-flags-at-- (pos c)
  "SYNTAX_WITH_FLAGS: the code+flags integer for C at POS.
A non-cons entry reads as whitespace, as in `syntax_property_with_flags'."
  (let ((e (--syntax-raw-at-- pos c)))
    (if (consp e) (car e) 0)))

(defun --syntax-code-at-- (pos c)
  "SYNTAX: the syntax class of C at POS."
  (logand (--syntax-flags-at-- pos c) 255))

(defun --syntax-match-at-- (pos c)
  "SYNTAX_MATCH: the matching character of C at POS, or nil."
  (let ((e (--syntax-raw-at-- pos c)))
    (and (consp e) (cdr e))))

;; syntax_multibyte: with `multibyte-syntax-as-symbol', every non-ASCII
;; character reads as a symbol constituent regardless of its table entry.
(defun --syntax-code-mb-- (pos c mbsym)
  (if (or (< c 128) (not mbsym)) (--syntax-code-at-- pos c) 3))

;; ---- SYNTAX_FLAGS_* (syntax.c) ----
(defun --syn-comstart-first-- (f) (/= 0 (logand f 65536)))      ; 1 << 16
(defun --syn-comstart-second-- (f) (/= 0 (logand f 131072)))    ; 1 << 17
(defun --syn-comend-first-- (f) (/= 0 (logand f 262144)))       ; 1 << 18
(defun --syn-comend-second-- (f) (/= 0 (logand f 524288)))      ; 1 << 19
(defun --syn-comstartend-first-- (f) (/= 0 (logand f 327680)))  ; 0x50000
(defun --syn-prefix-- (f) (/= 0 (logand f 1048576)))            ; 1 << 20
(defun --syn-styleb-- (f) (if (/= 0 (logand f 2097152)) 1 0))   ; 1 << 21
(defun --syn-nested-- (f) (/= 0 (logand f 4194304)))            ; 1 << 22
(defun --syn-stylec2-- (f) (logand (ash f -22) 2))              ; 1 << 23 -> 2
;; FLAGS is the flags of the main char of the marker: the second for a comment
;; start, the first for a comment end.
(defun --syn-comment-style-- (f other)
  (logior (--syn-styleb-- f) (--syn-stylec2-- f) (--syn-stylec2-- other)))

;; ---- char_quoted / prev_char_comend_first ----
(defun --char-quoted-- (charpos)
  "Port of syntax.c `char_quoted': is CHARPOS preceded by an odd escape run?"
  (let ((beg (point-min)) (pos charpos) (quoted nil) (stop nil) c code)
    (while (and (not stop) (> pos beg))
      (setq pos (1- pos))
      (setq c (char-after pos))
      (setq code (--syntax-code-at-- pos c))
      (if (or (= code 9) (= code 10))   ; Sescape, Scharquote
          (setq quoted (not quoted))
        (setq stop t)))
    quoted))

(defun --prev-char-comend-first-- (pos)
  "Port of syntax.c `prev_char_comend_first'."
  (let ((c (char-after (1- pos))))
    (--syn-comend-first-- (--syntax-flags-at-- (1- pos) c))))

;; ---- find_defun_start (syntax.c), without the one-entry memo ----
;; The memo is pure speed; it caches the answer for a repeated query and is
;; invalidated on every buffer modification, so dropping it cannot change a
;; result.  `open-paren-in-column-0-is-defun-start' nil means only BEGV counts.
(defun --find-defun-start-- (pos)
  (let ((beg (point-min)) (found nil))
    (if (not open-paren-in-column-0-is-defun-start)
        beg
      (save-excursion
        (goto-char pos)
        (while (and (not found) (> (point) beg))
          (goto-char (line-beginning-position))
          (if (and (< (point) (point-max))
                   (eq (--syntax-code-at-- (point) (char-after (point))) 4))
              (setq found (point))
            (if (<= (point) beg) (setq found beg) (goto-char (1- (point))))))
        (or found beg)))))

;; ---- forw_comment (syntax.c) ----
;; Returns (FOUND POSITION INCOMMENT LAST-SYNTAX).  INCOMMENT and LAST-SYNTAX
;; are only meaningful when FOUND is nil, exactly as the C's out-parameters are
;; only written on the not-found path.
(defun --forw-comment-- (from stop nesting style prev-syntax)
  (let ((syntax prev-syntax) code c c1 other-syntax
        (skip-head nil) (broke nil) (out nil))
    (when (<= nesting 0) (setq nesting -1))
    (setq code (logand syntax 255))
    ;; "Enter the loop in the middle so that we find a 2-char comment ender if
    ;; we start in the middle of it."
    (when (and (/= syntax 0) (< from stop)) (setq skip-head t))
    (while (and (not out) (not broke))
      (if skip-head
          (setq skip-head nil)
        (if (= from stop)
            (setq out (list nil from nesting
                            (if (or (= code 9) (= code 10)
                                    (--syn-comend-first-- syntax)
                                    (and (> nesting 0)
                                         (--syn-comstart-first-- syntax)))
                                syntax --syn-smax--)))
          (setq c (char-after from))
          (setq prev-syntax syntax)
          (setq syntax (--syntax-flags-at-- from c))
          (setq code (logand syntax 255))
          (cond
           ;; A comment ender of the style this comment section began with.
           ((and (= code 12)
                 (= (--syn-comment-style-- syntax 0) style)
                 (if (--syn-nested-- syntax)
                     (and (> nesting 0) (= (setq nesting (1- nesting)) 0))
                   (< nesting 0))
                 (not (and comment-end-can-be-escaped
                           (memq (logand prev-syntax 255) '(9 10)))))
            (setq broke t))
           ;; A comment fence ends a fence-style comment.
           ((and (= code 14) (= style --st-comment-style--))
            (setq broke t))
           (t
            (when (and (> nesting 0) (= code 11) (--syn-nested-- syntax)
                       (= (--syn-comment-style-- syntax 0) style))
              (setq nesting (1+ nesting)))
            (when (and comment-end-can-be-escaped (memq code '(9 10)))
              (setq from (1+ from))
              (if (= from stop)
                  (setq skip-head 'continue)
                (setq c (char-after from))
                (setq prev-syntax syntax)
                (setq syntax --syn-smax--)
                (setq code syntax)))
            (unless (eq skip-head 'continue)
              (setq from (1+ from)))))))
      (when (and (not out) (not broke))
        (if (eq skip-head 'continue)
            (setq skip-head nil)
          ;; forw_incomment:
          (when (and (< from stop) (--syn-comend-first-- syntax)
                     (progn (setq c1 (char-after from))
                            (setq other-syntax (--syntax-flags-at-- from c1))
                            (--syn-comend-second-- other-syntax))
                     (= (--syn-comment-style-- syntax other-syntax) style)
                     (if (or (--syn-nested-- syntax) (--syn-nested-- other-syntax))
                         (> nesting 0)
                       (< nesting 0)))
            ;; So that a two-char |# ender cannot report its # as LAST-SYNTAX.
            (setq syntax --syn-smax--)
            (setq nesting (1- nesting))
            (if (<= nesting 0)
                (setq broke t)
              (setq from (1+ from))))
          (when (and (not broke)
                     (> nesting 0) (< from stop)
                     (--syn-comstart-first-- syntax)
                     (progn (setq c1 (char-after from))
                            (setq other-syntax (--syntax-flags-at-- from c1))
                            (and (= (--syn-comment-style-- other-syntax syntax) style)
                                 (--syn-comstart-second-- other-syntax)))
                     (or (--syn-nested-- syntax) (--syn-nested-- other-syntax)))
            ;; So that a #|# run is not also a comment ender.
            (setq syntax --syn-smax--)
            (setq from (1+ from))
            (setq nesting (1+ nesting))))))
    (or out (list t from nesting --syn-smax--))))

;; ---- back_comment (syntax.c) ----
;; Returns (FOUND POSITION).  FOUND is `from != comment_end'.
(defun --back-comment-- (from stop comnested comstyle)
  (let ((string-style -1) (string-lossage nil) (comment-lossage nil)
        (comment-end from) (comstart-pos 0) (defun-start 0)
        (nesting 1) (syntax 0) (lossage nil) (done nil) (loop t)
        code c prev-syntax com2start com2end comstart)
    (while (and loop (/= from stop))
      (setq from (1- from))
      (setq prev-syntax syntax)
      (setq c (char-after from))
      (setq syntax (--syntax-flags-at-- from c))
      (setq code (logand syntax 255))
      (setq com2start (and (--syn-comstart-first-- syntax)
                           (--syn-comstart-second-- prev-syntax)
                           (= comstyle (--syn-comment-style-- prev-syntax syntax))
                           (eq (and (or (--syn-nested-- prev-syntax)
                                        (--syn-nested-- syntax))
                                    t)
                               (and comnested t))))
      (setq com2end (and (--syn-comend-first-- syntax)
                         (--syn-comend-second-- prev-syntax)))
      (setq comstart (or com2start (= code 11)))
      ;; Overlapping 2-char markers: don't try to be clever.
      (when (and (> from stop) (or com2end comstart))
        (let* ((next-c (char-after (1- from)))
               (next-syntax (--syntax-flags-at-- (1- from) next-c)))
          (when (or (and (or comstart comnested)
                         (--syn-comend-second-- syntax)
                         (--syn-comend-first-- next-syntax))
                    (and (or com2end comnested)
                         (--syn-comstart-second-- syntax)
                         (= comstyle (--syn-comment-style-- syntax prev-syntax))
                         (--syn-comstart-first-- next-syntax)))
            (setq lossage t loop nil))))
      (when loop
        ;; The first 2-char marker seen counts as a starter, later ones as enders.
        (when (and com2start (= comstart-pos 0)) (setq com2end nil))
        (cond (com2end (setq code 12))
              (com2start (setq code 11)))
        (cond
         ;; Comment starters of a different style are not ours.
         ((and (not com2end) (not com2start) (= code 11)
               (or (/= comstyle (--syn-comment-style-- syntax 0))
                   (not (eq (and (--syn-nested-- syntax) t) (and comnested t)))))
          nil)
         ;; Escaped characters, except comment-enders, which cannot be escaped.
         ((and (or comment-end-can-be-escaped (/= code 12))
               (--char-quoted-- from))
          nil)
         (t
          (cond
           ((memq code '(15 14 7))      ; Sstring_fence, Scomment_fence, Sstring
            (when (memq code '(15 14))
              (setq c (if (= code 15) --st-string-style-- --st-comment-style--)))
            (cond ((= string-style -1) (setq string-style c))
                  ((= string-style c) (setq string-style -1))
                  (t (setq string-lossage t))))
           ((= code 11)                 ; Scomment
            (if (or (/= string-style -1) comment-lossage string-lossage)
                (setq lossage t loop nil)
              (if (not comnested)
                  (setq comstart-pos from)
                (setq nesting (1- nesting))
                (when (<= nesting 0) (setq done t loop nil)))))
           ((= code 12)                 ; Sendcomment
            (if (and (= (--syn-comment-style-- syntax 0) comstyle)
                     (eq (and (or (and com2end (--syn-nested-- prev-syntax))
                                  (--syn-nested-- syntax))
                              t)
                         (and comnested t)))
                (if comnested
                    (setq nesting (1+ nesting))
                  ;; Anything before this would match this ender, not ours.
                  (setq from stop))
              (when (or (/= comstart-pos 0) (not (eq c ?\n)))
                (setq comment-lossage t))))
           ((= code 4)                  ; Sopen
            (when (and open-paren-in-column-0-is-defun-start
                       (null comment-use-syntax-ppss)
                       (or (= from stop) (eq (char-after (1- from)) ?\n)))
              (setq defun-start from)
              (setq from stop)))
           (t nil))))))
    (cond
     (done nil)
     (lossage
      ;; Two kinds of string delimiter mixed together: decode going forwards
      ;; from a known safe place, recording where we last passed a starter.
      (when (= defun-start 0)
        (setq defun-start (--find-defun-start-- comment-end)))
      (let ((go t) state)
        (while go
          (setq state (--scan-sexps-forward-- (--pps-internalize-- nil)
                                              defun-start comment-end
                                              --pps-no-target-- nil 0))
          (setq defun-start comment-end)
          (if (and (= (--pps-incomment-- state) (if comnested 1 -1))
                   (= (--pps-comstyle-- state) comstyle))
              (setq from (--pps-comstr-start-- state))
            (setq from comment-end)
            (when (/= (--pps-incomment-- state) 0)
              (setq defun-start (+ (--pps-comstr-start-- state) 2))))
          (setq go (< defun-start comment-end)))))
     ((= comstart-pos 0) (setq from comment-end))
     (t (setq from comstart-pos)))
    (list (/= from comment-end) from)))

;; ---- the parse state of scan_sexps_forward ----
;; A 12-slot vector standing in for `struct lisp_parse_state'.
(defconst --pps-no-target-- -2305843009213693952
  "Stand-in for TYPE_MINIMUM (EMACS_INT): a depth the scan cannot reach.")

(defun --pps-depth-- (s) (aref s 0))
(defun --pps-instring-- (s) (aref s 1))
(defun --pps-incomment-- (s) (aref s 2))
(defun --pps-comstyle-- (s) (aref s 3))
(defun --pps-quoted-- (s) (aref s 4))
(defun --pps-mindepth-- (s) (aref s 5))
(defun --pps-thislevelstart-- (s) (aref s 6))
(defun --pps-prevlevelstart-- (s) (aref s 7))
(defun --pps-location-- (s) (aref s 8))
(defun --pps-comstr-start-- (s) (aref s 9))
(defun --pps-levelstarts-- (s) (aref s 10))
(defun --pps-prev-syntax-- (s) (aref s 11))

(defun --pps-internalize-- (external)
  "Port of syntax.c `internalize_parse_state'."
  (if (null external)
      (vector 0 -1 0 0 nil 0 -1 -1 0 -1 nil --syn-smax--)
    (let* ((depth (let ((tem (nth 0 external))) (if (integerp tem) tem 0)))
           (tem3 (nth 3 external))
           (instring (if tem3 (if (characterp tem3) tem3 --st-string-style--) -1))
           (tem4 (nth 4 external))
           (incomment (if tem4 (if (integerp tem4) tem4 -1) 0))
           (quoted (and (nth 5 external) t))
           (tem7 (nth 7 external))
           (comstyle (cond ((null tem7) 0)
                           ((and (integerp tem7) (>= tem7 0)
                                 (<= tem7 --st-comment-style--))
                            tem7)
                           (t --st-comment-style--)))
           (tem8 (nth 8 external))
           (comstr-start (if (integerp tem8) tem8 -1))
           (levelstarts (nth 9 external))
           (tem10 (nth 10 external))
           (prev-syntax (if (null tem10) --syn-smax-- tem10)))
      (vector depth instring incomment comstyle quoted 0 -1 -1 0
              comstr-start levelstarts prev-syntax))))

;; in_2char_comment_start (syntax.c): is the char at FROM the second half of a
;; 2-character comment opener begun by PREV-FROM-SYNTAX?  Updates STATE.
(defun --pps-in-2char-comment-start-- (state prev-from-syntax prev-from from)
  (let (c1 syntax)
    (when (and (--syn-comstart-first-- prev-from-syntax)
               (progn (setq c1 (char-after from))
                      (setq syntax (--syntax-flags-at-- from c1))
                      (--syn-comstart-second-- syntax)))
      (aset state 3 (--syn-comment-style-- syntax prev-from-syntax))
      (aset state 2 (if (or (--syn-nested-- prev-from-syntax)
                            (--syn-nested-- syntax))
                        1 -1))
      (aset state 9 prev-from)
      t)))

;; ---- scan_sexps_forward (syntax.c) ----
;; The C is one function with eleven labels and a fallthrough switch.  It is
;; transcribed here as an explicit label machine: LABEL holds the C's program
;; counter, each branch returns the next label, and nil ends the scan.  Writing
;; it as structured elisp would need the control flow to be re-derived, which is
;; exactly the step that turns a port into a rewrite.
;;
;; `struct level levelstart[100]' becomes OUTER (a list of (LAST . PREV) conses,
;; innermost first) plus CUR-LAST/CUR-PREV for `curlevel'.  The C silently
;; clamps at 100 levels rather than signalling, so NLEV does too.
(defun --scan-sexps-forward-- (state from end targetdepth stopbefore commentstop)
  (let* ((depth (--pps-depth-- state))
         (start-quoted (--pps-quoted-- state))
         (mindepth depth)
         (prev-from from)
         (prev-from-syntax (--pps-prev-syntax-- state))
         (prev-prev-from-syntax --syn-smax--)
         (boundary-stop (eq commentstop -1))
         (begv (point-min))
         (cur-last -1) (cur-prev -1) (outer nil) (nlev 0)
         (label 'entry)
         nofence res code c c-code symchar tem)
    (when (/= from begv) (setq prev-from (1- from)))
    ;; INC_FROM, as a closure so every call site reads like the C's macro.  A
    ;; plain lexical closure rather than `cl-flet': `cl-flet' walks the whole
    ;; body to rewrite the call sites, and this body is the largest form in the
    ;; prelude, which pushed prelude loading past the 2 MiB stack a test thread
    ;; gets (the shipped binary runs on a 512 MiB interpreter stack and never
    ;; saw it).
    (let ((inc-from (lambda ()
                      (setq prev-from from)
                      (setq tem (char-after prev-from))
                      (setq prev-prev-from-syntax prev-from-syntax)
                      (setq prev-from-syntax (--syntax-flags-at-- prev-from tem))
                      (setq from (1+ from)))))
      (while label
        (setq label
              (cond
               ;; ---- entry dispatch ----
               ((eq label 'entry)
                (dolist (temhd (--pps-levelstarts-- state))
                  (when (integerp temhd) (setq cur-last temhd))
                  (if (= nlev 99)
                      nil
                    (push (cons cur-last cur-prev) outer)
                    (setq nlev (1+ nlev)))
                  (setq cur-prev -1 cur-last -1))
                (setq cur-prev -1 cur-last -1)
                (aset state 4 nil)
                (cond
                 ((/= (--pps-incomment-- state) 0) 'startincomment)
                 ((>= (--pps-instring-- state) 0)
                  (setq nofence (/= (--pps-instring-- state) --st-string-style--))
                  (if start-quoted 'startquotedinstring 'startinstring))
                 (start-quoted 'startquoted)
                 ((and (< from end)
                       (--pps-in-2char-comment-start-- state prev-from-syntax
                                                        prev-from from))
                  (funcall inc-from)
                  (setq prev-from-syntax --syn-smax--)
                  'atcomment)
                 (t 'main)))

               ;; ---- while (from < end) ----
               ((eq label 'main)
                (if (>= from end)
                    'done
                  (funcall inc-from)
                  (cond
                   ((and (< from end)
                         (--pps-in-2char-comment-start-- state prev-from-syntax
                                                          prev-from from))
                    (funcall inc-from)
                    (setq prev-from-syntax --syn-smax--)
                    'atcomment)
                   ((--syn-prefix-- prev-from-syntax) 'main)
                   (t
                    (setq code (logand prev-from-syntax 255))
                    (cond
                     ((memq code '(9 10))            ; Sescape, Scharquote
                      (if stopbefore 'stop
                        (setq cur-last prev-from)
                        'startquoted))
                     ((memq code '(2 3))             ; Sword, Ssymbol
                      (if stopbefore 'stop
                        (setq cur-last prev-from)
                        'symstarted))
                     ((= code 14)                    ; Scomment_fence
                      (aset state 3 --st-comment-style--)
                      (aset state 2 -1)
                      (aset state 9 prev-from)
                      'atcomment)
                     ((= code 11)                    ; Scomment
                      (aset state 3 (--syn-comment-style-- prev-from-syntax 0))
                      (aset state 2 (if (--syn-nested-- prev-from-syntax) 1 -1))
                      (aset state 9 prev-from)
                      'atcomment)
                     ((= code 4)                     ; Sopen
                      (if stopbefore 'stop
                        (setq depth (1+ depth))
                        (setq cur-last prev-from)
                        (if (= nlev 99)
                            nil
                          (push (cons cur-last cur-prev) outer)
                          (setq nlev (1+ nlev)))
                        (setq cur-prev -1 cur-last -1)
                        (if (= targetdepth depth) 'done 'main)))
                     ((= code 5)                     ; Sclose
                      (setq depth (1- depth))
                      (when (< depth mindepth) (setq mindepth depth))
                      (when (> nlev 0)
                        (setq cur-last (car (car outer)))
                        (setq cur-prev (cdr (car outer)))
                        (setq outer (cdr outer))
                        (setq nlev (1- nlev)))
                      (setq cur-prev cur-last)
                      (if (= targetdepth depth) 'done 'main))
                     ((memq code '(7 15))            ; Sstring, Sstring_fence
                      (aset state 9 (1- from))
                      (if stopbefore 'stop
                        (setq cur-last prev-from)
                        (aset state 1 (if (= code 7)
                                          (char-after prev-from)
                                        --st-string-style--))
                        (if boundary-stop 'done 'startinstring)))
                     (t 'main))))))            ; Smath, whitespace, punct, ...

               ;; ---- startquoted ----
               ((eq label 'startquoted)
                (if (= from end) 'endquoted (funcall inc-from) 'symstarted))

               ;; ---- symstarted / symdone ----
               ((eq label 'symstarted)
                (cond
                 ((>= from end) (setq cur-prev cur-last) 'main)
                 ((--pps-in-2char-comment-start-- state prev-from-syntax
                                                   prev-from from)
                  (funcall inc-from)
                  (setq prev-from-syntax --syn-smax--)
                  'atcomment)
                 (t
                  (setq symchar (char-after from))
                  (setq code (--syntax-code-at-- from symchar))
                  (cond
                   ((memq code '(9 10))              ; Scharquote, Sescape
                    (funcall inc-from)
                    (if (= from end) 'endquoted (funcall inc-from) 'symstarted))
                   ((memq code '(2 3 6))             ; Sword, Ssymbol, Squote
                    (funcall inc-from)
                    'symstarted)
                   (t (setq cur-prev cur-last) 'main)))))

               ;; ---- atcomment / startincomment ----
               ((eq label 'atcomment)
                (if (or (/= commentstop 0) boundary-stop)
                    'done
                  'startincomment))

               ((eq label 'startincomment)
                ;; The (from == BEGV) test enters forw_comment in the middle so
                ;; that a 2-char ender is found even when the scan starts inside
                ;; it -- but not when we are only just at the comment's start
                ;; (think of "(*) ... (*)").
                (setq res (--forw-comment-- from end
                                            (--pps-incomment-- state)
                                            (--pps-comstyle-- state)
                                            (if (= from begv) 0 prev-from-syntax)))
                (setq from (nth 1 res))
                (setq prev-from-syntax (nth 3 res))
                (if (not (nth 0 res))
                    (progn
                      (aset state 2 (nth 2 res))
                      (if (memq (logand prev-from-syntax 255) '(9 10))
                          'endquoted
                        'done))
                  (funcall inc-from)
                  (aset state 2 0)
                  (aset state 3 0)
                  (setq prev-from-syntax --syn-smax--)
                  (if boundary-stop 'done 'main)))

               ;; ---- startinstring / startquotedinstring / string_end ----
               ((eq label 'startinstring)
                (setq nofence (/= (--pps-instring-- state) --st-string-style--))
                'instring-loop)

               ((eq label 'startquotedinstring)
                (if (>= from end) 'endquoted (funcall inc-from) 'instring-loop))

               ((eq label 'instring-loop)
                (if (>= from end)
                    'done
                  (setq c (char-after from))
                  (setq c-code (--syntax-code-at-- from c))
                  (if (and nofence (eq c (--pps-instring-- state)) (= c-code 7))
                      'string-end
                    (cond
                     ((= c-code 15)                  ; Sstring_fence
                      (if (not nofence) 'string-end (funcall inc-from) 'instring-loop))
                     ((memq c-code '(9 10))          ; Scharquote, Sescape
                      (funcall inc-from)
                      (if (>= from end) 'endquoted (funcall inc-from) 'instring-loop))
                     (t (funcall inc-from) 'instring-loop)))))

               ((eq label 'string-end)
                (aset state 1 -1)
                (setq cur-prev cur-last)
                (funcall inc-from)
                (if boundary-stop 'done 'main))

               ;; ---- stop / endquoted / done ----
               ((eq label 'stop)
                (setq from prev-from)
                (setq prev-from-syntax prev-prev-from-syntax)
                'done)

               ((eq label 'endquoted)
                (aset state 4 t)
                'done)

               ((eq label 'done)
                (aset state 0 depth)
                (aset state 5 mindepth)
                (aset state 6 cur-prev)
                (aset state 7 (if (= nlev 0) -1 (car (car outer))))
                (aset state 8 from)
                (aset state 10 (reverse (mapcar #'car outer)))
                (aset state 11 (if (or (--syn-comstartend-first-- prev-from-syntax)
                                       (--pps-quoted-- state))
                                   prev-from-syntax
                                 --syn-smax--))
                nil)))))
    state))

;; ---- scan_lists (syntax.c) ----
;; The C's `goto lose' is a signal, so it stays a signal here.  `done'/`done2'
;; end one iteration of the count loop and `return Qnil' leaves the whole scan,
;; so those two are catch tags.
(defun --scan-lists-- (from0 count depth sexpflag)
  (let* ((stop (if (> count 0) (point-max) (point-min)))
         (min-depth (if (> depth 0) 0 depth))
         (from (max (point-min) (min (point-max) from0)))
         (last-good from0)
         (comstyle 0) (comnested nil) (mathexit nil)
         (mbsym (and sexpflag multibyte-syntax-as-symbol t))
         c c1 code syntax other-syntax comstart-first prefix
         stringterm c-code quoted temp-pos res act inner)
    (catch '--sl-return--
      (while (> count 0)
        (catch '--sl-done--
          (while (< from stop)
            (setq c (char-after from))
            (setq syntax (--syntax-flags-at-- from c))
            (setq code (--syntax-code-mb-- from c mbsym))
            (setq comstart-first (--syn-comstart-first-- syntax))
            (setq comnested (--syn-nested-- syntax))
            (setq comstyle (--syn-comment-style-- syntax 0))
            (setq prefix (--syn-prefix-- syntax))
            (when (= depth min-depth) (setq last-good from))
            (setq from (1+ from))
            ;; The C reassigns C inside the && chain, so it is clobbered
            ;; whenever the first two conjuncts hold -- even if
            ;; `parse-sexp-ignore-comments' is nil and the branch is not taken.
            (when (and (< from stop) comstart-first)
              (setq c (char-after from))
              (setq other-syntax (--syntax-flags-at-- from c))
              (when (and (--syn-comstart-second-- other-syntax)
                         parse-sexp-ignore-comments)
                (setq code 11)
                (setq comstyle (--syn-comment-style-- other-syntax syntax))
                (setq comnested (or comnested (--syn-nested-- other-syntax)))
                (setq from (1+ from))))
            (unless prefix
              (setq act nil)
              (when (memq code '(9 10))            ; Sescape, Scharquote
                (when (= from stop) (--sl-lose-- last-good from))
                (setq from (1+ from))
                (setq code 2))                     ; fall through to Sword
              (cond
               ((memq code '(2 3))                 ; Sword, Ssymbol
                (unless (or (/= depth 0) (not sexpflag))
                  (setq inner t)
                  (while (and inner (< from stop))
                    (setq c (char-after from))
                    (setq c-code (--syntax-code-mb-- from c mbsym))
                    (cond
                     ((memq c-code '(9 10))
                      (setq from (1+ from))
                      (when (= from stop) (--sl-lose-- last-good from)))
                     ((memq c-code '(2 3 6)) nil)  ; Sword, Ssymbol, Squote
                     (t (setq inner nil)))
                    (when inner (setq from (1+ from))))
                  (throw '--sl-done-- nil)))
               ((memq code '(11 14))               ; Scomment, Scomment_fence
                (when (= code 14) (setq comstyle --st-comment-style--))
                (when parse-sexp-ignore-comments
                  (setq res (--forw-comment-- from stop
                                              (if comnested 1 0) comstyle 0))
                  (setq from (nth 1 res))
                  (unless (nth 0 res)
                    (if (= depth 0)
                        (throw '--sl-done-- nil)
                      (--sl-lose-- last-good from)))
                  (setq from (1+ from))))
               ((= code 8)                         ; Smath
                (when sexpflag
                  (when (and (/= from stop) (eq c (char-after from)))
                    (setq from (1+ from)))
                  (if mathexit
                      (progn (setq mathexit nil) (setq act 'close))
                    (setq mathexit t)
                    (setq act 'open))))
               ((= code 4) (setq act 'open))       ; Sopen
               ((= code 5) (setq act 'close))      ; Sclose
               ((memq code '(7 15))                ; Sstring, Sstring_fence
                (setq stringterm (char-after (1- from)))
                (setq inner t)
                (while inner
                  (when (>= from stop) (--sl-lose-- last-good from))
                  (setq c (char-after from))
                  (setq c-code (--syntax-code-mb-- from c mbsym))
                  (if (if (= code 7)
                          (and (eq c stringterm) (= c-code 7))
                        (= c-code 15))
                      (setq inner nil)
                    (when (memq c-code '(9 10)) (setq from (1+ from)))
                    (setq from (1+ from))))
                (setq from (1+ from))
                (when (and (= depth 0) sexpflag) (throw '--sl-done-- nil)))
               (t nil))                            ; whitespace, punct, quote...
              (cond
               ((eq act 'open)
                (setq depth (1+ depth))
                (when (= depth 0) (throw '--sl-done-- nil)))
               ((eq act 'close)
                (setq depth (1- depth))
                (when (= depth 0) (throw '--sl-done-- nil))
                (when (< depth min-depth)
                  (signal 'scan-error
                          (list "Containing expression ends prematurely"
                                last-good from)))))))
          ;; Reached end of buffer: error if within an object, nil if between.
          (when (/= depth 0) (--sl-lose-- last-good from))
          (throw '--sl-return-- nil))
        (setq count (1- count)))

      (while (< count 0)
        (catch '--sl-done--
          (while (> from stop)
            (setq from (1- from))
            (setq c (char-after from))
            (setq syntax (--syntax-flags-at-- from c))
            (setq code (--syntax-code-mb-- from c mbsym))
            (when (= depth min-depth) (setq last-good from))
            (setq comstyle 0)
            (setq comnested (--syn-nested-- syntax))
            (when (= code 12) (setq comstyle (--syn-comment-style-- syntax 0)))
            (setq prefix nil)
            (when (and (> from stop) (--syn-comend-second-- syntax)
                       (--prev-char-comend-first-- from)
                       parse-sexp-ignore-comments)
              (setq from (1- from))
              (setq code 12)
              (setq c1 (char-after from))
              (setq other-syntax (--syntax-flags-at-- from c1))
              (setq comstyle (--syn-comment-style-- other-syntax syntax))
              (setq comnested (or comnested (--syn-nested-- other-syntax))))
            ;; Quoting turns anything but a comment-ender into a word char.
            (if (and (/= code 12) (--char-quoted-- from))
                (progn (setq from (1- from)) (setq code 2))
              (when (--syn-prefix-- syntax) (setq prefix t)))
            (unless prefix
              (setq act nil)
              (cond
               ((memq code '(2 3 9 10))            ; Sword, Ssymbol, Sescape, ...
                (unless (or (/= depth 0) (not sexpflag))
                  (setq inner t)
                  (while (and inner (> from stop))
                    (setq temp-pos (1- from))
                    (setq c1 (char-after temp-pos))
                    ;; Don't allow comment-end to be quoted.
                    (if (= (--syntax-code-mb-- temp-pos c1 mbsym) 12)
                        (setq inner nil)
                      (setq quoted (--char-quoted-- (1- from)))
                      (when quoted
                        (setq from (1- from))
                        (setq temp-pos (1- temp-pos)))
                      (setq c1 (char-after temp-pos))
                      (if (and (not quoted)
                               (not (memq (--syntax-code-mb-- temp-pos c1 mbsym)
                                          '(2 3 6))))
                          (setq inner nil)
                        (setq from (1- from)))))
                  (throw '--sl-done-- nil)))
               ((= code 8)                         ; Smath
                (when sexpflag
                  (when (> from (point-min))
                    (setq temp-pos (1- from))
                    (when (and (/= from stop) (eq c (char-after temp-pos)))
                      (setq from (1- from))))
                  (if mathexit
                      (progn (setq mathexit nil) (setq act 'open))
                    (setq mathexit t)
                    (setq act 'close))))
               ((= code 5) (setq act 'close))      ; Sclose
               ((= code 4) (setq act 'open))       ; Sopen
               ((= code 12)                        ; Sendcomment
                (when parse-sexp-ignore-comments
                  (setq res (--back-comment-- from stop comnested comstyle))
                  (when (nth 0 res) (setq from (nth 1 res)))))
               ((memq code '(14 15))               ; Scomment_fence, Sstring_fence
                (setq inner t)
                (while inner
                  (when (= from stop) (--sl-lose-- last-good from))
                  (setq from (1- from))
                  (unless (--char-quoted-- from)
                    (setq c (char-after from))
                    (when (= (--syntax-code-mb-- from c mbsym) code)
                      (setq inner nil))))
                (when (and (= code 15) (= depth 0) sexpflag)
                  (throw '--sl-done-- nil)))
               ((= code 7)                         ; Sstring
                (setq stringterm (char-after from))
                (setq inner t)
                (while inner
                  (when (= from stop) (--sl-lose-- last-good from))
                  (setq from (1- from))
                  (unless (--char-quoted-- from)
                    (setq c (char-after from))
                    (when (and (eq c stringterm)
                               (= (--syntax-code-mb-- from c mbsym) 7))
                      (setq inner nil))))
                (when (and (= depth 0) sexpflag) (throw '--sl-done-- nil)))
               (t nil))
              (cond
               ((eq act 'close)
                (setq depth (1+ depth))
                (when (= depth 0) (throw '--sl-done-- nil)))
               ((eq act 'open)
                (setq depth (1- depth))
                (when (= depth 0) (throw '--sl-done-- nil))
                (when (< depth min-depth)
                  (signal 'scan-error
                          (list "Containing expression ends prematurely"
                                last-good from)))))))
          (when (/= depth 0) (--sl-lose-- last-good from))
          (throw '--sl-return-- nil))
        (setq count (1+ count)))
      from)))

(defun --sl-lose-- (last-good from)
  (signal 'scan-error (list "Unbalanced parentheses" last-good from)))

;; ---- the scanner's Lisp entry points ----
(defun scan-lists (from count depth)
  "Scan from character number FROM by COUNT lists.
Scan forward if COUNT is positive, backward if COUNT is negative.
Return the character number of the position thus found.

A \"list\", in this context, refers to a balanced parenthetical
grouping, as determined by the syntax table.

If DEPTH is nonzero, treat that as the nesting depth of the starting
point (i.e. the starting point is DEPTH parentheses deep).  This
function scans over parentheses until the depth goes to zero COUNT
times.  Hence, positive DEPTH moves out that number of levels of
parentheses, while negative DEPTH moves to a deeper level.

Comments are ignored if `parse-sexp-ignore-comments' is non-nil.

If we reach the beginning or end of the accessible part of the buffer
before we have scanned over COUNT lists, return nil if the depth at
that point is zero, and signal an error if the depth is nonzero."
  (unless (integerp from) (signal 'wrong-type-argument (list 'fixnump from)))
  (unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
  (unless (integerp depth) (signal 'wrong-type-argument (list 'fixnump depth)))
  (--scan-lists-- from count depth nil))

(defun scan-sexps (from count)
  "Scan from character number FROM by COUNT balanced expressions.
If COUNT is negative, scan backwards.
Returns the character number of the position thus found.

Comments are ignored if `parse-sexp-ignore-comments' is non-nil.

If the beginning or end of (the accessible part of) the buffer is reached
in the middle of a parenthetical grouping, an error is signaled.
If the beginning or end is reached between groupings
but before count is used up, nil is returned."
  (unless (integerp from) (signal 'wrong-type-argument (list 'fixnump from)))
  (unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
  (--scan-lists-- from count 0 t))

(defun matching-paren (character)
  "Return the matching parenthesis of CHARACTER, or nil if none."
  (unless (characterp character)
    (signal 'wrong-type-argument (list 'characterp character)))
  (let ((code (--syntax-code-at-- nil character)))
    (and (memq code '(4 5)) (--syntax-match-at-- nil character))))

(defun syntax-after (pos)
  "Return the raw syntax descriptor for the char after POS.
If POS is outside the buffer's accessible portion, return nil."
  (unless (or (< pos (point-min)) (>= pos (point-max)))
    (let ((st (and parse-sexp-lookup-properties
                   (get-char-property pos 'syntax-table))))
      (if (consp st) st (aref (syntax-table) (char-after pos))))))

(defun syntax-prefix-flag-p (c)
  "Whether the syntax of character C has the prefix flag set."
  (--syn-prefix-- (--syntax-flags-at-- nil c)))

(defun backward-prefix-chars ()
  "Move point backward over any number of chars with prefix syntax.
This includes chars with expression prefix syntax class (') and those with
the prefix syntax flag (p)."
  (let* ((beg (point-min)) (opoint (point)) (pos (point)) (go t) c)
    (if (<= pos beg)
        (progn (goto-char opoint) nil)
      (setq pos (1- pos))
      (while (and go
                  (not (--char-quoted-- pos))
                  (progn (setq c (char-after pos))
                         (or (= (--syntax-code-at-- pos c) 6)
                             (syntax-prefix-flag-p c))))
        (setq opoint pos)
        (if (<= pos beg)
            (setq go nil)
          (setq pos (1- pos))))
      (goto-char opoint)
      nil)))

;; ── indentation and whitespace commands (indent.c, simple.el) ──
(defvar indent-tabs-mode t)
(defvar delete-trailing-lines t)
(defun back-to-indentation ()
  "Move point to the first non-whitespace character on this line."
  (beginning-of-line 1)
  (skip-syntax-forward " " (line-end-position))
  (backward-prefix-chars))
(defun delete-horizontal-space (&optional backward-only)
  "Delete all spaces and tabs around point.
If BACKWARD-ONLY is non-nil, delete them only before point."
  (let ((orig-pos (point)))
    (delete-region
     (if backward-only
         orig-pos
       (progn (skip-chars-forward " \t") (point)))
     (progn (skip-chars-backward " \t") (point)))))
(defun delete-trailing-whitespace (&optional start end)
  "Delete trailing whitespace between START and END (default: whole buffer).
With no END, also delete trailing empty lines at the end of the buffer when
`delete-trailing-lines' is non-nil. Returns nil."
  (save-match-data
    (save-excursion
      (let ((end-marker (and end (copy-marker end))))
        (goto-char (or start (point-min)))
        (with-syntax-table (make-syntax-table (syntax-table))
          ;; Don't delete formfeeds, even if they are considered whitespace.
          (modify-syntax-entry ?\f "_")
          (while (re-search-forward "\\s-$" end-marker t)
            (skip-syntax-backward "-" (line-beginning-position))
            (delete-region (point) (match-end 0))))
        (if end
            (set-marker end-marker nil)
          (and delete-trailing-lines
               (= (goto-char (point-max)) (1+ (buffer-size)))
               (<= (skip-chars-backward "\n") -2)
               (delete-region (1+ (point)) (point-max)))))))
  nil)
;; simple.el whitespace commands. elisprs has no `field' text properties, so
;; simple.el's `(constrain-to-field nil ORIG-POS)' calls — which only differ
;; from point inside a field — are spelled as point.
(defvar fill-prefix nil)
(defvar deactivate-mark nil)
(defun fixup-whitespace ()
  "Fixup white space between objects around point.
Leave one space or none, according to the context."
  (save-excursion
    (delete-horizontal-space)
    (if (or (looking-at "^\\|$\\|\\s)")
            (save-excursion (forward-char -1)
                            (looking-at "$\\|\\s(\\|\\s'")))
        nil
      (insert ?\s))))
(defun delete-indentation (&optional arg beg end)
  "Join this line to previous and fix up whitespace at join.
With ARG, join the current line to the following line. When BEG and END are
non-nil, join all lines in the region they define."
  (setq deactivate-mark t)
  (if (and beg (not arg))
      (and (goto-char beg)
           (> end (line-end-position))
           (goto-char end))
    (setq beg (1- (line-beginning-position (and arg 2))))
    (when arg (forward-line)))
  (let ((prefix (and (> (length fill-prefix) 0)
                     (regexp-quote fill-prefix))))
    (while (and (> (line-beginning-position) beg)
                (forward-line 0)
                (= (preceding-char) ?\n))
      (delete-char -1)
      (if (and prefix (looking-at prefix))
          (replace-match "" t t))
      (fixup-whitespace))))
(defalias 'join-line #'delete-indentation)
(defun delete-blank-lines ()
  "On blank line, delete all surrounding blank lines, leaving just one.
On isolated blank line, delete that one.
On nonblank line, delete any immediately following blank lines."
  (let (thisblank singleblank)
    (save-excursion
      (beginning-of-line)
      (setq thisblank (looking-at "[ \t]*$"))
      (setq singleblank
            (and thisblank
                 (not (looking-at "[ \t]*\n[ \t]*$"))
                 (or (bobp)
                     (progn (forward-line -1)
                            (not (looking-at "[ \t]*$")))))))
    (if thisblank
        (progn
          (beginning-of-line)
          (if singleblank (forward-line 1))
          (delete-region (point)
                         (if (re-search-backward "[^ \t\n]" nil t)
                             (progn (forward-line 1) (point))
                           (point-min)))))
    (if (not (and thisblank singleblank))
        (save-excursion
          (end-of-line)
          (forward-line 1)
          (delete-region (point)
                         (if (re-search-forward "[^ \t\n]" nil t)
                             (progn (beginning-of-line) (point))
                           (point-max)))))
    (if (looking-at "^[ \t]*\n\\'")
        (delete-region (point) (point-max)))))
(defun just-one-space (&optional n)
  "Delete all spaces and tabs around point, leaving one space (or N spaces).
If N is negative, delete newlines as well, leaving -N spaces."
  (let ((skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
        (num             (abs (or n 1))))
    (skip-chars-backward skip-characters)
    (let* ((num   (- num (skip-chars-forward " " (+ num (point)))))
           (mid   (point))
           (end   (progn
                    (skip-chars-forward skip-characters)
                    (point))))
      (delete-region mid end)
      (insert (make-string num ?\s)))))
;; subr.el `shell-quote-argument', POSIX branch: the ms-dos and windows-nt
;; branches are for `system-type's elisprs never runs as.
(defun shell-quote-argument (argument &optional _posix)
  "Quote ARGUMENT for passing as argument to an inferior POSIX shell."
  (if (equal argument "")
      "''"
    (string-replace
     "\n" "'\n'"
     (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))

;; ── round 32: buffer primitives and commands that were void ──
;; The C ones are written against their editfns.c / indent.c contracts; the
;; Lisp ones are ports of the 31.1 sources (simple.el, sort.el, tabify.el,
;; replace.el, subr.el, float-sup.el).
(defalias 'point-at-eol #'line-end-position)
(defalias 'point-at-bol #'line-beginning-position)
(defconst degrees-to-radians (/ float-pi 180.0)
  "Degrees to radian conversion constant.")
(defconst radians-to-degrees (/ 180.0 float-pi)
  "Radian to degree conversion constant.")
(defmacro degrees-to-radians (x)
  "Convert X from degrees to radians."
  (list '* degrees-to-radians x))
(defmacro radians-to-degrees (x)
  "Convert X from radians to degrees."
  (list '* radians-to-degrees x))
(defun function-alias-p (func &optional _noerror)
  "Return nil if FUNC is not a function alias.
If FUNC is a function alias, return the function alias chain."
  (let ((chain nil))
    (while (and (symbolp func)
                (setq func (symbol-function func))
                (symbolp func))
      (push func chain))
    (nreverse chain)))
(defun add-to-ordered-list (list-var element &optional order)
  "Add ELEMENT to the value of LIST-VAR if it isn't there yet, keeping the
list ordered by the numbers recorded in LIST-VAR's `list-order' property."
  (let ((ordering (get list-var 'list-order)))
    (unless ordering
      (put list-var 'list-order
           (setq ordering (make-hash-table :weakness 'key :test 'eq))))
    (when order
      (puthash element (and (numberp order) order) ordering))
    (unless (memq element (symbol-value list-var))
      (set list-var (cons element (symbol-value list-var))))
    (set list-var (sort (symbol-value list-var)
                        (lambda (a b)
                          (let ((oa (gethash a ordering))
                                (ob (gethash b ordering)))
                            (if (and oa ob)
                                (< oa ob)
                              oa)))))))
(defun insert-buffer-substring-no-properties (buffer &optional start end)
  "Insert before point a substring of BUFFER, without text properties."
  (let ((opoint (point)))
    (insert-buffer-substring buffer start end)
    (let ((inhibit-read-only t))
      (set-text-properties opoint (point) nil))))
(defun compare-buffer-substrings (buffer1 start1 end1 buffer2 start2 end2)
  "Compare two substrings of two buffers; return result as number.
editfns.c: -N if the first is less after N-1 equal characters, N if greater,
0 if equal; `case-fold-search' non-nil folds case."
  (let ((text (lambda (buffer start end)
                (with-current-buffer (if buffer (or (get-buffer buffer)
                                                    (error "No buffer named %s" buffer))
                                       (current-buffer))
                  (let ((b (or start (point-min))) (e (or end (point-max))))
                    (when (> b e) (setq b (prog1 e (setq e b))))
                    (unless (and (<= (point-min) b) (<= e (point-max)))
                      (signal 'args-out-of-range (list start end)))
                    (buffer-substring-no-properties b e))))))
    (let ((r (compare-strings (funcall text buffer1 start1 end1) nil nil
                              (funcall text buffer2 start2 end2) nil nil
                              case-fold-search)))
      (if (eq r t) 0 r))))
(defun current-word (&optional strict really-word)
  "Return the word at or near point, as a string, without text properties."
  (save-excursion
    (let* ((oldpoint (point)) (start (point)) (end (point))
           (syntaxes (if really-word "w" "w_"))
           (not-syntaxes (concat "^" syntaxes)))
      (skip-syntax-backward syntaxes) (setq start (point))
      (goto-char oldpoint)
      (skip-syntax-forward syntaxes) (setq end (point))
      (when (and (eq start oldpoint) (eq end oldpoint)
                 ;; Point is neither within nor adjacent to a word.
                 (not strict))
        ;; Look for preceding word in same line.
        (skip-syntax-backward not-syntaxes (line-beginning-position))
        (if (bolp)
            ;; No preceding word in same line.
            ;; Look for following word in same line.
            (progn
              (skip-syntax-forward not-syntaxes (line-end-position))
              (setq start (point))
              (skip-syntax-forward syntaxes)
              (setq end (point)))
          (setq end (point))
          (skip-syntax-backward syntaxes)
          (setq start (point))))
      ;; If we found something nonempty, return it as a string.
      (unless (= start end)
        (buffer-substring-no-properties start end)))))
(defun indent-line-to (column)
  "Indent current line to COLUMN."
  (beginning-of-line 1)
  (skip-chars-forward " \t")
  (let ((cur-col (current-column)))
    (cond ((< cur-col column)
           (if (>= (- column (* (/ cur-col tab-width) tab-width)) tab-width)
               (delete-region (point)
                              (progn (skip-chars-backward " ") (point))))
           (indent-to column))
          ((> cur-col column) ; too far right (after tab?)
           (delete-region (progn (move-to-column column t) (point))
                          ;; The `move-to-column' call may replace
                          ;; tabs with spaces, so we can't reuse the
                          ;; previous start point.
                          (progn (beginning-of-line 1)
                                 (skip-chars-forward " \t")
                                 (point)))))))

;; tabify.el
(defun untabify (start end &optional _arg)
  "Convert all tabs in region to multiple spaces, preserving columns."
  (let ((c (current-column)))
    (save-excursion
      (save-restriction
        (narrow-to-region (point-min) end)
        (goto-char start)
        (while (search-forward "\t" nil t)      ; faster than re-search
          (forward-char -1)
          (let ((tab-beg (point))
                (indent-tabs-mode nil)
                column)
            (skip-chars-forward "\t")
            (setq column (current-column))
            (delete-region tab-beg (point))
            (indent-to column)))))
    (move-to-column c)))
(defvar tabify-regexp " [ \t]+"
  "Regexp matching whitespace that tabify should consider.")
(defun tabify (start end &optional _arg)
  "Convert multiple spaces in region to tabs when possible."
  (save-excursion
    (save-restriction
      ;; Include the beginning of the line in the narrowing
      ;; since otherwise it will throw off current-column.
      (goto-char start)
      (beginning-of-line)
      (narrow-to-region (point) end)
      (goto-char start)
      (let ((indent-tabs-mode t))
        (while (re-search-forward tabify-regexp nil t)
          (let ((end-col (current-column))
                (beg-col (save-excursion (goto-char (match-beginning 0))
                                         (skip-chars-forward "\t")
                                         (current-column))))
            (if (= (/ end-col tab-width) (/ beg-col tab-width))
                nil
              (delete-region (match-beginning 0) (point))
              (indent-to end-col))))))))

;; replace.el: `keep-lines', `flush-lines', `how-many' (`count-matches').
;; The INTERACTIVE argument only adds the region default and a message.
(defcustom search-upper-case 'not-yanks
  "If non-nil, upper case chars disable case fold searching."
  :type '(choice (const :tag "off" nil) (const not-yanks) (other :tag "on" t)))
(defun isearch-no-upper-case-p (string regexp-flag)
  "Return t if there are no upper case chars in STRING."
  (let (quote-flag (i 0) (len (length string)) found)
    (while (and (not found) (< i len))
      (let ((char (aref string i)))
        (if (and regexp-flag (eq char ?\\))
            (setq quote-flag (not quote-flag))
          (if (and (not quote-flag) (not (eq char (downcase char))))
              (setq found t))
          (setq quote-flag nil)))
      (setq i (1+ i)))
    (not (or found
             (and regexp-flag (string-match "\\[:\\(upp\\|low\\)er:]" string)
                  (condition-case err
                      (progn
                        (string-match (substring string 0 (match-beginning 0))
                                      "")
                        nil)
                    (invalid-regexp
                     (equal "Unmatched [ or [^" (cadr err)))))))))
(defun keep-lines (regexp &optional rstart rend interactive)
  "Delete all lines except those containing matches for REGEXP."
  (if rstart
      (progn
        (goto-char (min rstart rend))
        (setq rend
              (progn
                (save-excursion
                  (goto-char (max rstart rend))
                  (unless (or (bolp) (eobp))
                    (forward-line 0))
                  (point-marker)))))
    (if (and interactive (use-region-p))
        (setq rstart (region-beginning)
              rend (progn
                     (goto-char (region-end))
                     (unless (or (bolp) (eobp))
                       (forward-line 0))
                     (point-marker)))
      (setq rstart (point)
            rend (point-max-marker)))
    (goto-char rstart))
  (save-excursion
    (or (bolp) (forward-line 1))
    (let ((start (point))
          (case-fold-search
           (if (and case-fold-search search-upper-case)
               (isearch-no-upper-case-p regexp t)
             case-fold-search)))
      (while (< (point) rend)
        ;; Start is first char not preserved by previous match.
        (if (not (re-search-forward regexp rend 'move))
            (delete-region start rend)
          (let ((end (save-excursion (goto-char (match-beginning 0))
                                     (forward-line 0)
                                     (point))))
            ;; Now end is first char preserved by the new match.
            (if (< start end)
                (delete-region start end))))
        (setq start (save-excursion (forward-line 1) (point)))
        ;; If the match was empty, avoid matching again at same place.
        (and (< (point) rend)
             (= (match-beginning 0) (match-end 0))
             (forward-char 1)))))
  (set-marker rend nil)
  nil)
(defun flush-lines (regexp &optional rstart rend interactive)
  "Delete lines containing matches for REGEXP; return the number deleted."
  (if rstart
      (progn
        (goto-char (min rstart rend))
        (setq rend (copy-marker (max rstart rend))))
    (if (and interactive (use-region-p))
        (setq rstart (region-beginning)
              rend (copy-marker (region-end)))
      (setq rstart (point)
            rend (point-max-marker)))
    (goto-char rstart))
  (let ((count 0)
        (case-fold-search
         (if (and case-fold-search search-upper-case)
             (isearch-no-upper-case-p regexp t)
           case-fold-search)))
    (save-excursion
      (while (and (< (point) rend)
                  (re-search-forward regexp rend t))
        (delete-region (save-excursion (goto-char (match-beginning 0))
                                       (forward-line 0)
                                       (point))
                       (progn (forward-line 1) (point)))
        (setq count (1+ count))))
    (set-marker rend nil)
    (when interactive (message (ngettext "Deleted %d matching line"
                                         "Deleted %d matching lines"
                                         count)
                               count))
    count))
(defalias 'count-matches 'how-many)

;; sort.el. `sort-reorder-buffer' copies through a temporary buffer exactly as
;; sort.el does; elisprs buffers carry no multibyte flag and no modified flag,
;; so `set-buffer-multibyte' and `with-buffer-unmodified-if-unchanged' have
;; nothing to preserve and are left out.
(defcustom sort-fold-case nil
  "Non-nil if the buffer sort functions should ignore case."
  :type 'boolean)
(defun sort-subr (reverse nextrecfun endrecfun
                          &optional startkeyfun endkeyfun predicate)
  "General text sorting routine to divide buffer into records and sort them."
  (save-excursion
    (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
                                         startkeyfun endkeyfun))
           (old (reverse sort-lists))
           (case-fold-search sort-fold-case))
      (if (null sort-lists)
          ()
        (or reverse (setq sort-lists (nreverse sort-lists)))
        (setq sort-lists
              (sort sort-lists
                    (cond (predicate
                           (lambda (a b) (funcall predicate (car a) (car b))))
                          ((numberp (car (car sort-lists)))
                           'car-less-than-car)
                          ((consp (car (car sort-lists)))
                           (lambda (a b)
                             (> 0 (compare-buffer-substrings
                                   nil (car (car a)) (cdr (car a))
                                   nil (car (car b)) (cdr (car b))))))
                          (t
                           (lambda (a b) (string< (car a) (car b)))))))
        (if reverse (setq sort-lists (nreverse sort-lists)))
        (sort-reorder-buffer sort-lists old))))
  nil)
(defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
  (let ((sort-lists ())
        (start-rec nil)
        done key)
    (while (not (eobp))
      (setq start-rec (point))          ;save record start
      (setq done nil)
      ;; Get key value, or move to start of key.
      (setq key (catch 'key
                  (or (and startkeyfun (funcall startkeyfun))
                      ;; If key was not returned as value,
                      ;; move to end of key and get key from the buffer.
                      (let ((start (point)))
                        (funcall (or endkeyfun
                                     (prog1 endrecfun (setq done t))))
                        (cons start (point))))))
      ;; Move to end of this record (start of next one, or end of buffer).
      (cond ((prog1 done (setq done nil)))
            (endrecfun (funcall endrecfun))
            (nextrecfun (funcall nextrecfun) (setq done t)))
      (if key (push
               ;; consing optimization in case in which key is same as record.
               (if (and (consp key)
                        (equal (car key) start-rec)
                        (equal (cdr key) (point)))
                   (cons key key)
                 (cons key (cons start-rec (point))))
               sort-lists))
      (and (not done) nextrecfun (funcall nextrecfun)))
    sort-lists))
(defun sort-reorder-buffer (sort-lists old)
  (let ((last (point-min))
        (min (point-min)) (max (point-max))
        (old-buffer (current-buffer))
        temp-buffer)
    (with-temp-buffer
      (setq temp-buffer (current-buffer))
      ;; Copy the sorted text into the temporary buffer.
      (while sort-lists
        (goto-char (point-max))
        (insert-buffer-substring old-buffer
                                 last
                                 (nth 1 (car old)))
        (goto-char (point-max))
        (insert-buffer-substring old-buffer
                                 (nth 1 (car sort-lists))
                                 (cdr (cdr (car sort-lists))))
        (setq last (cdr (cdr (car old)))
              sort-lists (cdr sort-lists)
              old (cdr old)))
      (goto-char (point-max))
      (insert-buffer-substring old-buffer last max)
      ;; Copy the reordered text from the temporary buffer
      ;; to the buffer we sorted (OLD-BUFFER).
      (set-buffer old-buffer)
      (let ((inhibit-quit t))
        ;; Leave the last character of the region so markers at its end stay.
        (delete-region min (1- max))
        ;; Now replace the one remaining old character with the sorted text.
        (goto-char (point-min))
        (insert-buffer-substring temp-buffer)
        (delete-region max (1+ max))))))
(defvar inhibit-field-text-motion nil)
(defun sort-lines (reverse beg end)
  "Sort lines in region alphabetically; REVERSE non-nil means descending order."
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (let ((inhibit-field-text-motion t))
        (sort-subr reverse 'forward-line 'end-of-line)))))
(defvar sort-numeric-base 10
  "The default base used by `sort-numeric-fields'.")
(defvar sort-fields-syntax-table nil)
(if sort-fields-syntax-table nil
  (let ((table (make-syntax-table))
        (i 0))
    (while (< i 256)
      (modify-syntax-entry i "w" table)
      (setq i (1+ i)))
    (modify-syntax-entry ?\s " " table)
    (modify-syntax-entry ?\t " " table)
    (modify-syntax-entry ?\n " " table)
    (modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
    (setq sort-fields-syntax-table table)))
(defun sort-numeric-fields (field beg end)
  "Sort lines in region numerically by the FIELDth field of each line."
  (let ((inhibit-field-text-motion t))
    (sort-fields-1
     field beg end
     (lambda ()
       ;; Don't try to parse blank lines (they'll be sorted at the start).
       (if (looking-at "[\t ]*$")
           0
         (sort-skip-fields field)
         (let* ((case-fold-search t)
                (base
                 (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
                     (cond ((match-beginning 1)
                            (goto-char (match-end 1))
                            16)
                           ((match-beginning 2)
                            (goto-char (match-end 2))
                            8)
                           (t nil)))))
           (string-to-number (buffer-substring (point)
                                               (save-excursion
                                                 (forward-sexp 1)
                                                 (point)))
                             (or base sort-numeric-base)))))
     nil)))
(defun sort-fields (field beg end)
  "Sort lines in region lexicographically by the FIELDth field of each line."
  (let ((inhibit-field-text-motion t))
    (sort-fields-1 field beg end
                   (lambda ()
                     (sort-skip-fields field)
                     nil)
                   (lambda () (skip-chars-forward "^ \t\n")))))
(defun sort-skip-fields (n)
  (if (> n 0)
      ;; Skip across N - 1 fields.
      (let ((i (1- n)))
        (while (> i 0)
          (skip-chars-forward " \t")
          (skip-chars-forward "^ \t\n")
          (setq i (1- i)))
        (skip-chars-forward " \t")
        (if (eolp)
            (error "Line has too few fields: %s"
                   (buffer-substring
                    (line-beginning-position)
                    (line-end-position)))))
    (end-of-line)
    ;; Skip back across - N - 1 fields.
    (let ((i (1- (- n))))
      (while (> i 0)
        (skip-chars-backward " \t")
        (skip-chars-backward "^ \t\n")
        (setq i (1- i)))
      (skip-chars-backward " \t"))
    (if (bolp)
        (error "Line has too few fields: %s"
               (buffer-substring
                (line-beginning-position)
                (line-end-position))))
    ;; Position at the front of the field even if moving backwards.
    (skip-chars-backward "^ \t\n")))
(defun sort-fields-1 (field beg end startkeyfun endkeyfun)
  (let ((tbl (syntax-table)))
    (if (zerop field) (setq field 1))
    (unwind-protect
        (save-excursion
          (save-restriction
            (narrow-to-region beg end)
            (goto-char (point-min))
            (set-syntax-table sort-fields-syntax-table)
            (sort-subr nil
                       'forward-line 'end-of-line
                       startkeyfun endkeyfun)))
      (set-syntax-table tbl))))
(defvar sort-regexp-fields-regexp)
(defvar sort-regexp-record-end)
(defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
  "Sort the text in the region lexicographically by REGEXP-defined records/keys."
  (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
         (setq key-regexp 0))
        ((string-match "\\`\\\\[1-9]\\'" key-regexp)
         (setq key-regexp (- (aref key-regexp 1) ?0))))
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (let (sort-regexp-record-end
            (sort-regexp-fields-regexp record-regexp))
        (re-search-forward sort-regexp-fields-regexp nil t)
        (setq sort-regexp-record-end (point))
        (goto-char (match-beginning 0))
        (sort-subr reverse
                   'sort-regexp-fields-next-record
                   (lambda ()
                     (goto-char sort-regexp-record-end))
                   (lambda ()
                     (let ((n 0))
                       (cond ((numberp key-regexp)
                              (setq n key-regexp))
                             ((re-search-forward
                               key-regexp sort-regexp-record-end t)
                              (setq n 0))
                             (t (throw 'key nil)))
                       (condition-case ()
                           (cons (match-beginning n)
                                 (match-end n))
                         ;; if there was no such register
                         (error (throw 'key nil))))))))))
(defun sort-regexp-fields-next-record ()
  (let ((oldpos (point)))
    (and (re-search-forward sort-regexp-fields-regexp nil 'move)
         (setq sort-regexp-record-end (match-end 0))
         (if (= sort-regexp-record-end oldpos)
             (progn
               (forward-char 1)
               (re-search-forward sort-regexp-fields-regexp nil 'move)
               (setq sort-regexp-record-end (match-end 0)))
           t)
         (goto-char (match-beginning 0)))))
(defun reverse-region (beg end)
  "Reverse the order of lines in a region."
  (if (> beg end)
      (let (mid) (setq mid end end beg beg mid)))
  (save-excursion
    ;; Put beg at the start of a line and end and the end of one --
    ;; the largest possible region which fits this criteria.
    (goto-char beg)
    (or (bolp) (forward-line 1))
    (setq beg (point))
    (goto-char end)
    (or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
    (setq end (point-marker))
    (when (<= end beg)
      (user-error "There are no full lines in the region"))
    (let (ll (do t))
      (while do
        (goto-char beg)
        (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
                       ll))
        (setq do (/= (point) end))
        (delete-region beg (if do (1+ (point)) (point))))
      (while (cdr ll)
        (insert (car ll) "\n")
        (setq ll (cdr ll)))
      (insert (car ll)))))
(defun delete-duplicate-lines (beg end &optional reverse adjacent keep-blanks
                               interactive)
  "Delete all but one copy of any identical lines in the region; return count."
  (let ((lines (unless adjacent (make-hash-table :test 'equal)))
        line prev-line first-line
        (count 0)
        (beg (copy-marker beg))
        (end (copy-marker end)))
    (save-excursion
      (goto-char (if reverse end beg))
      (if (and reverse (bolp)) (forward-char -1))
      (while (if reverse
                 (not first-line)
               (and (< (point) end) (not (eobp))))
        (setq first-line (and reverse (or (<= (point) beg) (bobp))))
        (setq line (buffer-substring-no-properties
                    (line-beginning-position) (line-end-position)))
        (if (and keep-blanks (string= "" line))
            (forward-line 1)
          (if (if adjacent (equal line prev-line) (gethash line lines))
              (progn
                (delete-region (progn (forward-line 0) (point))
                               (progn (forward-line 1) (point)))
                (if reverse (forward-line -1))
                (setq count (1+ count)))
            (if adjacent (setq prev-line line) (puthash line t lines))
            (forward-line (if reverse -1 1))))))
    (set-marker beg nil)
    (set-marker end nil)
    (when interactive
      (message "Deleted %d %sduplicate line%s%s"
               count
               (if adjacent "adjacent " "")
               (if (= count 1) "" "s")
               (if reverse " backward" "")))
    count))

(defun forward-comment (count)
  "Move forward across up to COUNT comments.  If COUNT is negative, move backward.
Stop scanning if we find something other than a comment or whitespace.
Set point to where scanning stops.
If COUNT comments are found as expected, with nothing except whitespace
between them, return t; otherwise return nil."
  (unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
  (let* ((stop (if (> count 0) (point-max) (point-min)))
         (from (point))
         (comstyle 0) (comnested nil) (count1 count)
         c c1 code syntax other-syntax comstart-first found res quoted
         (fence-found nil) ini)
    (catch '--fc--
      (while (> count1 0)
        (setq code nil)
        (while (or (null code) (= code 0) (and (= code 12) (eq c ?\n)))
          (when (= from stop) (goto-char from) (throw '--fc-- nil))
          (setq c (char-after from))
          (setq syntax (--syntax-flags-at-- from c))
          (setq code (logand syntax 255))
          (setq comstart-first (--syn-comstart-first-- syntax))
          (setq comnested (--syn-nested-- syntax))
          (setq comstyle (--syn-comment-style-- syntax 0))
          (setq from (1+ from))
          (when (and (< from stop) comstart-first)
            (setq c1 (char-after from))
            (setq other-syntax (--syntax-flags-at-- from c1))
            (when (--syn-comstart-second-- other-syntax)
              (setq code 11)
              (setq comstyle (--syn-comment-style-- other-syntax syntax))
              (setq comnested (or comnested (--syn-nested-- other-syntax)))
              (setq from (1+ from)))))
        (cond ((= code 14) (setq comstyle --st-comment-style--))
              ((/= code 11)
               (setq from (1- from))
               (goto-char from)
               (throw '--fc-- nil)))
        (setq res (--forw-comment-- from stop (if comnested 1 0) comstyle 0))
        (setq from (nth 1 res))
        (unless (nth 0 res) (goto-char from) (throw '--fc-- nil))
        (setq from (1+ from))
        (setq count1 (1- count1)))

      (while (< count1 0)
        (catch '--fc-one--
          (while t
            (when (<= from stop) (goto-char (point-min)) (throw '--fc-- nil))
            (setq from (1- from))
            (setq quoted (--char-quoted-- from))
            (setq c (char-after from))
            (setq syntax (--syntax-flags-at-- from c))
            (setq code (logand syntax 255))
            (setq comstyle 0)
            (setq comnested (--syn-nested-- syntax))
            (when (= code 12) (setq comstyle (--syn-comment-style-- syntax 0)))
            (when (and (> from stop) (--syn-comend-second-- syntax)
                       (--prev-char-comend-first-- from)
                       (not (--char-quoted-- (1- from))))
              (setq from (1- from))
              (setq code 12)
              (setq c1 (char-after from))
              (setq other-syntax (--syntax-flags-at-- from c1))
              (setq comstyle (--syn-comment-style-- other-syntax syntax))
              (setq comnested (or comnested (--syn-nested-- other-syntax))))
            (cond
             ((= code 14)                        ; Scomment_fence
              (setq fence-found nil)
              (setq ini from)
              (when (> from stop)
                (catch '--fc-fence--
                  (while t
                    (setq from (1- from))
                    (setq c (char-after from))
                    (cond ((and (= (--syntax-code-at-- from c) 14)
                                (not (--char-quoted-- from)))
                           (setq fence-found t)
                           (throw '--fc-fence-- nil))
                          ((= from stop) (throw '--fc-fence-- nil))))))
              (if fence-found
                  (throw '--fc-one-- nil)
                (setq from ini)
                (setq from (1+ from))
                (goto-char from)
                (throw '--fc-- nil)))
             ((= code 12)                        ; Sendcomment
              (setq found (and (or (not quoted) (not comment-end-can-be-escaped))
                               (--back-comment-- from stop comnested comstyle)))
              (if (and found (nth 0 found))
                  (progn (setq from (nth 1 found)) (throw '--fc-one-- nil))
                (unless (eq c ?\n)
                  ;; Go back to the end of this not-quite-endcomment.
                  (when (/= (--syntax-code-at-- from (char-after from)) code)
                    (setq from (1+ from)))
                  (setq from (1+ from))
                  (goto-char from)
                  (throw '--fc-- nil))))
             ((or (/= code 0) quoted)
              (setq from (1+ from))
              (goto-char from)
              (throw '--fc-- nil)))))
        (setq count1 (1+ count1)))
      (goto-char from)
      t)))

;; ---- parse-partial-sexp (syntax.c Fparse_partial_sexp) ----
(defun parse-partial-sexp (from to &optional targetdepth stopbefore oldstate commentstop)
  "Parse Lisp syntax starting at FROM until TO; return status of parse at TO.
Parsing stops at TO or when certain criteria are met;
 point is set to where parsing stops.

If OLDSTATE is omitted or nil, parsing assumes that FROM is the
 beginning of a function.  If not, OLDSTATE should be the state at FROM."
  (let ((target (if targetdepth
                    (progn
                      (unless (integerp targetdepth)
                        (signal 'wrong-type-argument (list 'fixnump targetdepth)))
                      targetdepth)
                  --pps-no-target--))
        (f (if (markerp from) (marker-position from) from))
        (t2 (if (markerp to) (marker-position to) to))
        state)
    (when (< t2 f) (error "End position is smaller than start position"))
    ;; `validate_region' (editfns.c) rejects an out-of-range pair outright --
    ;; it does not clamp -- and names the buffer and the arguments AS PASSED:
    ;;   (parse-partial-sexp 1 40) in an empty buffer
    ;;     => (args-out-of-range #<buffer *scratch*> 1 40)
    ;; Clamping instead makes the call answer a plausible state for a region
    ;; that does not exist.
    (unless (and (<= (point-min) f) (<= t2 (point-max)))
      (signal 'args-out-of-range (list (current-buffer) from to)))
    (setq state (--pps-internalize-- oldstate))
    (--scan-sexps-forward-- state f t2 target (and stopbefore t)
                            (cond ((null commentstop) 0)
                                  ((eq commentstop 'syntax-table) -1)
                                  (t 1)))
    (goto-char (--pps-location-- state))
    (list (--pps-depth-- state)
          (if (< (--pps-prevlevelstart-- state) 0) nil (--pps-prevlevelstart-- state))
          (if (< (--pps-thislevelstart-- state) 0) nil (--pps-thislevelstart-- state))
          (if (>= (--pps-instring-- state) 0)
              (if (= (--pps-instring-- state) --st-string-style--)
                  t
                (--pps-instring-- state))
            nil)
          (cond ((< (--pps-incomment-- state) 0) t)
                ((= (--pps-incomment-- state) 0) nil)
                (t (--pps-incomment-- state)))
          (and (--pps-quoted-- state) t)
          (--pps-mindepth-- state)
          (if (= (--pps-comstyle-- state) 0)
              nil
            (if (= (--pps-comstyle-- state) --st-comment-style--)
                'syntax-table
              (--pps-comstyle-- state)))
          (if (or (/= (--pps-incomment-- state) 0)
                  (>= (--pps-instring-- state) 0))
              (--pps-comstr-start-- state)
            nil)
          (--pps-levelstarts-- state)
          (if (= (--pps-prev-syntax-- state) --syn-smax--)
              nil
            (--pps-prev-syntax-- state)))))

;; ---- cl-macs.el (31.1) lambda-list machinery, verbatim ----
;; `cl-defun', `cl-defmacro' and `cl-function' are `cl--transform-lambda': the
;; leading plain arguments stay in the lambda list (so a simple arglist is an
;; ordinary function and its arity errors name the closure), the rest arrive as
;; `&rest --cl-rest--' and are parsed by the code `cl--do-arglist' generates,
;; which signals `(wrong-number-of-arguments NAME N)' and the keyword errors
;; Emacs signals; and the body is wrapped in `(cl-block NAME ...)'. Placed
;; before the first top-level `cl-defstruct' (`ppss', below), whose
;; constructor is a `cl-defsubst', because
;; elisprs expands macros when a form is defined.
;; macroexp.el, needed by `cl--transform-lambda' at the first expansion.
(defun macroexp-parse-body (body)
  "Parse a function BODY into (DECLARATIONS . EXPS)."
  (let ((decls ()))
    (while
        (and body
             (let ((e (car body)))
               (or (and (stringp e) (cdr body))
                   (memq (car-safe e)
                         '(:documentation declare interactive cl-declare)))))
      (push (pop body) decls))
    (cons (nreverse decls) body)))
(defvar cl--bind-block) (defvar cl--bind-defs) (defvar cl--bind-enquote)
(defvar cl--bind-lets) (defvar cl--bind-forms)
(defconst cl--lambda-list-keywords
  '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
;; cl-macs.el: the variables a cl lambda list binds -- what `cl-defstruct' uses
;; to tell a slot that a constructor argument names from one it fills itself.
(defun cl--arglist-args (args)
  (if (nlistp args) (list args)
    (let ((res nil) (kind nil) arg)
      (while (consp args)
	(setq arg (pop args))
	(if (memq arg cl--lambda-list-keywords) (setq kind arg)
	  (if (eq arg '&cl-defs) (pop args)
	    (and (consp arg) kind (setq arg (car arg)))
	    (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
	    (setq res (nconc res (cl--arglist-args arg))))))
      (nconc res (and args (list args))))))
(defmacro cl--pop2 (place)
  `(prog1 (car (cdr ,place))
     (setq ,place (cdr (cdr ,place)))))
(defun cl--const-expr-p (x)
  "Check if X is constant (i.e., no side effects or dependencies).

See `macroexp-const-p' for similar functionality without cl-lib dependency."
  (cond ((consp x)
	 (or (eq (car x) 'quote)
	     (and (memq (car x) '(function cl-function))
		  (or (symbolp (nth 1 x))
		      (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
	((symbolp x) (and (memq x '(nil t)) t))
	(t t)))
(defun cl--const-expr-val (x)
  "Return the value of X known at compile-time.
If X is not known at compile time, return nil.  Before testing
whether X is known at compile time, macroexpand it completely in
`macroexpand-all-environment'."
  (let ((x (macroexpand-all x macroexpand-all-environment)))
    (if (macroexp-const-p x)
        (if (consp x) (nth 1 x) x))))
;; macroexp.el (31.1).
(defun macroexp--dynamic-variable-p (var)
  "Whether the variable VAR is dynamically scoped.
Only valid during macro-expansion."
  (or (not lexical-binding)
      (special-variable-p var)
      (memq var macroexp--dynvars)
      (and (boundp 'byte-compile-bound-variables)
           (memq var byte-compile-bound-variables))))
(defun cl--slet (bindings body &optional nowarn)
  "Like `cl--slet*' but for \"parallel let\"."
  (let ((dyns nil)) ;Vars declared as dynbound among the bindings?
    (when lexical-binding
      (dolist (binding bindings) ;; `seq-some' lead to bootstrap problems.
        (when (macroexp--dynamic-variable-p (car binding))
          (push (car binding) dyns))))
    (cond
     (dyns
      (let ((form `(funcall (lambda (,@(mapcar #'car bindings))
                              ,@(macroexp-unprogn body))
                            ,@(mapcar #'cadr bindings))))
        (if (not nowarn) form
          `(with-suppressed-warnings ((lexical ,@dyns)) ,form))))
     ((null (cdr bindings))
      (macroexp-let* bindings body))
     (t `(let ,bindings ,@(macroexp-unprogn body))))))

(defun cl--slet* (bindings body)
  "Like `macroexp-let*' but uses static scoping for all the BINDINGS."
  (if (null bindings) body
    (cl--slet `(,(car bindings)) (cl--slet* (cdr bindings) body))))

(defun cl--transform-lambda (form bind-block)
  "Transform a function form FORM of name BIND-BLOCK.
BIND-BLOCK is the name of the symbol to which the function will be bound,
and which will be used for the name of the `cl-block' surrounding the
function's body.
FORM is of the form (ARGS . BODY)."
  (let* ((args (car form)) (body (cdr form)) (orig-args args)
	 (cl--bind-block bind-block) (cl--bind-defs nil) (cl--bind-enquote nil)
         (parsed-body (macroexp-parse-body body))
	 (header (car parsed-body)) (simple-args nil))
    (setq body (cdr parsed-body))
    ;; "(. X) to (&rest X)" conversion already done in cl--do-arglist, but we
    ;; do it here as well, so as to be able to see if we can avoid
    ;; cl--do-arglist.
    (setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
    (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
    (let ((cl-defs (memq '&cl-defs args)))
      (when cl-defs
        (setq cl--bind-defs (cadr cl-defs))
	;; Remove "&cl-defs DEFS" from args.
        (setcdr cl-defs (cddr cl-defs))
	(setq args (delq '&cl-defs args))))
    (if (setq cl--bind-enquote (memq '&cl-quote args))
	(setq args (delq '&cl-quote args)))
    (if (memq '&whole args) (error "&whole not currently implemented"))
    (let* ((p (memq '&environment args))
           (v (cadr p)))
      (if p (setq args (nconc (delq (car p) (delq v args))
                              `(&aux (,v macroexpand-all-environment))))))
    ;; Take away all the simple args whose parsing can be handled more
    ;; efficiently by a plain old `lambda' than the manual parsing generated
    ;; by `cl--do-arglist'.
    (let ((optional nil))
      (while (and args (symbolp (car args))
                  (not (memq (car args) '(nil &rest &body &key &aux)))
                  (or (not optional)
                      ;; Optional args whose default is nil are simple.
                      (null (nth 1 (assq (car args) (cdr cl--bind-defs)))))
                  (not (and (eq (car args) '&optional) (setq optional t)
                            (car cl--bind-defs))))
        (push (pop args) simple-args))
      (when optional
        (if args (push '&optional args))
        ;; Don't keep a dummy trailing &optional without actual optional args.
        (if (eq '&optional (car simple-args)) (pop simple-args))))
    (or (eq cl--bind-block 'cl-none)
	(setq body (list `(cl-block ,cl--bind-block ,@body))))
    (let* ((cl--bind-lets nil) (cl--bind-forms nil)
           (rest-args
            (cond
             ((null args) nil)
             ((eq (car args) '&aux)
              (cl--do-&aux args)
              (setq cl--bind-lets (nreverse cl--bind-lets))
              nil)
             (t ;; `simple-args' doesn't handle all the parsing that we need,
              ;; so we pass the rest to cl--do-arglist which will do
              ;; "manual" parsing.
              (let ((slen (length simple-args))
                    (usage-str
                     ;; Macro expansion can take place in the middle of
                     ;; apparently harmless computation, so it should not
                     ;; touch the match-data.
                     (save-match-data
                       ;; (require (quote help)) -- help.el is preloaded.
                       (help--docstring-quote
                        (let ((print-gensym nil) (print-quoted t)
                              (print-escape-newlines t))
                          (format "%S" (cons 'fn (cl--make-usage-args
                                                  orig-args))))))))
                (when (memq '&optional simple-args)
                  (decf slen))
                (setq header
                      (cons
                       (if (eq :documentation (car-safe (car header)))
                           `(:documentation (help-add-fundoc-usage
                                             ,(cadr (pop header))
                                             ,usage-str))
                         (help-add-fundoc-usage
                          (if (stringp (car header)) (pop header))
                          ;; Be careful with make-symbol and (back)quote,
                          ;; see bug#12884.
                          usage-str))
                       header))
                ;; FIXME: we'd want to choose an arg name for the &rest param
                ;; and pass that as `expr' to cl--do-arglist, but that ends up
                ;; generating code with a redundant let-binding, so we instead
                ;; pass a dummy and then look in cl--bind-lets to find what var
                ;; this was bound to.
                (cl--do-arglist args :dummy slen)
                (setq cl--bind-lets (nreverse cl--bind-lets))
                ;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
                (list '&rest (car (pop cl--bind-lets))))))))
      `((,@(nreverse simple-args) ,@rest-args)
        ,@header
        ;; Function arguments are unconditionally statically scoped (bug#47552).
        ,(cl--slet* cl--bind-lets
                    (macroexp-progn
                     `(,@(nreverse cl--bind-forms)
                       ,@body)))))))

(defmacro cl-defun (name args &rest body)
  "Define NAME as a function.
Like normal `defun', except ARGLIST allows full Common Lisp conventions,
and BODY is implicitly surrounded by (cl-block NAME ...).

\(fn NAME ARGLIST [DOCSTRING] BODY...)"
  (declare (doc-string 3) (indent 2))
  `(defun ,name ,@(cl--transform-lambda (cons args body) name)))

(defmacro cl-defmacro (name args &rest body)
  "Define NAME as a macro.
Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
and BODY is implicitly surrounded by (cl-block NAME ...).

\(fn NAME ARGLIST [DOCSTRING] BODY...)"
  (declare (doc-string 3) (indent 2))
  `(defmacro ,name ,@(cl--transform-lambda (cons args body) name)))

(defmacro cl-function (func)
  "Introduce a function.
Like normal `function', except that if argument is a lambda form,
its argument list allows full Common Lisp conventions."
  (if (eq (car-safe func) 'lambda)
      `(function (lambda . ,(cl--transform-lambda (cdr func) 'cl-none)))
    `(function ,func)))

(defun cl--make-usage-var (x)
  "X can be a var or a (destructuring) lambda-list."
  (cond
   ((symbolp x) (make-symbol (upcase (symbol-name x))))
   ((consp x) (cl--make-usage-args x))
   (t x)))

(defun cl--make-usage-args (arglist)
  (let ((aux (ignore-errors (cl-position '&aux arglist))))
    (when aux
      ;; `&aux' args aren't arguments, so let's just drop them from the
      ;; usage info.
      (setq arglist (take aux arglist))))
  (if (not (proper-list-p arglist))
      (let* ((last (last arglist))
             (tail (cdr last)))
        (unwind-protect
            (progn
              (setcdr last nil)
              (nconc (cl--make-usage-args arglist) (cl--make-usage-var tail)))
          (setcdr last tail)))
    ;; `orig-args' can contain &cl-defs.
    (let ((x (memq '&cl-defs arglist)))
      (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
    (let ((state nil))
      (mapcar (lambda (x)
                (cond
                 ((symbolp x)
                  (let ((first (aref (symbol-name x) 0)))
                    (if (eq ?\& first)
                        (setq state x)
                      ;; Strip a leading underscore, since it only
                      ;; means that this argument is unused.
                      (make-symbol (upcase (if (eq ?_ first)
                                               (substring (symbol-name x) 1)
                                             (symbol-name x)))))))
                 ((not (consp x)) x)
                 ((memq state '(nil &rest)) (cl--make-usage-args x))
                 (t      ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
                  (cl-list*
                   (if (and (consp (car x)) (eq state '&key))
                       (list (caar x) (cl--make-usage-var (nth 1 (car x))))
                     (cl--make-usage-var (car x)))
                   (nth 1 x)                        ;INITFORM.
                   (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
                   ))))
              arglist))))

(defun cl--do-&aux (args)
  (while (and (eq (car args) '&aux) (pop args))
    (while (and args (not (memq (car args) cl--lambda-list-keywords)))
      (if (consp (car args))
          (if (and cl--bind-enquote (cadar args))
              (cl--do-arglist (caar args)
                              `',(cadr (pop args)))
            (cl--do-arglist (caar args) (cadr (pop args))))
        (cl--do-arglist (pop args) nil))))
  (if args (error "Malformed argument list ends with: %S" args)))

(defun cl--do-arglist (args expr &optional num)   ; uses cl--bind-*
  (if (nlistp args)
      (if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
	  (error "Invalid argument name: %s" args)
	(push (list args expr) cl--bind-lets))
    (setq args (cl-copy-list args))
    (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
    (let ((p (memq '&body args))) (if p (setcar p '&rest)))
    (if (memq '&environment args) (error "&environment used incorrectly"))
    (let ((restarg (memq '&rest args))
	  (safety (if (macroexp-compiling-p) cl--optimize-safety 3))
	  (keys t)
	  (laterarg nil) (exactarg nil) minarg)
      (or num (setq num 0))
      (setq restarg (if (listp (cadr restarg))
                        (make-symbol "--cl-rest--")
                      (cadr restarg)))
      (push (list restarg expr) cl--bind-lets)
      (if (eq (car args) '&whole)
	  (push (list (cl--pop2 args) restarg) cl--bind-lets))
      (let ((p args))
	(setq minarg restarg)
	(while (and p (not (memq (car p) cl--lambda-list-keywords)))
	  (or (eq p args) (setq minarg (list 'cdr minarg)))
	  (setq p (cdr p)))
	(if (memq (car p) '(nil &aux))
	    (setq minarg `(= (length ,restarg)
                             ,(length (cl-ldiff args p)))
		  exactarg (not (eq args p)))))
      (while (and args (not (memq (car args) cl--lambda-list-keywords)))
	(let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car-safe)
			    restarg)))
	  (cl--do-arglist
	   (pop args)
	   (if (or laterarg (= safety 0)) poparg
	     `(if ,minarg ,poparg
                (signal 'wrong-number-of-arguments
                        (list ,(and (not (eq cl--bind-block 'cl-none))
                                    `',cl--bind-block)
                              (length ,restarg)))))))
	(setq num (1+ num) laterarg t))
      (while (and (eq (car args) '&optional) (pop args))
	(while (and args (not (memq (car args) cl--lambda-list-keywords)))
	  (let ((arg (pop args)))
	    (or (consp arg) (setq arg (list arg)))
	    (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
	    (let ((def (if (cdr arg) (nth 1 arg)
			 (or (car cl--bind-defs)
			     (nth 1 (assq (car arg) cl--bind-defs)))))
		  (poparg `(pop ,restarg)))
	      (and def cl--bind-enquote (setq def `',def))
	      (cl--do-arglist (car arg)
			     (if def `(if ,restarg ,poparg ,def) poparg))
	      (setq num (1+ num))))))
      (if (eq (car args) '&rest)
	  (let ((arg (cl--pop2 args)))
	    (if (consp arg) (cl--do-arglist arg restarg)))
	(or (eq (car args) '&key) (= safety 0) exactarg
	    (push `(if ,restarg
                       (signal 'wrong-number-of-arguments
                               (list
                                ,(and (not (eq cl--bind-block 'cl-none))
                                      `',cl--bind-block)
                                (+ ,num (length ,restarg)))))
                  cl--bind-forms)))
      (while (and (eq (car args) '&key) (pop args))
        (unless (listp keys) (setq keys nil))
	(while (and args (not (memq (car args) cl--lambda-list-keywords)))
	  (let ((arg (pop args)))
	    (or (consp arg) (setq arg (list arg)))
	    (let* ((karg (if (consp (car arg)) (caar arg)
                           (let ((name (symbol-name (car arg))))
                             ;; Strip a leading underscore, since it only
                             ;; means that this argument is unused, but
                             ;; shouldn't affect the key's name (bug#12367).
                             (if (eq ?_ (aref name 0))
                                 (setq name (substring name 1)))
                             (intern (format ":%s" name)))))
                   (varg (if (consp (car arg)) (cadar arg) (car arg)))
		   (def (if (cdr arg) (cadr arg)
                          ;; The ordering between those two or clauses is
                          ;; irrelevant, since in practice only one of the two
                          ;; is ever non-nil (the car is only used for
                          ;; cl-deftype which doesn't use the cdr).
			  (or (car cl--bind-defs)
                              (cadr (assq varg cl--bind-defs)))))
                   (look `(plist-member ,restarg ',karg)))
	      (and def cl--bind-enquote (setq def `',def))
	      (if (cddr arg)
		  (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
			 (val `(car (cdr ,temp))))
		    (cl--do-arglist temp look)
		    (cl--do-arglist varg
				   `(if ,temp
                                        (prog1 ,val (setq ,temp t))
                                      ,def)))
		(cl--do-arglist
		 varg
		 `(car (cdr ,(if (null def)
				 look
			       `(or ,look
                                    ,(if (eq (cl--const-expr-p def) t)
					 `'(nil ,(cl--const-expr-val def))
				       `(list nil ,def))))))))
	      (push karg keys)))))
      (when (consp keys) (setq keys (nreverse keys)))
      (or (and (eq (car args) '&allow-other-keys) (pop args))
	  (= safety 0)
          (cond
           ((eq keys t) nil)            ;No &keys at all
           ((null keys)                 ;A &key but no actual keys specified.
            (push `(when ,restarg
                     (error ,(format "Keyword argument %%S not one of %S"
                                     keys)
                            (car ,restarg)))
                  cl--bind-forms))
           (t
	    (let* ((var (make-symbol "--cl-keys--"))
		   (allow '(:allow-other-keys))
		   (check `(while ,var
                             (cond
                              ((memq (car ,var) ',(append keys allow))
                               (unless (cdr ,var)
                                 (error "Missing argument for %s" (car ,var)))
                               (setq ,var (cdr (cdr ,var))))
                              ((car (cdr (memq (quote ,@allow) ,restarg)))
                               (setq ,var nil))
                              (t
                               (error
                                ,(format "Keyword argument %%S not one of %S"
                                         keys)
                                (car ,var)))))))
	      (push `(let ((,var ,restarg)) ,check) cl--bind-forms)))))
      (cl--do-&aux args)
      nil)))


;; ---- syntax.el: the ppss accessors, syntax-propertize and syntax-ppss ----
(cl-defstruct (ppss (:constructor make-ppss) (:copier nil) (:type list))
  (depth nil) (innermost-start nil) (last-complete-sexp-start nil)
  (string-terminator nil) (comment-depth nil) (quoted-p nil)
  (min-depth nil) (comment-style nil) (comment-or-string-start nil)
  (open-parens nil) (two-character-syntax nil))

(defvar-local syntax-propertize-function nil
  "Mode-specific function to apply `syntax-table' text properties.")
(defvar-local syntax-propertize--done -1
  "Position up to which syntax-table properties have been set.")
(defvar-local syntax-ppss-table nil
  "Syntax-table to use during `syntax-ppss', if any.")

(defun syntax-propertize (pos)
  "Ensure that syntax-table properties are set until POS (a buffer point)."
  (when (and syntax-propertize-function
             (< syntax-propertize--done pos))
    (let ((start (max (point-min) syntax-propertize--done))
          (end (min (point-max) pos)))
      (setq syntax-propertize--done end)
      (save-excursion (funcall syntax-propertize-function start end))))
  nil)

(defun syntax-ppss-depth (ppss) (nth 0 ppss))

(defun syntax-ppss-toplevel-pos (ppss)
  "Get the latest syntactically outermost position found in a syntactic scan.
PPSS is a scan state, as returned by `parse-partial-sexp' or `syntax-ppss'."
  (or (car (nth 9 ppss)) (nth 8 ppss)))

(defun syntax-ppss-context (ppss)
  "Say whether PPSS is a string, a comment, or something else."
  (cond ((nth 3 ppss) 'string) ((nth 4 ppss) 'comment) (t nil)))

(defun syntax-ppss-flush-cache (_beg &rest _ignored)
  "Flush the `syntax-ppss' cache from BEG onward."
  nil)

;; NAMED boundary: Emacs memoizes the parse in `syntax-ppss-last' and
;; `syntax-ppss-cache' and restarts from the nearest cached position, so its
;; elements 2 and 6 depend on where the cache happened to have an entry -- which
;; is exactly why its docstring says those two "cannot be relied upon".  This
;; parses from `point-min' every time, which is what Emacs itself does on a cold
;; cache, so every element including 2 and 6 matches a first call in a fresh
;; buffer.  The difference is speed, and element 2/6 drift that Emacs already
;; disclaims.
(defun syntax-ppss (&optional pos)
  "Parse-Partial-Sexp State at POS, defaulting to point.
If POS is given, this function moves point to POS.

The returned value is the same as that of `parse-partial-sexp'
run from `point-min' to POS except that values at positions 2 and 6
in the returned list (counting from 0) cannot be relied upon."
  (unless pos (setq pos (point)))
  (syntax-propertize pos)
  (with-syntax-table (or syntax-ppss-table (syntax-table))
    (parse-partial-sexp (point-min) pos)))

;; ---- lisp.el: sexp and list motion ----
(defvar forward-sexp-function nil
  "If non-nil, `forward-sexp' delegates to this function.
Should take the same arguments and behave similarly to `forward-sexp'.")

(defun forward-sexp-default-function (&optional arg)
  "Default function for `forward-sexp-function'."
  (goto-char (or (scan-sexps (point) arg) (buffer-end arg)))
  (if (< arg 0) (backward-prefix-chars)))

(defun forward-sexp (&optional arg interactive)
  "Move forward across one balanced expression (sexp).
With ARG, do it that many times.  Negative arg -N means move
backward across N balanced expressions.  This command assumes
point is not in a string or comment.  Calls
`forward-sexp-function' to do the work, if that is non-nil."
  (if interactive
      (condition-case _
          (forward-sexp arg nil)
        (scan-error (user-error (if (> arg 0) "No next sexp" "No previous sexp"))))
    (or arg (setq arg 1))
    (if forward-sexp-function
        (funcall forward-sexp-function arg)
      (forward-sexp-default-function arg))))

(defun backward-sexp (&optional arg interactive)
  "Move backward across one balanced expression (sexp).
With ARG, do it that many times.  Negative arg -N means
move forward across N balanced expressions."
  (or arg (setq arg 1))
  (forward-sexp (- arg) interactive))

(defun forward-list (&optional arg interactive)
  "Move forward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move backward across N groups of parentheses."
  (if interactive
      (condition-case _
          (forward-list arg nil)
        (scan-error (user-error (if (> arg 0) "No next group" "No previous group"))))
    (or arg (setq arg 1))
    (goto-char (or (scan-lists (point) arg 0) (buffer-end arg)))))

(defun backward-list (&optional arg interactive)
  "Move backward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move forward across N groups of parentheses."
  (or arg (setq arg 1))
  (forward-list (- arg) interactive))

(defun down-list (&optional arg interactive)
  "Move forward down one level of parentheses.
With ARG, do this that many times.
A negative argument means move backward but still go down a level."
  (when (ppss-comment-or-string-start (syntax-ppss))
    (user-error "This command doesn't work in strings or comments"))
  (if interactive
      (condition-case _
          (down-list arg nil)
        (scan-error (user-error "At bottom level")))
    (or arg (setq arg 1))
    (let ((inc (if (> arg 0) 1 -1)))
      (while (/= arg 0)
        (goto-char (or (scan-lists (point) inc -1) (buffer-end arg)))
        (setq arg (- arg inc))))))

(defun backward-up-list (&optional arg escape-strings no-syntax-crossing)
  "Move backward out of one level of parentheses.
With ARG, do this that many times.  A negative argument means move
forward but still to a less deep spot."
  (up-list (- (or arg 1)) escape-strings no-syntax-crossing))

(defun up-list (&optional arg escape-strings no-syntax-crossing)
  "Move forward out of one level of parentheses.
With ARG, do this that many times.  A negative argument means move
backward but still to a less deep spot."
  (or arg (setq arg 1))
  (let ((inc (if (> arg 0) 1 -1))
        (pos nil))
    (while (/= arg 0)
      (condition-case err
          (save-restriction
            ;; If we've been asked not to cross string boundaries and we're
            ;; inside a string, narrow to that string so that scan-lists
            ;; doesn't find a match in a different string.
            (when no-syntax-crossing
              (let* ((syntax (syntax-ppss))
                     (string-comment-start (nth 8 syntax)))
                (when string-comment-start
                  (save-excursion
                    (goto-char string-comment-start)
                    (narrow-to-region
                     (point)
                     (if (nth 3 syntax)
                         (condition-case nil
                             (progn (forward-sexp) (point))
                           (scan-error (point-max)))
                       (forward-comment 1)
                       (point)))))))
            (if (null forward-sexp-function)
                (goto-char (or (scan-lists (point) inc 1) (buffer-end arg)))
              (condition-case err2
                  (while (progn (setq pos (point))
                                (forward-sexp inc)
                                (/= (point) pos)))
                (scan-error (goto-char (nth (if (> arg 0) 3 2) err2))))
              (if (= (point) pos)
                  (signal 'scan-error
                          (list "Unbalanced parentheses" (point) (point))))))
        (scan-error
         (let ((syntax nil))
           (or
            (and escape-strings
                 (or syntax (setq syntax (syntax-ppss)))
                 (nth 3 syntax)
                 (goto-char (nth 8 syntax))
                 (progn (when (> inc 0) (forward-sexp)) t))
            (and no-syntax-crossing
                 (or syntax (setq syntax (syntax-ppss)))
                 (nth 4 syntax)
                 (goto-char (nth 8 syntax))
                 (or (< inc 0) (forward-comment 1))
                 (setq arg (+ arg inc)))
            (if no-syntax-crossing
                (user-error "At top level")
              (signal (car err) (cdr err)))))))
      (setq arg (- arg inc)))))

;; ---- Lisp-mode syntax tables (lisp-mode.el / elisp-mode.el) ----
;; Pure make-syntax-table + modify-syntax-entry constructions; ported verbatim so
;; libraries that base their own parse tables on them (ietf-drums, rfc2047, the
;; url-* parsers, mail-parse) load with the exact upstream syntax classes.
(defvar lisp-data-mode-syntax-table
  (let ((table (make-syntax-table))
        (i 0))
    (while (< i ?0)
      (modify-syntax-entry i "_   " table)
      (setq i (1+ i)))
    (setq i (1+ ?9))
    (while (< i ?A)
      (modify-syntax-entry i "_   " table)
      (setq i (1+ i)))
    (setq i (1+ ?Z))
    (while (< i ?a)
      (modify-syntax-entry i "_   " table)
      (setq i (1+ i)))
    (setq i (1+ ?z))
    (while (< i 128)
      (modify-syntax-entry i "_   " table)
      (setq i (1+ i)))
    (modify-syntax-entry ?\s "    " table)
    ;; Non-break space acts as whitespace.
    (modify-syntax-entry ?\xa0 "    " table)
    (modify-syntax-entry ?\t "    " table)
    (modify-syntax-entry ?\f "    " table)
    (modify-syntax-entry ?\n ">   " table)
    (modify-syntax-entry ?\; "<   " table)
    (modify-syntax-entry ?` "'   " table)
    (modify-syntax-entry ?' "'   " table)
    (modify-syntax-entry ?, "'   " table)
    (modify-syntax-entry ?@ "_ p" table)
    ;; Used to be singlequote; changed for flonums.
    (modify-syntax-entry ?. "_   " table)
    (modify-syntax-entry ?# "'   " table)
    (modify-syntax-entry ?\" "\"    " table)
    (modify-syntax-entry ?\\ "\\   " table)
    (modify-syntax-entry ?\( "()  " table)
    (modify-syntax-entry ?\) ")(  " table)
    (modify-syntax-entry ?\[ "(]" table)
    (modify-syntax-entry ?\] ")[" table)
    table)
  "Parent syntax table used in Lisp modes.")

(defvar lisp-mode-syntax-table
  (let ((table (make-syntax-table lisp-data-mode-syntax-table)))
    (modify-syntax-entry ?\[ "_   " table)
    (modify-syntax-entry ?\] "_   " table)
    (modify-syntax-entry ?# "' 14" table)
    (modify-syntax-entry ?| "\" 23bn" table)
    table)
  "Syntax table used in `lisp-mode'.")

(defvar emacs-lisp-mode-syntax-table
  (let ((table (make-syntax-table lisp-data-mode-syntax-table)))
    ;; Remove the "p" flag from the entry of `@' because we use instead
    ;; `syntax-propertize' to take care of `,@', which is more precise.
    (modify-syntax-entry ?@ "_" table)
    table)
  "Syntax table used in `emacs-lisp-mode'.")

;; `emacs -Q --batch' starts in `*scratch*', and `initial-major-mode' puts that
;; buffer in `lisp-interaction-mode' -- a `define-derived-mode' child of
;; `emacs-lisp-mode', so it inherits that mode's syntax table.  Every
;; `char-syntax' / `\sC' answer a batch script sees therefore comes from the
;; elisp table, not from `standard-syntax-table':
;;
;;   emacs -Q --batch --eval '(prin1 (list (char-syntax ?\;) (char-syntax ?.) \
;;                                         (char-syntax ?$) (char-syntax ?{)))'
;;   => (60 95 95 95)
;;
;; where the standard table answers (46 46 119 40).  Install it as the initial
;; buffer's table so the prelude's own forms read the elisp table.  The mode
;; itself comes later: `prelude_31::STARTUP_SCRATCH' runs `initial-major-mode'
;; in `*scratch*' once elisp-mode.el has loaded, which installs
;; `lisp-interaction-mode-syntax-table' (a child of this one) over it.
(set-syntax-table emacs-lisp-mode-syntax-table)

;; ---- abbrev tables (abbrev.el) ----
;; An abbrev table IS an obarray: each abbrev is a symbol interned in it whose
;; VALUE is the expansion, and the table's own properties live on the symbol
;; named "" interned in the same table.  This used to be a documented
;; placeholder built on a plain vector with a side-table for the properties,
;; because elisprs had no obarrays; it does now, so this is the real thing and
;; `(abbrev-table-p (make-abbrev-table))' and `(obarrayp ...)' both answer t
;; while a bare `(obarray-make)' answers nil to the first.
(defun obarray-get (ob name) (intern-soft name ob))
(defun obarray-put (ob name) (intern name ob))
(defun obarray-map (fn ob) (mapatoms fn ob))
(defun abbrev-table-get (table prop)
  "Get the property PROP of abbrev table TABLE."
  (let ((sym (obarray-get table ""))) (if sym (get sym prop))))
(defun abbrev-table-put (table prop val)
  "Set the property PROP of abbrev table TABLE to VAL."
  (let ((sym (obarray-put table "")))
    (set sym nil)          ; so it is never mistaken for an abbrev
    (put sym prop val)))
(defun make-abbrev-table (&optional props)
  "Create a new, empty abbrev table object.
PROPS is a list of properties."
  (let ((table (obarray-make)))
    ;; The `modiff' counter doubles as the tag that says this obarray is an
    ;; abbrev table -- which is how `abbrev-table-p' tells the two apart.
    (abbrev-table-put table :abbrev-table-modiff 0)
    (while (consp props)
      (abbrev-table-put table (pop props) (pop props)))
    table))
(defun abbrev-table-p (object)
  "Return non-nil if OBJECT is an abbrev table."
  (and (obarrayp object)
       (numberp (ignore-error wrong-type-argument
                  (abbrev-table-get object :abbrev-table-modiff)))))
(defun abbrev-table-empty-p (object &optional ignore-system)
  "Return nil if there are any abbrev symbols in OBJECT.
The table's own \"\" property symbol does not count."
  (unless (abbrev-table-p object) (error "Non abbrev table object"))
  (not (catch 'some
         (obarray-map (lambda (abbrev)
                        (unless (or (zerop (length (symbol-name abbrev)))
                                    (and ignore-system (abbrev-get abbrev :system)))
                          (throw 'some t)))
                      object))))
(defalias 'abbrev-get #'get)
(defalias 'abbrev-put #'put)
(defvar abbrev-minor-mode-table-alist nil
  "Alist of abbrev tables to use for minor modes.")
(defvar abbrev-table-name-list '(global-abbrev-table)
  "List of symbols whose values are abbrev tables.")
(defun define-abbrev (table name expansion &optional hook &rest props)
  "Define an abbrev NAME in TABLE expanding to EXPANSION.
Answers the abbrev's symbol, whose VALUE is the expansion -- which is what
`abbrev-expansion' reads back."
  (declare (indent defun))
  ;; The obsolete positional calling convention: (… HOOK COUNT SYSTEM).
  (when (and (consp props) (or (null (car props)) (numberp (car props))))
    (setq props (append (list :count (car props))
                        (if (nth 1 props) (list :system (nth 1 props))))))
  (unless (plist-get props :count) (setq props (plist-put props :count 0)))
  (setq props (plist-put props :abbrev-table-modiff
                         (abbrev-table-get table :abbrev-table-modiff)))
  (let ((sym (obarray-put table name)))
    (set sym expansion)
    (fset sym hook)
    (setplist sym props)
    (abbrev-table-put table :abbrev-table-modiff
                      (1+ (abbrev-table-get table :abbrev-table-modiff)))
    sym))
(defun abbrev-symbol (abbrev &optional table)
  "The symbol representing ABBREV in TABLE (default the global table)."
  (let ((sym (obarray-get (or table global-abbrev-table) abbrev)))
    (and sym (symbol-value sym) sym)))
(defun abbrev-expansion (abbrev &optional table)
  "Return the string ABBREV expands into, or nil."
  (let ((sym (abbrev-symbol abbrev table)))
    (and sym (symbol-value sym))))
(defvar global-abbrev-table (make-abbrev-table)
  "The abbrev table whose abbrevs affect all buffers.")
(defun define-abbrev-table (tablename &optional definitions _docstring &rest props)
  "Define TABLENAME as an abbrev table name, with DEFINITIONS in it.
Answers nil, as Emacs does -- the table is reached through the variable."
  (declare (doc-string 3) (indent defun))
  (unless (and (boundp tablename) (abbrev-table-p (symbol-value tablename)))
    (set tablename (make-abbrev-table)))
  (let ((table (symbol-value tablename)))
    (while (consp props)
      (abbrev-table-put table (pop props) (pop props)))
    (dolist (d definitions)
      (apply #'define-abbrev table d)))
  (unless (memq tablename abbrev-table-name-list)
    (setq abbrev-table-name-list (cons tablename abbrev-table-name-list)))
  nil)

;; merge-ordered-lists (subr.el): merge LISTS into one, removing duplicates and
;; obeying each list's relative order (C3-style). Used by derived-mode-all-parents.
(defun merge-ordered-lists (lists &optional error-function)
  "Merge LISTS in a consistent order.
LISTS is a list of lists of elements."
  (let ((result '()))
    (setq lists (remq nil lists))
    (while (cdr (setq lists (delq nil lists)))
      (let* ((next nil)
	     (tail lists))
	(while tail
	  (let ((candidate (caar tail))
	        (other-lists lists))
	    (while other-lists
	      (if (not (memql candidate (cdr (car other-lists))))
	          (setq other-lists (cdr other-lists))
	        (setq candidate nil)
	        (setq other-lists nil)))
	    (if (not candidate)
	        (setq tail (cdr tail))
	      (setq next candidate)
	      (setq tail nil))))
	(unless next
	  (setq next (funcall (or error-function #'caar) lists))
	  (unless (assoc next lists #'eql)
	    (error "Invalid candidate returned by error-function: %S" next)))
	(push next result)
	(setq lists
	      (mapcar (lambda (l) (if (eql (car l) next) (cdr l) l))
		      lists))))
    (if (null result) (car lists)
      (append (nreverse result) (car lists)))))

;; Mode-line/hook variables (subr.el, buffer.c defaults).
(defvar-local major-mode 'fundamental-mode
  "Symbol for current buffer's major mode.")
(defvar-local mode-name nil
  "Pretty name of current buffer's major mode.")
(defvar delay-mode-hooks nil
  "If non-nil, `run-mode-hooks' should delay running the hooks.")
(defvar-local delayed-mode-hooks nil
  "List of delayed mode hooks waiting to be run.")
(put 'delay-mode-hooks 'permanent-local t)
(defvar-local delayed-after-hook-functions nil
  "List of delayed :after-hook forms waiting to be run.")
(defvar change-major-mode-after-body-hook nil
  "Normal hook run in major mode functions, before the mode hooks.")
(defvar after-change-major-mode-hook nil
  "Normal hook run at the very end of major mode functions.")
(defvar change-major-mode-hook nil
  "Normal hook run by `kill-all-local-variables' before it kills locals.")
(defvar-local local-abbrev-table nil
  "Local (mode-specific) abbrev table of current buffer.")

;; kill-all-local-variables (buffer.c documented behavior): run
;; `change-major-mode-hook', then eliminate the current buffer's local variables
;; except those with a non-nil `permanent-local' property, and reset the local
;; keymap. (Syntax-table/abbrev-table resets belong to subsystems not modeled.)
;; The always-local slots survive, but `reset_buffer_local_variables' stores
;; Fundamental mode's `major-mode' and `mode-name' and a t
;; `buffer-invisibility-spec' into them.
(defun kill-all-local-variables (&optional kill-permanent)
  "Switch to Fundamental mode by killing current buffer's local variables."
  (run-hooks 'change-major-mode-hook)
  (dolist (sym (--buffer-local-symbols--))
    (unless (and (not kill-permanent) (get sym 'permanent-local))
      (kill-local-variable sym)))
  (use-local-map nil)
  (setq major-mode 'fundamental-mode
        mode-name "Fundamental"
        buffer-invisibility-spec t)
  nil)

;; buffer.c `Fbuffer_local_variables': the per-buffer slots in the order of
;; `struct buffer' (`FOR_EACH_PER_BUFFER_OBJECT_AT'), then the Lisp locals of
;; `local_var_alist', oldest binding first.  A void local is a bare symbol.
;; The slot order is measured: make every DEFVAR_PER_BUFFER variable local in a
;; temp buffer of `emacs -Q --batch' and read back `buffer-local-variables'.
(defconst buffer--per-buffer-slot-order
  '(buffer-undo-list cursor-in-non-selected-windows text-conversion-style
    line-spacing cursor-type scroll-down-aggressively scroll-up-aggressively
    buffer-display-time fringe-cursor-alist fringe-indicator-alist
    indicate-buffer-boundaries indicate-empty-lines horizontal-scroll-bar
    vertical-scroll-bar scroll-bar-height scroll-bar-width
    fringes-outside-margins right-fringe-width left-fringe-width
    right-margin-width left-margin-width buffer-display-count
    buffer-invisibility-spec buffer-file-truename point-before-scroll
    cache-long-scans buffer-auto-save-file-format buffer-file-format
    buffer-file-coding-system enable-multibyte-characters mark-active
    buffer-display-table abbrev-mode overwrite-mode selective-display-ellipses
    selective-display bidi-paragraph-start-re bidi-paragraph-separate-re
    bidi-paragraph-direction bidi-display-reordering ctl-arrow word-wrap
    truncate-lines auto-fill-function left-margin fill-column tab-width
    local-abbrev-table tab-line-format header-line-format mode-line-format
    mode-name local-minor-modes major-mode buffer-read-only
    buffer-auto-save-file-name buffer-saved-size buffer-backed-up
    default-directory buffer-file-name)
  "The DEFVAR_PER_BUFFER variables in `struct buffer' order.")
(defun buffer-local-variables (&optional buffer)
  "Return an alist of variables that are buffer-local in BUFFER."
  (unless (or (null buffer) (bufferp buffer))
    (signal 'wrong-type-argument (list 'bufferp buffer)))
  (with-current-buffer (or buffer (current-buffer))
    (let* ((locals (--buffer-local-symbols--))
           (slots nil)
           (rest nil))
      (dolist (sym buffer--per-buffer-slot-order)
        (when (memq sym locals) (push sym slots)))
      (dolist (sym locals)
        (unless (memq sym buffer--per-buffer-slot-order) (push sym rest)))
      (mapcar (lambda (sym) (if (boundp sym) (cons sym (symbol-value sym)) sym))
              (nconc (nreverse slots) (nreverse rest))))))

;; run-mode-hooks / delay-mode-hooks (subr.el, ported faithfully). The
;; `hack-local-variables' branch is inert here — `buffer-file-name' is always nil
;; (no file-visiting buffers).
(defun run-mode-hooks (&rest hooks)
  "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS."
  (if delay-mode-hooks
      (dolist (hook hooks)
	(push hook delayed-mode-hooks))
    (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
    (and (bound-and-true-p syntax-propertize-function)
         (not (local-variable-p 'parse-sexp-lookup-properties))
         (setq-local parse-sexp-lookup-properties t))
    (setq delayed-mode-hooks nil)
    (apply #'run-hooks (cons 'change-major-mode-after-body-hook hooks))
    (if (buffer-file-name)
        (with-demoted-errors "File local-variables error: %s"
          (hack-local-variables 'no-mode)))
    (run-hooks 'after-change-major-mode-hook)
    (dolist (fun (prog1 (nreverse delayed-after-hook-functions)
                    (setq delayed-after-hook-functions nil)))
      (funcall fun))))
(defmacro delay-mode-hooks (&rest body)
  "Execute BODY, but delay any `run-mode-hooks'."
  (declare (debug t) (indent 0))
  `(progn
     (make-local-variable 'delay-mode-hooks)
     (let ((delay-mode-hooks t))
       ,@body)))


;; Derived-mode parent tracking (subr.el).
(defun derived-mode--flush (mode)
  (put mode 'derived-mode--all-parents nil)
  (let ((followers (get mode 'derived-mode--followers)))
    (when followers
      (put mode 'derived-mode--followers nil)
      (mapc #'derived-mode--flush followers))))
(defun derived-mode-set-parent (mode parent)
  "Declare PARENT to be the parent of MODE."
  (put mode 'derived-mode-parent parent)
  (derived-mode--flush mode))
(defun derived-mode-add-parents (mode extra-parents)
  "Add EXTRA-PARENTS to the parents of MODE."
  (put mode 'derived-mode-extra-parents extra-parents)
  (derived-mode--flush mode))
(defun derived-mode-all-parents (mode &optional known-children)
  "Return all the parents of MODE, starting with MODE."
  (let ((ps (get mode 'derived-mode--all-parents)))
    (cond
     (ps ps)
     ((memq mode known-children)
      (memq mode (reverse known-children)))
     (t
      (let* ((new-children (cons mode known-children))
             (get-all-parents
              (lambda (parent)
                (let ((followers (get parent 'derived-mode--followers)))
                  (unless (memq mode followers)
                    (put parent 'derived-mode--followers
                         (cons mode followers))))
                (derived-mode-all-parents parent new-children)))
             (parent (or (get mode 'derived-mode-parent)
                         (let ((alias (symbol-function mode)))
                           (and (symbolp alias) alias))))
             (extras (get mode 'derived-mode-extra-parents))
             (all-parents
              (merge-ordered-lists
               (cons (if (and parent (not (memq parent extras)))
                         (funcall get-all-parents parent))
                     (mapcar get-all-parents extras)))))
        (if (and (memq mode all-parents) known-children)
            (cons mode (remq mode all-parents))
          (put mode 'derived-mode--all-parents (cons mode all-parents))))))))
(defun provided-mode-derived-p (mode &optional modes &rest old-modes)
  "Non-nil if MODE is derived from a mode that is a member of the list MODES."
  (cond
   (old-modes (setq modes (cons modes old-modes)))
   ((not (listp modes)) (setq modes (list modes))))
  (let ((ps (derived-mode-all-parents mode)))
    (while (and modes (not (memq (car modes) ps)))
      (setq modes (cdr modes)))
    (car modes)))
(defun derived-mode-p (&optional modes &rest old-modes)
  "Return non-nil if the current major mode is derived from one of MODES."
  (provided-mode-derived-p major-mode (if old-modes (cons modes old-modes)
                                        modes)))

;; use-local-map / current-local-map are C primitives (builtins.rs) backed by the
;; current buffer's local keymap slot.

;; Docstring helpers (subr.el / derived.el). internal--format-docstring-line does
;; not fill/wrap here (fill is cosmetic; the string content matches Emacs).
(defun internal--format-docstring-line (string &rest objects)
  "Format a single documentation line from STRING and OBJECTS."
  (when (string-match "\n" string)
    (error "Unable to fill string containing newline: %S" string))
  (apply #'format string objects))
(defsubst derived-mode-hook-name (mode)
  "Construct a mode-hook name based on the symbol MODE."
  (intern (concat (symbol-name mode) "-hook")))
(defsubst derived-mode-map-name (mode)
  "Construct a map name based on the symbol MODE."
  (intern (concat (symbol-name mode) "-map")))
(defsubst derived-mode-syntax-table-name (mode)
  "Construct a syntax-table name based on the symbol MODE."
  (intern (concat (symbol-name mode) "-syntax-table")))
(defsubst derived-mode-abbrev-table-name (mode)
  "Construct an abbrev-table name based on the symbol MODE."
  (intern (concat (symbol-name mode) "-abbrev-table")))
(defun derived-mode-make-docstring (parent child &optional
					   docstring syntax abbrev)
  "Construct a docstring for a new mode if none is provided."
  (let ((map (derived-mode-map-name child))
	(hook (derived-mode-hook-name child)))
    (unless (stringp docstring)
      (setq docstring
	    (if (null parent)
                (concat
                 "Major-mode.\n"
                 (internal--format-docstring-line
                  "Uses keymap `%s'%s%s." map
                  (if abbrev (format "%s abbrev table `%s'"
                                     (if syntax "," " and") abbrev) "")
                  (if syntax (format " and syntax-table `%s'" syntax) "")))
	      (format "Major mode derived from `%s' by `define-derived-mode'.
It inherits all of the parent's attributes, but has its own keymap%s:

%s

which more-or-less shadow%s %s's corresponding table%s."
		      parent
		      (cond ((and abbrev syntax)
			     ",\nabbrev table and syntax table")
			    (abbrev "\nand abbrev table")
			    (syntax "\nand syntax table")
			    (t ""))
                      (internal--format-docstring-line
                       "  `%s'%s"
                       map
                       (cond ((and abbrev syntax)
                              (format ", `%s' and `%s'" abbrev syntax))
                             ((or abbrev syntax)
                              (format " and `%s'" (or abbrev syntax)))
                             (t "")))
		      (if (or abbrev syntax) "" "s")
		      parent
		      (if (or abbrev syntax) "s" "")))))
    (unless (string-match (regexp-quote (symbol-name hook)) docstring)
      (setq docstring
            (concat docstring "\n\n"
                    (internal--format-docstring-line
                     "%s%s%s"
                     (if (null parent)
                         "This mode "
                       (concat
                        "In addition to any hooks its parent mode "
                        (if (string-match (format "[`‘]%s['’]"
                                                  (regexp-quote
                                                   (symbol-name parent)))
                                          docstring)
                            nil
                          (format "`%s' " parent))
                        "might have run, this mode "))
                     (format "runs the hook `%s'" hook)
                     ", as the final or penultimate step during initialization."))))
    (unless (string-match "\\\\[{[]" docstring)
      (setq docstring (concat docstring "\n\n\\{" (symbol-name map) "}")))
    docstring))

;; define-derived-mode (derived.el), ported faithfully.
(defmacro define-derived-mode (child parent name &optional docstring &rest body)
  "Create a new mode CHILD which is a variant of an existing mode PARENT."
  (declare (debug (&define name symbolp sexp [&optional stringp]
			   [&rest keywordp sexp] def-body))
	   (doc-string 4)
	   (indent defun))
  (when (and docstring (not (stringp docstring)))
    (push docstring body)
    (setq docstring nil))
  (when (eq parent 'fundamental-mode) (setq parent nil))
  (let ((map (derived-mode-map-name child))
	(syntax (derived-mode-syntax-table-name child))
	(abbrev (derived-mode-abbrev-table-name child))
	(declare-abbrev t)
	(declare-syntax t)
	(hook (derived-mode-hook-name child))
	(group nil)
        (interactive t)
        (after-hook nil))
    (while (keywordp (car body))
      (pcase (pop body)
	(:group (setq group (pop body)))
	(:abbrev-table (setq abbrev (pop body)) (setq declare-abbrev nil))
	(:syntax-table (setq syntax (pop body)) (setq declare-syntax nil))
        (:after-hook (setq after-hook (pop body)))
        (:interactive (setq interactive (pop body)))
	(_ (pop body))))
    (setq docstring (derived-mode-make-docstring
		     parent child docstring syntax abbrev))
    `(progn
       (defvar ,hook nil)
       (unless (get ',hook 'variable-documentation)
         (put ',hook 'variable-documentation
              ,(format "Hook run after entering `%S'.
No problems result if this variable is not bound.
`add-hook' automatically binds it.  (This is true for all hook variables.)"
                       child)))
       ;; Mark the map special (bare `defvar', no value) always, but only
       ;; INITIALIZE it when unbound -- mirroring Emacs's no-clobber `defvar'
       ;; and the syntax/abbrev guards below.  A mode whose map is preloaded
       ;; (e.g. `special-mode-map' via `defvar-keymap') keeps its bindings.
       (with-no-warnings (defvar ,map))
       (unless (boundp ',map)
	 (put ',map 'definition-name ',child)
	 (defvar ,map (make-sparse-keymap)))
       (unless (get ',map 'variable-documentation)
	 (put ',map 'variable-documentation
	      (purecopy ,(format "Keymap for `%s'." child))))
       ,(if declare-syntax
	    `(progn
               (defvar ,syntax)
	       (unless (boundp ',syntax)
		 (put ',syntax 'definition-name ',child)
		 (defvar ,syntax (make-syntax-table)))
	       (unless (get ',syntax 'variable-documentation)
		 (put ',syntax 'variable-documentation
		      (purecopy ,(format "Syntax table for `%s'." child))))))
       ,(if declare-abbrev
	    `(progn
               (defvar ,abbrev)
	       (unless (boundp ',abbrev)
		 (put ',abbrev 'definition-name ',child)
		 (defvar ,abbrev
		   (progn (define-abbrev-table ',abbrev nil) ,abbrev)))
	       (unless (get ',abbrev 'variable-documentation)
		 (put ',abbrev 'variable-documentation
		      (purecopy ,(format "Abbrev table for `%s'." child))))))
       (if (fboundp 'derived-mode-set-parent)
           (derived-mode-set-parent ',child ',parent)
         (put ',child 'derived-mode-parent ',parent))
       ,(if group `(put ',child 'custom-mode-group ,group))
       (defun ,child ()
	 ,docstring
	 ,(and interactive '(interactive))
	 (delay-mode-hooks
	  (,(or parent 'kill-all-local-variables))
	  (setq major-mode (quote ,child))
	  (setq mode-name ,name)
	  ,(when parent
	     `(progn
		(if (get (quote ,parent) 'mode-class)
		    (put (quote ,child) 'mode-class
			 (get (quote ,parent) 'mode-class)))
		(unless (keymap-parent ,map)
		  (set-keymap-parent ,map (current-local-map)))
		,(when declare-syntax
		   `(let ((parent (char-table-parent ,syntax)))
		      (unless (and parent
				   (not (eq parent (standard-syntax-table))))
			(set-char-table-parent ,syntax (syntax-table)))))
                ,(when declare-abbrev
                   `(unless (or (abbrev-table-get ,abbrev :parents)
                                (eq ,abbrev local-abbrev-table))
                      (abbrev-table-put ,abbrev :parents
                                        (list local-abbrev-table))))))
	  (use-local-map ,map)
	  ,(when syntax `(set-syntax-table ,syntax))
	  ,(when abbrev `(setq local-abbrev-table ,abbrev))
	  ,@body)
	 ,@(when after-hook
	     `((push (lambda () ,after-hook) delayed-after-hook-functions)))
	 (run-mode-hooks ',hook)))))

;; ---- fundamental-mode + special-mode (simple.el) ----
;; Buffer-local state slots these modes touch (buffer.c C variables in Emacs;
;; buffer-local Lisp variables here).
(defvar-local buffer-read-only nil
  "Non-nil if this buffer is read-only.")
(defvar-local buffer-undo-list nil
  "List of undo entries in current buffer.
A value of t means undo information is not being recorded.")

;; buffer-disable-undo (simple.el): stop keeping undo information.
(defun buffer-disable-undo (&optional _buffer)
  "Make current buffer stop keeping undo information."
  (setq buffer-undo-list t))
(defun buffer-enable-undo (&optional _buffer)
  "Start keeping undo information for the current buffer."
  (interactive "")
  (when (eq buffer-undo-list t)
    (setq buffer-undo-list nil)))

;; subr.el `with-silent-modifications': run BODY without it counting as a
;; modification -- the modified flag is restored unless the buffer was already
;; modified (and not merely auto-saved) on entry.
(defvar inhibit-modification-hooks nil)
(defmacro with-silent-modifications (&rest body)
  "Execute BODY, pretending it does not modify the buffer."
  (declare (debug t) (indent 0))
  (let ((modified (make-symbol "modified")))
    `(let* ((,modified (buffer-modified-p))
            (buffer-undo-list t)
            (inhibit-read-only t)
            (inhibit-modification-hooks t))
       (unwind-protect
           (progn
             ,@body)
         (when (memq ,modified '(nil autosaved))
           (restore-buffer-modified-p ,modified))))))

;; fundamental-mode (simple.el): the root major mode.  Body is empty; it just
;; resets local variables and installs itself as `major-mode'.
(defun fundamental-mode ()
  "Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one."
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'fundamental-mode)
  (setq mode-name "Fundamental")
  (run-mode-hooks))

;; Display-engine state variables (C `character.c'/`xdisp.c' + `simple.el').
;; These are the real variable declarations, not stubs; the redisplay engine
;; that acts on them is a separate subsystem and is not modeled here.
;; `glyphless-char-display' is itself a char-table (subtype glyphless-char-display,
;; one extra slot), so it also exercises the char-table type.
(put 'glyphless-char-display 'char-table-extra-slots 1)
(defvar glyphless-char-display (make-char-table 'glyphless-char-display)
  "Char-table defining glyphless characters.")
(defvar-local truncate-lines nil
  "Non-nil means do not display continuation lines.")
(defvar-local bidi-paragraph-direction nil
  "If non-nil, forces a paragraph direction in the current buffer.")
(defvar-local text-scale-remap-header-line nil
  "If non-nil, text scaling may change the height of the header line.")
(defvar-local revert-buffer-function nil
  "Function to use to revert this buffer.")

;; special-mode (simple.el): parent mode for buffers that view formatted data.
(put 'special-mode 'mode-class 'special)
(define-derived-mode special-mode nil "Special"
  "Parent major mode from which special major modes should inherit.

A special major mode is intended to view specially formatted data
rather than files.  These modes usually use read-only buffers."
  (setq buffer-read-only t))

;; ---- define-minor-mode (easy-mmode.el) + supporting subr.el pieces ----

;; prefix-numeric-value (C callint.c documented behavior): the numeric value of a
;; raw prefix argument. nil -> 1, `-' -> -1, (N) -> N, a number -> itself.
(defun prefix-numeric-value (arg)
  "Return numeric meaning of raw prefix argument ARG."
  (cond ((null arg) 1)
        ((eq arg '-) -1)
        ((consp arg) (car arg))
        ((integerp arg) arg)
        (t 1)))
(defvar current-prefix-arg nil
  "The raw prefix argument for the next command.")
;; Interactive invocation is not modeled (no `call-interactively'); a command
;; called from Lisp — the only path here — is never an interactive call.
(defun called-interactively-p (&optional _kind) nil)
;; Batch has no echo area / mode line.
(defun current-message () nil)
(defun force-mode-line-update (&optional _all) nil)
;; Warnings are not modeled; return the form unchanged.
(defun macroexp-warn-and-return (_msg form &rest _) form)

;;; ---- declaration handlers (byte-run.el) -----------------------------------
;; `declare' specs that have a *runtime* effect (register a gv-setter, set the
;; obsolete/indent/doc-string properties, …) are processed at defun/defmacro
;; macroexpansion time.  In Emacs `defun'/`defmacro' are themselves macros that
;; do this; in elisprs they are compiler special forms, so the host's
;; defun/defmacro expander (macroexpand_all) delegates to
;; `elisprs--expand-defun-declarations' below once these handlers are defined.
;; Each `defun-declarations-alist' entry is (PROP FUN [DOC]); FUN is applied to
;; (NAME ARGLIST . VALUES) and returns a form to eval after the definition.
;; Ported faithfully from byte-run.el.
(defalias 'byte-run--set-advertised-calling-convention
  (lambda (f _args arglist when)
    (list 'set-advertised-calling-convention
          (list 'quote f) (list 'quote arglist) (list 'quote when))))
(defalias 'byte-run--set-obsolete
  (lambda (f _args new-name when)
    (list 'make-obsolete
          (list 'quote f) (list 'quote new-name) when)))
(defalias 'byte-run--set-interactive-only
  (lambda (f _args instead)
    (list 'function-put (list 'quote f)
          ''interactive-only (list 'quote instead))))
(defalias 'byte-run--set-pure
  (lambda (f _args val)
    (list 'function-put (list 'quote f)
          ''pure (list 'quote val))))
(defalias 'byte-run--set-side-effect-free
  (lambda (f _args val)
    (list 'function-put (list 'quote f)
          ''side-effect-free (list 'quote val))))
(defalias 'byte-run--set-important-return-value
  (lambda (f _args val)
    (list 'function-put (list 'quote f)
          ''important-return-value (list 'quote val))))
(defalias 'byte-run--set-compiler-macro
  (lambda (f args compiler-function)
    (if (not (eq (car-safe compiler-function) 'lambda))
        `(eval-and-compile
           (function-put ',f 'compiler-macro #',compiler-function))
      (let ((cfname (intern (concat (symbol-name f) "--anon-cmacro")))
            (data (cdr compiler-function)))
        `(progn
           (eval-and-compile
             (function-put ',f 'compiler-macro #',cfname))
           :autoload-end
           (eval-and-compile
             (defun ,cfname (,@(car data) ,@args)
               (ignore ,@(delq '&rest (delq '&optional (copy-sequence args))))
               ,@(cdr data))))))))
;; `add-to-list' is defined far above, before this bridge exists, so its
;; compiler macro is registered by hand -- in exactly the shape
;; `byte-run--set-compiler-macro' would have produced from a `declare'.
;;
;; The handler is subr.el's own. It DECLINES -- answering the form unchanged,
;; so the ordinary function runs -- unless VAR is a literally-quoted symbol
;; that is not special and APPEND is a constant, which is precisely the case
;; the function cannot serve: it reads and writes a symbol's value cell, and a
;; lexical variable has none. (subr.el also emits a byte-compiler warning here;
;; elisprs has no `macroexp-compiling-p' path, and Emacs skips the warning on
;; that branch too.)
(defun add-to-list--anon-cmacro (exp var elt &optional append compare-fn)
  (if (or (not (eq 'quote (car-safe var)))
          (special-variable-p (car (cdr var)))
          (not (macroexp-const-p append)))
      exp
    (let ((sym (car (cdr var)))
          (appendp (eval append t)))
      (list 'if (if compare-fn
                    (list 'cl-member elt sym :test compare-fn)
                  (list 'member elt sym))
            sym
            (if appendp
                (list 'setq sym (list 'append sym (list 'list elt)))
              (list 'setq sym (list 'cons elt sym)))))))
(function-put 'add-to-list 'compiler-macro #'add-to-list--anon-cmacro)

(defalias 'byte-run--set-doc-string
  (lambda (f _args pos)
    (list 'function-put (list 'quote f)
          ''doc-string-elt (if (numberp pos) pos (list 'quote pos)))))
(defalias 'byte-run--set-indent
  (lambda (f _args val)
    (list 'function-put (list 'quote f)
          ''lisp-indent-function (if (numberp val) val (list 'quote val)))))
(defalias 'byte-run--set-speed
  (lambda (f _args val)
    (list 'function-put (list 'quote f) ''speed (list 'quote val))))
(defalias 'byte-run--set-safety
  (lambda (f _args val)
    (list 'function-put (list 'quote f) ''safety (list 'quote val))))
(defalias 'byte-run--set-completion
  (lambda (f _args val)
    (list 'function-put (list 'quote f)
          ''completion-predicate (list 'function val))))
(defalias 'byte-run--set-modes
  (lambda (f _args &rest val)
    (list 'function-put (list 'quote f) ''command-modes (list 'quote val))))
(defalias 'byte-run--set-interactive-args
  (lambda (f args &rest val)
    (setq args (remove '&optional (remove '&rest args)))
    (list 'function-put (list 'quote f)
          ''interactive-args
          (list 'quote
                (mapcar (lambda (elem)
                          (cons (seq-position args (car elem)) (cadr elem)))
                        val)))))
(defalias 'byte-run--set-function-type
  (lambda (f _args val &optional f2)
    (when (and f2 (not (eq f2 f)))
      (error "`%s' does not match top level function `%s' inside function type declaration"
             f2 f))
    (list 'function-put (list 'quote f) ''function-type (list 'quote val))))
(defalias 'byte-run--set-debug
  (lambda (name _args spec)
    (list 'progn :autoload-end
          (list 'put (list 'quote name) ''edebug-form-spec (list 'quote spec)))))
(defalias 'byte-run--set-no-font-lock-keyword
  (lambda (name _args val)
    (list 'function-put (list 'quote name) ''no-font-lock-keyword (list 'quote val))))

;; Populate the alists declared earlier as nil (byte-run.el:235,349).
(setq defun-declarations-alist
      (list
       (list 'advertised-calling-convention
             #'byte-run--set-advertised-calling-convention)
       (list 'obsolete #'byte-run--set-obsolete)
       (list 'interactive-only #'byte-run--set-interactive-only)
       (list 'pure #'byte-run--set-pure)
       (list 'side-effect-free #'byte-run--set-side-effect-free)
       (list 'important-return-value #'byte-run--set-important-return-value)
       (list 'compiler-macro #'byte-run--set-compiler-macro)
       (list 'doc-string #'byte-run--set-doc-string)
       (list 'indent #'byte-run--set-indent)
       (list 'speed #'byte-run--set-speed)
       (list 'safety #'byte-run--set-safety)
       (list 'completion #'byte-run--set-completion)
       (list 'modes #'byte-run--set-modes)
       (list 'interactive-args #'byte-run--set-interactive-args)
       (list 'ftype #'byte-run--set-function-type)))
(setq macro-declarations-alist
      (cons (list 'debug #'byte-run--set-debug)
            (cons (list 'no-font-lock-keyword #'byte-run--set-no-font-lock-keyword)
                  defun-declarations-alist)))

;; byte-run.el:279 — split BODY into (DOCSTRING DECLARE INTERACTIVE REST WARNINGS).
(defun byte-run--parse-body (body allow-interactive)
  "Decompose BODY into (DOCSTRING DECLARE INTERACTIVE BODY-REST WARNINGS)."
  (let* ((top body)
         (docstring nil)
         (declare-form nil)
         (interactive-form nil)
         (warnings nil)
         (warn (lambda (msg form)
                 (push (macroexp-warn-and-return
                        (format-message msg) nil nil t form)
                       warnings))))
    (while
        (and body
             (let* ((form (car body))
                    (head (car-safe form)))
               (cond
                ((or (and (stringp form) (cdr body))
                     (eq head :documentation))
                 (cond
                  (docstring (funcall warn "More than one doc string" top))
                  (declare-form
                   (funcall warn "Doc string after `declare'" declare-form))
                  (interactive-form
                   (funcall warn "Doc string after `interactive'" interactive-form))
                  (t (setq docstring form)))
                 t)
                ((eq head 'declare)
                 (cond
                  (declare-form
                   (funcall warn "More than one `declare' form" form))
                  (interactive-form
                   (funcall warn "`declare' after `interactive'" form))
                  (t (setq declare-form form)))
                 t)
                ((eq head 'interactive)
                 (cond
                  ((not allow-interactive)
                   (funcall warn "No `interactive' form allowed here" form))
                  (interactive-form
                   (funcall warn "More than one `interactive' form" form))
                  (t (setq interactive-form form)))
                 t))))
      (setq body (cdr body)))
    (list docstring declare-form interactive-form body warnings)))

;; byte-run.el:326 — map each declaration clause through DECLARATIONS-ALIST.
(defun byte-run--parse-declarations (name arglist clauses construct declarations-alist)
  (let* ((cl-decls nil)
         (actions
          (mapcar
           (lambda (x)
             (let ((f (cdr (assq (car x) declarations-alist))))
               (cond
                (f (apply (car f) name arglist (cdr x)))
                ((and (featurep 'cl)
                      (memq (car x)
                            '(special inline notinline optimize warn)))
                 (push (list 'declare x) cl-decls)
                 nil)
                (t
                 (macroexp-warn-and-return
                  (format-message "Unknown %s property `%S'"
                                  construct (car x))
                  nil nil nil (car x))))))
           clauses)))
    (cons actions cl-decls)))

;; gv.el:159 — turn a (gv-setter …)/(gv-expander …) declaration into the form
;; that registers the corresponding generalized-variable handler.
(defun gv--defun-declaration (symbol name args handler &optional fix)
  `(progn
     :autoload-end
     ,(pcase (cons symbol handler)
        (`(gv-expander . (lambda (,do) . ,body))
         `(gv-define-expander ,name (lambda (,do ,@args) ,@body)))
        (`(gv-expander . ,(pred symbolp))
         `(gv-define-expander ,name #',handler))
        (`(gv-setter . (lambda (,store) . ,body))
         `(gv-define-setter ,name (,store ,@args) ,@body))
        (`(gv-setter . ,(pred symbolp))
         `(gv-define-simple-setter ,name ,handler ,fix))
        (_ (message "Unknown %s declaration %S" symbol handler) nil))))
(defsubst gv--expander-defun-declaration (&rest args)
  (apply #'gv--defun-declaration 'gv-expander args))
(defsubst gv--setter-defun-declaration (&rest args)
  (apply #'gv--defun-declaration 'gv-setter args))
(or (assq 'gv-expander defun-declarations-alist)
    (let ((x (list 'gv-expander #'gv--expander-defun-declaration)))
      (push x macro-declarations-alist)
      (push x defun-declarations-alist)))
(or (assq 'gv-setter defun-declarations-alist)
    (push (list 'gv-setter #'gv--setter-defun-declaration)
          defun-declarations-alist))

;; Bridge invoked by the host's defun/defmacro expander (macroexpand_all).
;; CONSTRUCT is `defun' or `defmacro'; NAME/ARGLIST/BODY are the raw pieces.
;; Returns the replacement form threading each declaration's runtime side-effect
;; form after the (unchanged-shape) definition, mirroring byte-run.el's `defun'
;; and `defmacro' macros — or nil when BODY has no `declare' (host falls through
;; to plain body expansion).
(defun elisprs--expand-defun-declarations (construct name arglist body)
  (let* ((allow-interactive (eq construct 'defun))
         (parse (byte-run--parse-body body allow-interactive))
         (docstring (nth 0 parse))
         (declare-form (nth 1 parse))
         (interactive-form (nth 2 parse))
         (rest (nth 3 parse))
         (warnings (nth 4 parse))
         (alist (if (eq construct 'defmacro)
                    macro-declarations-alist
                  defun-declarations-alist))
         (declarations
          (and declare-form
               (byte-run--parse-declarations
                name arglist (cdr declare-form) construct alist))))
    (when declare-form
      (setq rest (nconc warnings rest))
      (setq rest (nconc (cdr declarations) rest))
      (when interactive-form (setq rest (cons interactive-form rest)))
      (when docstring (setq rest (cons docstring rest)))
      (when (null rest) (setq rest '(nil)))
      (let ((def (cons construct (cons name (cons arglist rest)))))
        (if declarations
            (cons 'prog1 (cons def (car declarations)))
          def)))))
;; A `defun'/`defmacro' the prelude defined before this bridge existed kept
;; its `declare' unprocessed; Emacs's preloaded files are byte-compiled with
;; every declaration applied, so run the side-effect forms the bridge would
;; have threaded after each of those definitions (without redefining them).
(dolist (def (--early-declarations--))
  (let ((replaced (elisprs--expand-defun-declarations
                   (car def) (nth 1 def) (nth 2 def) (nthcdr 3 def))))
    (when (eq (car-safe replaced) 'prog1)
      (dolist (form (cddr replaced))
        (eval form t)))))
;; custom-local-buffer (custom.el): when non-nil in a Customization buffer,
;; :set functions target that buffer's local binding instead of the default.
(defvar custom-local-buffer nil
  "Non-nil, in a Customization buffer, means customize a specific buffer.
If this variable is non-nil, it should be a buffer,
and it means customize the local bindings of that buffer.
This variable is a permanent local, and it normally has a local binding
in every Customization buffer.")
(put 'custom-local-buffer 'permanent-local t)

;; custom-set-default (custom.el): the default :set function for a customizable
;; variable.  Sets the default value of VARIABLE to VALUE, unless a
;; `custom-local-buffer' is active (Customize buffer), in which case the local
;; binding in that buffer is set instead.
(defun custom-set-default (variable value)
  "Default :set function for a customizable variable.
Normally, this sets the default value of VARIABLE to VALUE,
but if `custom-local-buffer' is non-nil,
this sets the local binding in that buffer instead."
  (if custom-local-buffer
      (with-current-buffer custom-local-buffer
	(set variable value))
    (set-default-toplevel-value variable value)))

;; ---------------------------------------------------------------------------
;; custom-set-variables / custom-theme-set-variables (custom.el).
;;
;; This is the machinery a user's Customize block generates.  Ported faithfully
;; from custom.el (Emacs 30.2).  It is pure Lisp: no widgets, keymaps, eieio, or
;; face machinery on this path -- only theme-value/saved-value bookkeeping via
;; get/put plus the default :set (custom-set-default).
;; ---------------------------------------------------------------------------

;; load-history (lread.c global): normally a list of loaded files and the
;; symbols they defined.  elisprs does not track it; nil means "nothing known
;; to be loaded", which only affects the autoload branch of custom-load-symbol.
(defvar load-history nil
  "Alist mapping loaded file names to symbols and features.")

;; custom.el:690
(defvar custom-load-recursion nil
  "Hack to avoid recursive dependencies.")

;; custom.el:884
(defvar custom-known-themes '(user changed)
  "Themes that have been defined with `deftheme'.")

;; custom.el:892
(defsubst custom-theme-p (theme)
  "Non-nil when THEME has been defined."
  (memq theme custom-known-themes))

;; custom.el:895
(defsubst custom-check-theme (theme)
  "Check whether THEME is valid, and signal an error if it is not."
  (unless (custom-theme-p theme)
    (error "Unknown theme `%s'" theme)))

;; custom.el:753
(defun custom-quote (sexp)
  "Quote SEXP if it is not self quoting."
  (if (and (not (consp sexp))
           (or (keywordp sexp)
               (not (symbolp sexp))
               (booleanp sexp)))
      sexp
    (list 'quote sexp)))

;; custom.el:1234
(defvar custom--inhibit-theme-enable 'apply-only-user
  "Whether the custom-theme-set-* functions act immediately.
If nil, `custom-theme-set-variables' and `custom-theme-set-faces'
change the current values of the given variable or face.  If t,
they just make a record of the theme's settings.  If the value is
`apply-only-user', then only the `user' theme is allowed to
change the current values.")

;; custom.el:901
(defun custom--should-apply-setting (theme)
  (or (null custom--inhibit-theme-enable)
      (and (eq custom--inhibit-theme-enable 'apply-only-user)
           (eq theme 'user))))

;; custom.el:906
(defun custom-push-theme (prop symbol theme mode &optional value)
  "Record VALUE for face or variable SYMBOL in custom theme THEME.
PROP is `theme-face' for a face, `theme-value' for a variable.
MODE can be either the symbol `set' or the symbol `reset'."
  (unless (memq prop '(theme-value theme-face theme-icon))
    (error "Unknown theme property"))
  (let* ((old (get symbol prop))
	 (setting (assq theme old))
	 (theme-settings
	  (get theme 'theme-settings)))
    (cond
     ((eq mode 'reset)
      (when setting
	(let (res)
	  (dolist (theme-setting theme-settings)
	    (if (and (eq (car  theme-setting) prop)
		     (eq (cadr theme-setting) symbol))
		(setq res theme-setting)))
	  (put theme 'theme-settings (delq res theme-settings)))
	(put symbol prop (delq setting old))))
     (setting
      (let (res)
	(dolist (theme-setting theme-settings)
	  (if (and (eq (car  theme-setting) prop)
		   (eq (cadr theme-setting) symbol))
	      (setq res theme-setting)))
	(put theme 'theme-settings
	     (cons (list prop symbol theme value)
		   (delq res theme-settings)))
        (put symbol prop (cons (list theme value) (delq setting old)))))
     (t
      (when (custom--should-apply-setting theme)
	(unless old
	  (when (and (eq prop 'theme-value)
		     (boundp symbol))
	    (let ((sv  (get symbol 'standard-value))
		  (val (symbol-value symbol)))
	      (unless (or
                       (and sv (equal (eval (car sv)) val))
                       (and (eq theme 'user) (equal (custom-quote val) value)))
		(setq old `((changed ,(custom-quote val))))))))
	(put symbol prop (cons (list theme value) old)))
      (put theme 'theme-settings
	   (cons (list prop symbol theme value) theme-settings))))))

;; custom.el:693
(defun custom-load-symbol (symbol)
  "Load all dependencies for SYMBOL."
  (unless custom-load-recursion
    (let ((custom-load-recursion t))
      (ignore-errors
        (require 'cus-load))
      (ignore-errors
        (require 'cus-start))
      (dolist (load (get symbol 'custom-loads))
        (cond ((symbolp load) (ignore-errors (require load)))
	      ((assoc load load-history))
	      ((let ((regexp (concat "\\(\\`\\|/\\)" (regexp-quote load)
				     "\\(\\'\\|\\.\\)"))
		     (found nil))
		 (dolist (loaded load-history)
		   (and (stringp (car loaded))
			(string-match-p regexp (car loaded))
			(setq found t)))
		 found))
	      ((equal load "cus-edit"))
              (t (ignore-errors (load load))))))))

;; custom.el:1085 (defvars for the topological sort)
(defvar custom--sort-vars-table)
(defvar custom--sort-vars-result)

;; custom.el:1123
(defun custom--sort-vars-1 (sym &optional _ignored)
  (let ((elt (gethash sym custom--sort-vars-table)))
    (when elt
      (cond
       ((eq (car elt) 'dependant)
	(error "Circular custom dependency on `%s'" sym))
       ((car elt)
	(setcar elt 'dependant)
	(dolist (dep (get sym 'custom-dependencies))
	  (custom--sort-vars-1 dep))
	(setcar elt nil)
	(push (cdr elt) custom--sort-vars-result))))))

;; custom.el:1088
(defun custom--sort-vars (vars)
  "Sort VARS based on custom dependencies."
  (let ((custom--sort-vars-table (make-hash-table))
	(dependants (make-hash-table))
	(custom--sort-vars-result nil)
	last)
    (dolist (var vars)
      (puthash (car var) (cons t var) custom--sort-vars-table)
      (puthash (car var) var dependants))
    (dolist (var vars)
      (dolist (dep (get (car var) 'custom-dependencies))
	(remhash dep dependants)))
    (maphash (lambda (sym var)
	       (when (and (null (get sym 'custom-dependencies))
			  (or (nth 3 var)
			      (eq (get sym 'custom-set)
				  'custom-set-minor-mode)))
		 (remhash sym dependants)
		 (push var last)))
	     dependants)
    (maphash #'custom--sort-vars-1 dependants)
    (nconc (nreverse custom--sort-vars-result) last)))

;; custom.el:1017
(defun custom-theme-set-variables (theme &rest args)
  "Initialize variables for theme THEME according to settings in ARGS.
Each of the arguments in ARGS should be a list of this form:

  (SYMBOL EXP [NOW [REQUEST [COMMENT]]])"
  (custom-check-theme theme)
  (dolist (entry args)
    (let* ((symbol (indirect-variable (nth 0 entry))))
      (unless (or (get symbol 'standard-value)
                  (memq (get symbol 'custom-autoload) '(nil noset)))
        (custom-load-symbol symbol))))
  (setq args (custom--sort-vars args))
  (dolist (entry args)
    (unless (listp entry)
      (error "Incompatible Custom theme spec"))
    (let* ((symbol (indirect-variable (nth 0 entry)))
	   (value (nth 1 entry)))
      (custom-push-theme 'theme-value symbol theme 'set value)
      (when (custom--should-apply-setting theme)
	(let* ((now (nth 2 entry))
	       (requests (nth 3 entry))
	       (comment (nth 4 entry))
	       set)
	  (when requests
	    (put symbol 'custom-requests requests)
            (mapc (lambda (lib) (require lib nil t)) requests))
          (setq set (or (get symbol 'custom-set) #'custom-set-default))
	  (put symbol 'saved-value (list value))
	  (put symbol 'saved-variable-comment comment)
	  (condition-case data
	      (cond (now
		     (put symbol 'force-value t)
		     (funcall set symbol (eval value)))
		    ((default-boundp symbol)
		     (funcall set symbol (eval value))))
	    (error
	     (message "Error setting %s: %s" symbol data)))
	  (and (or now (default-boundp symbol))
	       (put symbol 'variable-comment comment)))))))

;; custom.el:1001
(defun custom-set-variables (&rest args)
  "Install user customizations of variable values specified in ARGS.
These settings are registered as theme `user'.
The arguments should each be a list of the form:

  (SYMBOL EXP [NOW [REQUEST [COMMENT]]])"
  (apply #'custom-theme-set-variables 'user args))

;; custom-set-minor-mode (custom.el): a defcustom :set that toggles the mode.
;; (Reached only via Customize, which is out of the mode-run path.)
(defun custom-set-minor-mode (variable value)
  (funcall variable (if value 1 0)))

;; minor-mode registries (subr.el defvars).
(defvar minor-mode-list nil
  "List of all minor mode functions.")
(defvar minor-mode-alist nil
  "Alist saying how to show minor modes in the mode line.")
(defvar minor-mode-map-alist nil
  "Alist of keymaps to use for minor modes.")
(defvar global-minor-modes nil
  "A list of the currently enabled global minor modes.")
(defvar-local local-minor-modes nil
  "A list of the currently enabled minor modes in the current buffer.")
(defvar mode-line-mode-menu (make-sparse-keymap "Minor Modes")
  "Menu of mode operations in the mode line.")

;; add-minor-mode (subr.el), ported faithfully.
(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
  "Register a new minor mode."
  (unless (memq toggle minor-mode-list)
    (push toggle minor-mode-list))
  (unless toggle-fun (setq toggle-fun toggle))
  (unless (eq toggle-fun toggle)
    (put toggle :minor-mode-function toggle-fun))
  (when name
    (let ((existing (assq toggle minor-mode-alist)))
      (if existing
	  (setcdr existing (list name))
	(let ((tail minor-mode-alist) found)
	  (while (and tail (not found))
	    (if (eq after (caar tail))
		(setq found tail)
	      (setq tail (cdr tail))))
	  (if found
	      (let ((rest (cdr found)))
		(setcdr found nil)
		(nconc found (list (list toggle name)) rest))
	    (push (list toggle name) minor-mode-alist))))))
  (when (get toggle :included)
    (define-key mode-line-mode-menu
      (vector toggle)
      (list 'menu-item
	    (concat
	     (or (get toggle :menu-tag)
		 (if (stringp name) name (symbol-name toggle)))
	     (let ((mode-name (if (symbolp name) (symbol-value name))))
	       (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
		   (concat " (" (match-string 0 mode-name) ")"))))
	    toggle-fun
	    :button (cons :toggle toggle))))
  (when keymap
    (let ((existing (assq toggle minor-mode-map-alist)))
      (if existing
	  (setcdr existing keymap)
	(let ((tail minor-mode-map-alist) found)
	  (while (and tail (not found))
	    (if (eq after (caar tail))
		(setq found tail)
	      (setq tail (cdr tail))))
	  (if found
	      (let ((rest (cdr found)))
		(setcdr found nil)
		(nconc found (list (cons toggle keymap)) rest))
	    (push (cons toggle keymap) minor-mode-map-alist)))))))

;; easy-mmode-pretty-mode-name (easy-mmode.el).
(defun easy-mmode-pretty-mode-name (mode &optional lighter)
  "Turn the symbol MODE into a string intended for the user."
  (let* ((case-fold-search t)
	 (name (concat (replace-regexp-in-string
			"-Minor" " minor"
			(capitalize (replace-regexp-in-string
				     "toggle-\\|-mode\\'" ""
                                     (symbol-name mode))))
		       " mode")))
    (setq name (replace-regexp-in-string "\\`Global-" "Global " name))
    (if (not (stringp lighter)) name
      (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
					      lighter))
      (replace-regexp-in-string (regexp-quote lighter) lighter name t t))))

;; ensure-empty-lines (subr.el): ensure LINES empty lines before point.
(defun ensure-empty-lines (&optional lines)
  "Ensure that there are LINES number of empty lines before point."
  (unless (bolp)
    (insert "\n"))
  (let ((lines (or lines 1))
        (start (save-excursion
                 (if (re-search-backward "[^\n]" nil t)
                     (+ (point) 2)
                   (point-min)))))
    (cond
     ((> (- (point) start) lines)
      (delete-region (point) (- (point) (- (point) start lines))))
     ((< (- (point) start) lines)
      (insert (make-string (- lines (- (point) start)) ?\n))))))

(defconst easy-mmode--arg-docstring
  "This is a %sminor mode.  If called interactively, toggle the
`%s' mode.  If the prefix argument is positive, enable the mode,
and if it is zero or negative, disable the mode.

If called from Lisp, toggle the mode if ARG is `toggle'.
Enable the mode if ARG is nil, omitted, or is a positive number.
Disable the mode if ARG is a negative number.

To check whether the minor mode is enabled in the current buffer,
evaluate %s.

The mode's hook is called both when the mode is enabled and when
it is disabled.")
;; easy-mmode--mode-docstring (easy-mmode.el). Uses a temp buffer to compose the
;; docstring; `fill-region' is skipped when unbound (no line-wrap; cosmetic).
(defun easy-mmode--mode-docstring (doc mode-pretty-name keymap-sym getter global)
  (if (and doc (string-match-p "\\bARG\\b" doc))
      doc
    (with-temp-buffer
      (let ((lines (if doc
                       (string-lines doc)
                     (list (format "Toggle %s on or off." mode-pretty-name)))))
        (insert (pop lines))
        (ensure-empty-lines)
        (while (and lines (equal (car lines) ""))
          (pop lines))
        (dolist (line lines)
          (insert line "\n"))
        (ensure-empty-lines)
        (let* ((fill-prefix nil)
               (docs-fc (bound-and-true-p emacs-lisp-docstring-fill-column))
               (fill-column (if (integerp docs-fc) docs-fc 65))
               (argdoc (format
                        easy-mmode--arg-docstring
                        (if global "global " "")
                        mode-pretty-name
                        (concat
                         (if (symbolp getter) "the variable ")
                         (format "`%s'"
                                 (string-replace "'" "\\='" (format "%S" getter)))))))
          (let ((start (point)))
            (insert argdoc)
            (when (fboundp 'fill-region)
              (fill-region start (point) 'left t))))
        (when (and (boundp keymap-sym)
                   (or (not doc)
                       (not (string-search "\\{" doc))))
          (ensure-empty-lines)
          (insert (format "\\{%s}" keymap-sym)))
        (buffer-string)))))

;; define-minor-mode (easy-mmode.el), ported faithfully.
(defmacro define-minor-mode (mode doc &rest body)
  "Define a new minor mode MODE."
  (declare (doc-string 2) (indent defun))
  (let* ((last-message (make-symbol "last-message"))
         (mode-name (symbol-name mode))
         (init-value nil)
         (keymap nil)
         (lighter nil)
	 (pretty-name nil)
	 (globalp nil)
	 (set nil)
	 (initialize nil)
	 (type nil)
	 (extra-args nil)
	 (extra-keywords nil)
         (variable nil)
         (setter `(setq ,mode))
         (getter mode)
         (modefun mode)
	 (after-hook nil)
	 (hook (intern (concat mode-name "-hook")))
	 (hook-on (intern (concat mode-name "-on-hook")))
	 (hook-off (intern (concat mode-name "-off-hook")))
         (interactive t)
         (warnwrap (if (or (null body) (keywordp (car body))) #'identity
                     (lambda (exp)
                       (macroexp-warn-and-return
                        (format-message
                         "Use keywords rather than deprecated positional arguments to `define-minor-mode'")
                        exp))))
	 keyw keymap-sym tmp)
    (unless (keywordp (car body))
      (setq init-value (pop body))
      (unless (keywordp (car body))
        (setq lighter (pop body))
        (unless (keywordp (car body))
          (setq keymap (pop body)))))
    (while (keywordp (setq keyw (car body)))
      (setq body (cdr body))
      (pcase keyw
	(:init-value (setq init-value (pop body)))
	(:lighter (setq lighter (purecopy (pop body))))
	(:global (setq globalp (pop body))
                 (when (and globalp (symbolp mode))
                   (setq setter `(setq-default ,mode))
                   (setq getter `(default-value ',mode))))
	(:extra-args (setq extra-args (pop body)))
	(:set (setq set (list :set (pop body))))
	(:initialize (setq initialize (list :initialize (pop body))))
	(:type (setq type (list :type (pop body))))
	(:keymap (setq keymap (pop body)))
	(:interactive (setq interactive (pop body)))
        (:variable (setq variable (pop body))
                   (if (not (and (setq tmp (cdr-safe variable))
                                 (or (symbolp tmp)
                                     (functionp tmp))))
                       (progn
                         (setq setter `(setf ,variable))
                         (setq getter variable))
                     (setq getter (car variable))
                     (setq setter `(funcall #',(cdr variable)))))
	(:after-hook (setq after-hook (pop body)))
	(_ (push keyw extra-keywords) (push (pop body) extra-keywords))))
    (setq pretty-name (easy-mmode-pretty-mode-name mode lighter))
    (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
		       (intern (concat mode-name "-map"))))
    (unless set (setq set '(:set #'custom-set-minor-mode)))
    (unless initialize
      (setq initialize '(:initialize #'custom-initialize-default)))
    (unless type (setq type '(:type 'boolean)))
    `(progn
       ,(cond
         (variable nil)
         ((not globalp)
          `(progn
             :autoload-end
             (defvar-local ,mode ,init-value
               ,(concat (format "Non-nil if %s is enabled.\n" pretty-name)
                        (internal--format-docstring-line
                         "Use the command `%s' to change this variable." mode)))))
         (t
	  (let ((base-doc-string
                 (concat "Non-nil if %s is enabled.
See the `%s' command
for a description of this minor mode."
                         (if body "
Setting this variable directly does not take effect;
either customize it (see the info node `Easy Customization')
or call the function `%s'."))))
	    `(defcustom ,mode ,init-value
	       ,(format base-doc-string pretty-name mode mode)
	       ,@set
	       ,@initialize
	       ,@type
               ,@(nreverse extra-keywords)))))
       ,(funcall
         warnwrap
         `(defun ,modefun (&optional arg ,@extra-args)
            ,(easy-mmode--mode-docstring doc pretty-name keymap-sym
                                         getter globalp)
            ,(when interactive
               (if (consp interactive)
                   `(interactive
                     (list (if current-prefix-arg
                               (prefix-numeric-value current-prefix-arg)
                             'toggle))
                     ,@interactive)
		 '(interactive
                   (list (if current-prefix-arg
                             (prefix-numeric-value current-prefix-arg)
                           'toggle)))))
	    (let ((,last-message (current-message)))
              (,@setter
               (cond ((eq arg 'toggle)
                      (not ,getter))
                     ((and (numberp arg)
                           (< arg 1))
                      nil)
                     (t
                      t)))
              ,@(if globalp
                    `((when (boundp 'global-minor-modes)
                        (setq global-minor-modes
                              (delq ',modefun global-minor-modes))
                        (when ,getter
                          (push ',modefun global-minor-modes))))
                  `((when (boundp 'local-minor-modes)
                      (setq local-minor-modes
                            (delq ',modefun local-minor-modes))
                      (when ,getter
                        (push ',modefun local-minor-modes)))))
              ,@body
              (run-hooks ',hook (if ,getter ',hook-on ',hook-off))
              (if (called-interactively-p 'any)
                  (progn
                    ,(if (and globalp (not variable))
                         `(customize-mark-as-set ',mode))
                    (unless (and (current-message)
                                 (not (equal ,last-message
                                             (current-message))))
                      (let ((local ,(if globalp "" " in current buffer")))
			(message "%s %sabled%s" ,pretty-name
			         (if ,getter "en" "dis") local)))))
	      ,@(when after-hook `(,after-hook)))
	    (force-mode-line-update)
	    ,getter))
       :autoload-end
       (defvar ,hook nil)
       (unless (get ',hook 'variable-documentation)
         (put ',hook 'variable-documentation
              ,(format "Hook run after entering or leaving `%s'.
No problems result if this variable is not bound.
`add-hook' automatically binds it.  (This is true for all hook variables.)"
                       modefun)))
       (put ',hook 'custom-type 'hook)
       (put ',hook 'standard-value (list nil))
       ,(unless (symbolp keymap)
	  `(defvar ,keymap-sym
	     (let ((m ,keymap))
	       (cond ((keymapp m) m)
		     ((listp m)
                      (easy-mmode-define-keymap m))
		     (t (error "Invalid keymap %S" m))))
	     ,(format "Keymap for `%s'." mode-name)))
       ,(let ((modevar (pcase getter (`(default-value ',v) v) (_ getter))))
          (if (not (symbolp modevar))
              (if (or lighter keymap)
                  (error ":lighter and :keymap unsupported with mode expression %S" getter))
            `(with-no-warnings
               (add-minor-mode ',modevar ',lighter
                               ,(if keymap keymap-sym
                                  `(if (boundp ',keymap-sym) ,keymap-sym))
                               nil
                               ,(unless (eq mode modefun) `',modefun))))))))

;;; ---- ERT: Emacs Lisp Regression Testing (subset) ----
;; Ported from ERT: `should` / `should-not` / `should-error` / `skip-unless`
;; assertions, `ert-fail` / `ert-pass`, and `ert-deftest` with an optional
;; docstring plus `:expected-result` and `:tags` keyword args. Assertions signal
;; `ert-test-failed`; `skip-unless` signals `ert-test-skipped`. The runner
;; classifies each test as pass / fail / skip / expected-fail (XFAIL) /
;; unexpected-pass and returns the number of UNEXPECTED results (0 = all as
;; expected). `ert-run-tests-batch-and-exit` errors out on any unexpected one.

(defvar ert--tests nil)   ; alist of (name . expected-result), :passed | :failed
(define-error 'ert-test-failed "Test failed")
(define-error 'ert-test-skipped "Test skipped")

;; should-failure explanation: for an assertion `(PRED ARG...)`, each ARG is
;; evaluated once and its value reported next to the form on failure — the way
;; ERT explains a failing `should`. Limited to known pure predicates so eager
;; argument evaluation can't change semantics; anything else falls back to a
;; plain truthiness check.
(defvar ert--explain-fns
  '(= /= < > <= >= eq eql equal not null member memq assoc assq
    stringp numberp integerp consp listp atom symbolp zerop))

(defun ert--let-binds (syms args)
  (if (null syms) nil
    (cons (list (car syms) (car args)) (ert--let-binds (cdr syms) (cdr args)))))

(defun ert--value-pairs (args syms)
  (if (null args) nil
    (cons (list 'cons (list 'quote (car args)) (car syms))
          (ert--value-pairs (cdr args) (cdr syms)))))

(defun ert--argsyms (n)
  (let ((i 0) (out nil))
    (while (< i n)
      (setq out (cons (intern (concat "--ert-a" (number-to-string i) "--")) out))
      (setq i (1+ i)))
    (reverse out)))

(defmacro should (form)
  (if (and (consp form) (memq (car form) ert--explain-fns))
      (let* ((fn (car form))
             (args (cdr form))
             (syms (ert--argsyms (length args))))
        `(let ,(ert--let-binds syms args)
           (if (,fn ,@syms) t
             (signal 'ert-test-failed
                     (list 'should ',form :values (list ,@(ert--value-pairs args syms)))))))
    `(if ,form t (signal 'ert-test-failed (list 'should ',form)))))

(defmacro should-not (form)
  `(if ,form (signal 'ert-test-failed (list 'should-not ',form)) t))

(defmacro ert-info (_spec &rest body)
  ;; Compatibility shim: real ERT attaches the info string to failure reports
  ;; (which needs the ERT UI); here `ert-info` simply evaluates its BODY.
  `(progn ,@body))

(defmacro should-error (form &rest keys)
  (let* ((type (plist-get keys :type))
         (check (if type (list 'not (list 'eq (list 'car '--ert-c--) type)) nil)))
    `(let ((--ert-c-- (condition-case --ert-e-- (progn ,form 'ert--no-error)
                        (error --ert-e--))))
       (cond
        ((eq --ert-c-- 'ert--no-error)
         (signal 'ert-test-failed (list 'should-error :no-error ',form)))
        (,check
         (signal 'ert-test-failed (list 'should-error :wrong-type --ert-c--)))
        (t --ert-c--)))))

(defmacro skip-unless (form)
  `(unless ,form (signal 'ert-test-skipped (list 'skip-unless ',form))))

(defun ert-fail (data) (signal 'ert-test-failed data))
(defun ert-pass () t)

(defmacro ert-deftest (name arglist &rest body)
  (declare (doc-string 3) (indent 2))
  ;; Strip an optional docstring, then leading :expected-result / :tags args.
  (if (stringp (car body)) (setq body (cdr body)))
  (let ((expected :passed))
    (while (memq (car body) '(:expected-result :tags))
      (if (eq (car body) :expected-result) (setq expected (car (cdr body))))
      (setq body (cdr (cdr body))))
    `(progn
       (defun ,name ,arglist ,@body)
       (setq ert--tests (cons (cons ',name ,expected) ert--tests))
       ',name)))

(defun ert-run-tests-batch ()
  ;; Test ORDER is by name, not by definition order.  `ert-select-tests' walks
  ;; `ert--test-obarray' and `ert-run-tests-batch' takes them as they come out,
  ;; which for an obarray is alphabetical -- measured on 30.2 with ten
  ;; deliberately unsorted names (defined q7 b2 z9 a1 m5 c3 y8 d4 x6 e0, run
  ;; a1 b2 c3 d4 e0 m5 q7 x6 y8 z9).  Running in definition order let a test
  ;; depend on an earlier one's side effects and pass here while failing under
  ;; `emacs -Q --batch -l'.
  (let ((tests (sort (reverse ert--tests)
                     (lambda (a b) (string-lessp (symbol-name (car a))
                                                 (symbol-name (car b))))))
        (total 0) (unexpected 0) (skipped 0))
    (while tests
      (let* ((entry (car tests)) (name (car entry)) (expected (cdr entry)))
        (setq total (1+ total))
        (condition-case --ert-err--
            ;; `ert--run-test-internal' (ert.el:796) runs the body inside
            ;; `(with-temp-buffer (save-window-excursion …))', so a test body
            ;; starts in ` *temp*' with the standard syntax table -- not in
            ;; `*scratch*' under `emacs-lisp-mode-syntax-table'.  Measured:
            ;;   emacs:   TOP buf="*scratch*" cs.=95  BODY buf=" *temp*"  cs.=46
            ;; and elisprs used to answer 95 in the body too.
            (with-temp-buffer
              (funcall name)
              (if (eq expected :failed)
                  (progn (setq unexpected (1+ unexpected))
                         (message "  UNEXPECTED-OK  %s" name))
                (message "  PASS   %s" name)))
          (ert-test-skipped
           (setq skipped (1+ skipped))
           (message "  SKIP   %s" name))
          (error
           (if (eq expected :failed)
               (message "  XFAIL  %s" name)
             (progn (setq unexpected (1+ unexpected))
                    (message "  FAIL   %s -- %S" name --ert-err--))))))
      (setq tests (cdr tests)))
    (message "Ran %d tests: %d unexpected, %d skipped." total unexpected skipped)
    unexpected))

(defun ert-run-tests-batch-and-exit ()
  "Run all tests; raise an error (→ non-zero exit) on any unexpected result."
  (let ((bad (ert-run-tests-batch)))
    (if (> bad 0) (error "%d unexpected ERT result(s)" bad) t)))

;;; ---- oclosure (Open Closures) ----
;; Faithful port of emacs-lisp/oclosure.el (Emacs 30.2).  An OClosure is a
;; closure that also carries a type (for cl-generic dispatch) and named,
;; optionally-mutable slots reachable from outside via generated accessors.
;;
;; elisprs divergences from oclosure.el (NAMED — the observable API matches the
;; Emacs binary exactly; only the host-specific internals differ):
;;  * The C primitives `oclosure--get/--set/--copy/--fix-type', `oclosure-type'
;;    and `closurep' are Rust builtins (src/builtins.rs), because elisprs closures
;;    are compiled (a fusevm Chunk + captured env), not aref-indexable
;;    interpreted-functions.  Slot values live in the closure's captured lexical
;;    env (the same storage the body reads), so `oclosure--set' and an in-body
;;    `setq' stay mutually visible — exactly as Emacs stores slots in the env.
;;  * `oclosure-define' installs the class AND the accessors/copiers in one
;;    runtime call (`oclosure--define'); Emacs splits this across an
;;    eval-and-compile class registration and a compile-time
;;    `oclosure--define-functions' macro.  Merging is safe because top-level forms
;;    are evaluated in order, so the class is registered before the next form's
;;    macroexpansion (which `oclosure-lambda' needs).
;;  * The cl--class / cl-slot-descriptor substrate (from cl-preloaded.el) is
;;    provided here minimally: the `closure' parent is a plain class object rather
;;    than the full built-in-type hierarchy.
;;  * The cl-print pretty-printer methods for accessors are omitted (cosmetic).

;; -- helpers not yet in the prelude --

;; macroexp--fgrep (macroexp.el:724): return those of BINDINGS whose var/func
;; symbol appears anywhere in SEXP — a poor-man's free-variable test used by
;; cl-generic to decide whether a method body references `cl-call-next-method'.
;; Faithful port, including the tortoise/hare cycle guard for cyclic data.
(defun macroexp--fgrep (bindings sexp)
  (let ((res '())
        (seen (make-hash-table :test #'eq))
        (sexpss (list (list sexp))))
    (while (and sexpss bindings)
      (let ((sexps (pop sexpss)))
        (unless (gethash sexps seen)
          (puthash sexps t seen)
          (if (vectorp sexps) (setq sexps (mapcar #'identity sexps)))
          (let ((tortoise sexps) (skip t))
            (while sexps
              (let ((sexp (if (consp sexps) (pop sexps)
                            (prog1 sexps (setq sexps nil)))))
                (if skip
                    (setq skip nil)
                  (setq tortoise (cdr tortoise))
                  (if (eq tortoise sexps)
                      (setq sexps nil)
                    (setq skip t)))
                (cond
                 ((or (consp sexp) (vectorp sexp)) (push sexp sexpss))
                 (t
                  (let ((tmp (assq sexp bindings)))
                    (when tmp
                      (push tmp res)
                      (setq bindings (remove tmp bindings))))))))))))
    res))

(defconst cl--lambda-list-keywords
  '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))

(defun cl--arglist-args (args)
  (if (not (listp args)) (list args)
    (let ((res nil) (kind nil) arg)
      (while (consp args)
        (setq arg (pop args))
        (if (memq arg cl--lambda-list-keywords) (setq kind arg)
          (if (eq arg '&cl-defs) (pop args)
            (and (consp arg) kind (setq arg (car arg)))
            (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
            (setq res (nconc res (cl--arglist-args arg))))))
      (nconc res (and args (list args))))))

(defun gv-setter (name)
  "Return the symbol where the (setf NAME) function should be placed."
  (intern (format "(setf %s)" name)))

;; -- cl--class / cl-slot-descriptor substrate (subset of cl-preloaded.el) --
(defun cl--find-class (name) (get name 'cl--class))

(cl-defstruct (cl-slot-descriptor
               (:conc-name cl--slot-descriptor-)
               (:constructor nil)
               (:constructor cl--make-slot-descriptor (name &optional initform type props)))
  name initform type props)

(cl-defstruct (cl--class (:constructor nil))
  name docstring parents slots index-table)

(cl-defstruct (oclosure--class (:include cl--class))
  allparents)

;; -- built-in type class registry (faithful port of cl-preloaded.el) --
;; cl-generic's typeof generalizer dispatches on the class DAG registered here:
;; `cl--generic-type-specializers' looks up the class of `cl-type-of' and walks
;; `cl--class-allparents'.  Without this, cl-generic-generalizers signals
;; "Unknown specializer integer" on the built-in-type prefill in cl-generic.el.

;; cl-preloaded.el:299 — the linearised parent list, most specific first.
(defun cl--class-allparents (class)
  (cons (cl--class-name class)
        (merge-ordered-lists (mapcar #'cl--class-allparents
                                     (cl--class-parents class)))))

;; cl-preloaded.el:304 — type descriptors for built-in types.
(cl-defstruct (built-in-class
               (:include cl--class)
               (:noinline t)
               (:constructor nil)
               (:constructor built-in-class--make (name docstring parents))
               (:copier nil))
  "Type descriptors for built-in types.
The `slots' (and hence `index-table') are currently unused."
  )

;; cl-preloaded.el:314 — register a built-in type NAME with PARENTS.
(defmacro cl--define-built-in-type (name parents &optional docstring &rest slots)
  (declare (indent 2) (doc-string 3))
  (unless (listp parents) (setq parents (list parents)))
  (unless (or parents (eq name t))
    (error "Missing parents for %S: %S" name parents))
  (let ((predicate (intern-soft (format
                                 (if (string-match "-" (symbol-name name))
                                     "%s-p" "%sp")
                                 name))))
    (unless (fboundp predicate) (setq predicate nil))
    (while (keywordp (car slots))
      (let ((kw (pop slots)) (val (pop slots)))
        (pcase kw
          (:predicate (setq predicate val))
          (_ (error "Unknown keyword arg: %S" kw)))))
    `(progn
       ,(if predicate `(put ',name 'cl-deftype-satisfies #',predicate)
          nil)
       (put ',name 'cl--class
            (built-in-class--make ',name ,docstring
                                  (mapcar (lambda (type)
                                            (let ((class (get type 'cl--class)))
                                              (unless class
                                                (error "Unknown type: %S" type))
                                              class))
                                          ',parents))))))

;; cl-preloaded.el:353 — like `functionp' but nil for lists and symbols.
(defun cl-functionp (object)
  "Return non-nil if OBJECT is a member of type `function'.
This is like `functionp' except that it returns nil for all lists and symbols,
regardless if `funcall' would accept to call them."
  (memq (cl-type-of object)
        '(primitive-function native-comp-function module-function
          interpreted-function byte-code-function)))

;; cl-preloaded.el:361-472 — the built-in type DAG, parents before children.
(cl--define-built-in-type t nil "Abstract supertype of everything.")
(cl--define-built-in-type atom t "Abstract supertype of anything but cons cells."
                          :predicate atom)
(cl--define-built-in-type tree-sitter-compiled-query atom)
(cl--define-built-in-type tree-sitter-node atom)
(cl--define-built-in-type tree-sitter-parser atom)
(when (fboundp 'user-ptrp)
  (cl--define-built-in-type user-ptr atom nil
                            :predicate user-ptrp))
(cl--define-built-in-type font-object atom)
(cl--define-built-in-type font-entity atom)
(cl--define-built-in-type font-spec atom)
(cl--define-built-in-type condvar atom)
(cl--define-built-in-type mutex atom)
(cl--define-built-in-type thread atom)
(cl--define-built-in-type terminal atom)
(cl--define-built-in-type hash-table atom)
(cl--define-built-in-type frame atom)
(cl--define-built-in-type buffer atom)
(cl--define-built-in-type window atom)
(cl--define-built-in-type process atom)
(cl--define-built-in-type finalizer atom)
(cl--define-built-in-type window-configuration atom)
(cl--define-built-in-type overlay atom)
(cl--define-built-in-type number-or-marker atom
  "Abstract supertype of both `number's and `marker's.")
(cl--define-built-in-type symbol atom
  "Type of symbols."
  (name     symbol-name)
  (value    symbol-value)
  (function symbol-function)
  (plist    symbol-plist))
(cl--define-built-in-type obarray atom)
(cl--define-built-in-type native-comp-unit atom)
(cl--define-built-in-type sequence t "Abstract supertype of sequences.")
(cl--define-built-in-type list sequence)
(cl--define-built-in-type array (sequence atom) "Abstract supertype of arrays.")
(cl--define-built-in-type number (number-or-marker)
  "Abstract supertype of numbers.")
(cl--define-built-in-type float (number))
(cl--define-built-in-type integer-or-marker (number-or-marker)
  "Abstract supertype of both `integer's and `marker's.")
(cl--define-built-in-type integer (number integer-or-marker))
(cl--define-built-in-type marker (integer-or-marker))
(cl--define-built-in-type bignum (integer)
  "Type of those integers too large to fit in a `fixnum'.")
(cl--define-built-in-type fixnum (integer)
  "Type of small (fixed-size) integers.")
(cl--define-built-in-type boolean (symbol)
  "Type of the canonical boolean values, i.e. either nil or t.")
(cl--define-built-in-type symbol-with-pos (symbol)
  "Type of symbols augmented with source-position information.")
(cl--define-built-in-type vector (array))
(cl--define-built-in-type record (atom)
  "Abstract type of objects with slots.")
(cl--define-built-in-type bool-vector (array) "Type of bitvectors.")
(cl--define-built-in-type char-table (array)
  "Type of special arrays that are indexed by characters.")
(cl--define-built-in-type string (array))
(cl--define-built-in-type null (boolean list)
  "Type of the nil value."
  :predicate null)
(cl--define-built-in-type cons (list)
  "Type of cons cells."
  (car car) (cdr cdr))
(cl--define-built-in-type function (atom)
  "Abstract supertype of function values.")
(cl--define-built-in-type compiled-function (function)
  "Abstract type of functions that have been compiled.")
(cl--define-built-in-type closure (function)
  "Abstract type of functions represented by a vector-like object.")
(cl--define-built-in-type byte-code-function (compiled-function closure)
  "Type of functions that have been byte-compiled.")
(cl--define-built-in-type subr (atom)
  "Abstract type of functions compiled to machine code.")
(cl--define-built-in-type module-function (function)
  "Type of functions provided via the module API.")
(cl--define-built-in-type interpreted-function (closure)
  "Type of functions that have not been compiled.")
(cl--define-built-in-type special-form (subr)
  "Type of the core syntactic elements of the Emacs Lisp language.")
(cl--define-built-in-type native-comp-function (subr compiled-function)
  "Type of functions that have been compiled by the native compiler.")
(cl--define-built-in-type primitive-function (subr compiled-function)
  "Type of functions hand written in C.")

;; cl-preloaded.el: the derived types defined alongside the built-in ones.
(cl-deftype natnum  () (declare (parents integer)) '(satisfies natnump))
(cl-deftype keyword () (declare (parents symbol)) '(satisfies keywordp))
(cl-deftype command () '(satisfies commandp))
;; cl-macs.el: the character and real-number derived types.
(cl-deftype character () (declare (parents fixnum natnum))
            '(and fixnum natnum))
(cl-deftype base-char () (declare (parents character))
            '(satisfies characterp))
(cl-deftype extended-char () (declare (parents character))
            '(and character (not base-char)))
(cl-deftype real (&optional min max)
  (list 'and 'number
        (if (memq min '(* nil)) t
          `(satisfies . ,(if (consp min)
                             (lambda (val) (> val (car min)))
                           (lambda (val) (>= val min)))))
        (if (memq max '(* nil)) t
          `(satisfies . ,(if (consp max)
                             (lambda (val) (< val (car max)))
                           (lambda (val) (<= val max)))))))

;; -- cl-defstruct class registry (faithful subset of cl-preloaded.el) --
;; cl-generic's typeof generalizer also dispatches on cl-defstruct types: it
;; needs `cl--find-class NAME' to return a `cl-structure-class' object.  Every
;; `cl-defstruct' now registers one (see the guarded form emitted by the macro);
;; the two metaclasses below and their parent chain (record → cl-structure-object
;; → cl--class → cl-structure-class) are bootstrapped by hand, matching the DAG
;; `cl--class-allparents' walks (binary-verified against GNU Emacs 30.2).

;; cl-preloaded.el:207 — the type of CL struct descriptors.  Extra slots beyond
;; those inherited from cl--class are kept for layout fidelity though the
;; cluster's load path only reads name/parents.
(cl-defstruct (cl-structure-class
               (:include cl--class)
               (:conc-name cl--struct-class-)
               (:predicate cl--struct-class-p)
               (:constructor nil)
               (:constructor cl--struct-new-class
                (name docstring parents type named slots index-table
                      children-sym tag print))
               (:copier nil))
  "The type of CL structs descriptors."
  (tag nil) (type nil) (named nil) (print nil) (children-sym nil))

;; cl-preloaded.el:232 — the root parent of all "normal" CL structs.
(cl-defstruct (cl-structure-object
               (:predicate cl-struct-p)
               (:constructor nil)
               (:copier nil))
  "The root parent of all \"normal\" CL structs")

;; Bootstrap the metaclass chain by hand (the `cl-defstruct' auto-registration
;; above short-circuits until cl-structure-object is registered).
(put 'cl-structure-object 'cl--class
     (cl--struct-new-class 'cl-structure-object nil (list (cl--find-class 'record))
                           nil nil nil nil nil nil nil))
(put 'cl--class 'cl--class
     (cl--struct-new-class 'cl--class nil (list (cl--find-class 'cl-structure-object))
                           nil nil nil nil nil nil nil))
(put 'cl-structure-class 'cl--class
     (cl--struct-new-class 'cl-structure-class nil (list (cl--find-class 'cl--class))
                           nil nil nil nil nil nil nil))

(defun oclosure--index-table (slotdescs)
  (let ((i -1)
        (it (make-hash-table :test 'eq)))
    (dolist (desc slotdescs)
      (let ((slot (cl--slot-descriptor-name desc)))
        (cl-incf i)
        (when (gethash slot it)
          (error "Duplicate slot name: %S" slot))
        (setf (gethash slot it) i)))
    it))

(defun oclosure--class-make (name docstring slots parents allparents)
  (make-oclosure--class :name name :docstring docstring :parents parents
                        :slots slots :index-table (oclosure--index-table slots)
                        :allparents allparents))

;; The `closure' parent class (minimal), then the `oclosure' root.
(setf (cl--find-class 'closure)
      (make-oclosure--class :name 'closure :allparents '(closure)))
(setf (cl--find-class 'oclosure)
      (oclosure--class-make 'oclosure
                            "The root parent of all OClosure types"
                            nil (list (cl--find-class 'closure))
                            '(oclosure)))

(defun oclosure--p (oclosure)
  (not (not (oclosure-type oclosure))))
(cl-deftype oclosure () '(satisfies oclosure--p))

(defun oclosure--slot-mutable-p (slotdesc)
  (not (alist-get :read-only (cl--slot-descriptor-props slotdesc))))

(defun oclosure--build-class (name docstring parent-names slots)
  (cl-assert (null (cdr parent-names)))
  (let* ((parent-class (let ((pname (or (car parent-names) 'oclosure)))
                         (or (cl--find-class pname)
                             (error "Unknown class: %S" pname))))
         (slotdescs
          (append
           (oclosure--class-slots parent-class)
           (mapcar (lambda (field)
                     (if (not (consp field))
                         (cl--make-slot-descriptor field nil nil
                                                   '((:read-only . t)))
                       (let ((sname (pop field))
                             (type nil)
                             (read-only t)
                             (props '()))
                         (while field
                           (pcase (pop field)
                             (:mutable (setq read-only (not (car field))))
                             (:type (setq type (car field)))
                             (p (message "Unknown property: %S" p)
                                (push (cons p (car field)) props)))
                           (setq field (cdr field)))
                         (cl--make-slot-descriptor sname nil type
                                                   `((:read-only . ,read-only)
                                                     ,@props)))))
                   slots))))
    (oclosure--class-make name docstring slotdescs
                          (if (cdr parent-names)
                              (oclosure--class-parents parent-class)
                            (list parent-class))
                          (cons name (oclosure--class-allparents
                                      parent-class)))))

(defun oclosure--defstruct-make-copiers (copiers slotdescs name)
  (let* ((mutables '())
         (slots (mapcar
                 (lambda (desc)
                   (let ((sname (cl--slot-descriptor-name desc)))
                     (when (oclosure--slot-mutable-p desc)
                       (push sname mutables))
                     sname))
                 slotdescs)))
    (mapcar
     (lambda (copier)
       (pcase-let*
           ((cname (pop copier))
            (args (or (pop copier) `(&key ,@slots)))
            (inline (and (eq :inline (car copier)) (pop copier)))
            (doc (or (pop copier)
                     (format "Copier for objects of type `%s'." name)))
            (obj (make-symbol "obj"))
            (absent (make-symbol "absent"))
            (anames (cl--arglist-args args))
            (mnames
             (let ((res '()) (tmp args))
               (while (and tmp (not (memq (car tmp) cl--lambda-list-keywords)))
                 (push (pop tmp) res))
               res))
            (has-kw (let ((k nil))
                      (dolist (a args)
                        (when (memq a cl--lambda-list-keywords) (setq k t)))
                      k))
            (index -1)
            (mutlist '())
            (argvals
             (mapcar
              (lambda (slot)
                (setq index (1+ index))
                (let* ((mutable (memq slot mutables))
                       (get `(oclosure--get ,obj ,index ,(not (not mutable)))))
                  (push mutable mutlist)
                  (cond
                   ((not (memq slot anames)) get)
                   ((memq slot mnames) slot)
                   (t `(if (eq ',absent ,slot) ,get ,slot)))))
              slots)))
         `(,(if inline 'cl-defsubst 'cl-defun) ,cname
           ,(if has-kw `(&cl-defs (',absent) ,obj ,@args) `(,obj ,@args))
           ,doc
           (oclosure--copy ,obj ',(if (remq nil mutlist) (nreverse mutlist))
                           ,@argvals))))
     copiers)))

(defun oclosure--install-functions (name copiers)
  (let* ((class (cl--find-class name))
         (slotdescs (oclosure--class-slots class))
         (i -1))
    (dolist (desc slotdescs)
      (setq i (1+ i))
      (let* ((slot (cl--slot-descriptor-name desc))
             (mutable (oclosure--slot-mutable-p desc))
             (aname (intern (format "%S--%S" name slot))))
        (if (not mutable)
            (defalias aname
              (oclosure--copy oclosure--accessor-prototype nil name slot i))
          (defalias aname
            (oclosure--accessor-copy oclosure--mut-getter-prototype name slot i))
          (defalias (gv-setter aname)
            (oclosure--accessor-copy oclosure--mut-setter-prototype name slot i)))))
    (dolist (form (oclosure--defstruct-make-copiers copiers slotdescs name))
      (eval form t))))

(defun oclosure--define (name docstring parent-names slots &rest props)
  (let* ((class (oclosure--build-class name docstring parent-names slots))
         (pred (lambda (oclosure)
                 (let ((type (oclosure-type oclosure)))
                   (when type
                     (memq name (oclosure--class-allparents
                                 (cl--find-class type)))))))
         (predname (or (plist-get props :predicate)
                       (intern (format "%s--internal-p" name)))))
    (setf (cl--find-class name) class)
    (dolist (slot (oclosure--class-slots class))
      (put (cl--slot-descriptor-name slot) 'slot-name t))
    (defalias predname pred)
    (put name 'cl-deftype-satisfies predname)
    (oclosure--install-functions name (plist-get props :copiers))
    name))

(defmacro oclosure-define (name &optional docstring &rest slots)
  "Define a new OClosure type."
  (declare (doc-string 2) (indent 1))
  (unless (or (stringp docstring) (null docstring))
    (push docstring slots)
    (setq docstring nil))
  (let* ((options (when (consp name)
                    (prog1 (copy-sequence (cdr name))
                      (setq name (car name)))))
         (get-opt (lambda (opt &optional all)
                    (let ((val (assq opt options))
                          tmp)
                      (when val (setq options (delq val options)))
                      (if (not all)
                          (cdr val)
                        (when val
                          (setq val (list (cdr val)))
                          (while (setq tmp (assq opt options))
                            (push (cdr tmp) val)
                            (setq options (delq tmp options)))
                          (nreverse val))))))
         (predicate (car (funcall get-opt :predicate)))
         (parent-names (or (funcall get-opt :parent)
                           (funcall get-opt :include)))
         (copiers (funcall get-opt :copier 'all)))
    `(oclosure--define ',name ,docstring ',parent-names ',slots
                       ,@(when predicate `(:predicate ',predicate))
                       :copiers ',copiers)))

(defmacro oclosure--lambda (type bindings mutables args &rest body)
  "Low level construction of an OClosure object."
  (declare (indent 3) (debug (sexp (&rest (sexp form)) sexp def-body)))
  (let* ((parsed (macroexp-parse-body body))
         (prebody (car parsed))
         (realbody (cdr parsed))
         (slotnames (mapcar #'car bindings)))
    `(let ,(mapcar (lambda (bind)
                     (if (cdr bind) bind
                       `(,(car bind) (progn nil))))
                   (reverse bindings))
       (oclosure--fix-type ,type ',slotnames ',mutables
         (lambda ,args
           ,@prebody
           (if t nil ,@slotnames
               ,@(mapcar (lambda (m) `(setq ,m ,m)) mutables))
           ,@realbody)))))

(defmacro oclosure-lambda (type-and-slots args &rest body)
  "Define anonymous OClosure function."
  (declare (indent 2))
  (let* ((type (car type-and-slots))
         (fields (cdr type-and-slots))
         (class (or (cl--find-class type)
                    (error "Unknown class: %S" type)))
         (slots (oclosure--class-slots class))
         (mutables '())
         (slotbinds (mapcar (lambda (slot)
                              (let ((sname (cl--slot-descriptor-name slot)))
                                (when (oclosure--slot-mutable-p slot)
                                  (push sname mutables))
                                (list sname)))
                            slots))
         (tempbinds (mapcar
                     (lambda (field)
                       (let* ((fname (car field))
                              (bind (assq fname slotbinds)))
                         (cond
                          ((not bind) (error "Unknown slot: %S" fname))
                          ((cdr bind) (error "Duplicate slot: %S" fname))
                          (t (let ((temp (gensym "temp")))
                               (setcdr bind (list temp))
                               (cons temp (cdr field)))))))
                     fields)))
    `(let ,tempbinds
       (oclosure--lambda ',type ,slotbinds ,mutables ,args ,@body))))

(defun oclosure--slot-index (oclosure slotname)
  (gethash slotname
           (oclosure--class-index-table
            (cl--find-class (oclosure-type oclosure)))))

(defun oclosure--slot-value (oclosure slotname)
  (let ((class (cl--find-class (oclosure-type oclosure)))
        (index (oclosure--slot-index oclosure slotname)))
    (oclosure--get oclosure index
                   (oclosure--slot-mutable-p
                    (nth index (oclosure--class-slots class))))))

(defun oclosure--set-slot-value (oclosure slotname value)
  (let ((class (cl--find-class (oclosure-type oclosure)))
        (index (oclosure--slot-index oclosure slotname)))
    (unless (oclosure--slot-mutable-p
             (nth index (oclosure--class-slots class)))
      (signal 'setting-constant (list oclosure slotname)))
    (oclosure--set value oclosure index)))

;; Accessor prototype + the `accessor'/`oclosure-accessor' types (bootstrapped
;; exactly like oclosure.el).
(defconst oclosure--accessor-prototype
  (oclosure--lambda 'oclosure-accessor ((type) (slot) (index)) nil
    (oclosure) (oclosure--get oclosure index nil)))

(oclosure-define accessor
  "OClosure function to access a specific slot of an object."
  type slot)

(oclosure-define (oclosure-accessor
                  (:parent accessor)
                  (:copier oclosure--accessor-copy (type slot index)))
  "OClosure function to access a specific slot of an OClosure function."
  index)

(defconst oclosure--mut-getter-prototype
  (oclosure-lambda (oclosure-accessor (type) (slot) (index)) (oclosure)
    (oclosure--get oclosure index t)))
(defconst oclosure--mut-setter-prototype
  (oclosure-lambda (oclosure-accessor (type) (slot) (index)) (val oclosure)
    (oclosure--set val oclosure index)))

(oclosure-define (save-some-buffers-function
                  (:predicate save-some-buffers-function--p)))

(oclosure-define (cconv--interactive-helper) fun if)
(defun cconv--interactive-helper (fun if)
  "Add interactive \"form\" IF to FUN."
  (oclosure-lambda (cconv--interactive-helper (fun fun) (if if))
      (&rest args)
    (apply (if (called-interactively-p 'any)
               #'funcall-interactively #'funcall)
           fun args)))

(provide 'oclosure)

;;; ---- coding systems (predicate/registry subset) ----
;; Faithful to GNU Emacs 30.2's built-in coding-system registry. Only the
;; registration/predicate surface is ported: `coding-system-p', `coding-system-base',
;; `coding-system-list', `check-coding-system'.  The actual encode/decode machinery
;; (define-coding-system-internal and the charset codecs) is not implemented here.
;; Registry data captured value-for-value from `emacs -Q --batch' via
;; (coding-system-list) and (coding-system-list t).
(define-error 'coding-system-error "Invalid coding system")

(defconst coding-system--all
  '(
    binary no-conversion undecided prefer-utf-8 raw-text no-conversion-multibyte latin-1 iso-8859-1
    iso-latin-1 emacs-mule cp65001 mule-utf-8 utf-8 utf-8-with-signature utf-8-auto utf-8-emacs
    utf-16le utf-16be utf-16-le utf-16le-with-signature utf-16-be utf-16be-with-signature utf-16 iso-2022-7bit
    iso-2022-7bit-ss2 iso-2022-int-1 iso-2022-7bit-lock iso-2022-cjk iso-2022-7bit-lock-ss2 iso-2022-8bit-ss2 ctext x-ctext
    compound-text ctext-no-compositions ctext-with-extensions x-ctext-with-extensions compound-text-with-extensions ascii iso-safe us-ascii
    utf-7 utf-7-imap chinese-iso-7bit iso-2022-cn iso-2022-cn-ext gb2312 cn-gb euc-cn
    euc-china cn-gb-2312 chinese-iso-8bit hz hz-gb-2312 chinese-hz cp950 cn-big5
    big5 chinese-big5 cn-big5-hkscs big5-hkscs chinese-big5-hkscs euc-taiwan euc-tw windows-936
    cp936 gbk chinese-gbk gb18030 chinese-gb18030 iso-8859-5 cyrillic-iso-8bit cp878
    koi8 koi8-r cyrillic-koi8 koi8-u alternativnyj cyrillic-alternativnyj cp866 koi8-t
    cp1251 windows-1251 cp866u ruscii cp1125 ibm855 cp855 mik
    pt154 devanagari in-is13194-devanagari ebcdic-us ebcdic-uk cp1047 ibm1047 cp038
    ebcdic-int ibm038 latin-2 iso-8859-2 iso-latin-2 latin-3 iso-8859-3 iso-latin-3
    latin-4 iso-8859-4 iso-latin-4 latin-5 iso-8859-9 iso-latin-5 latin-6 iso-8859-10
    iso-latin-6 latin-7 iso-8859-13 iso-latin-7 latin-8 iso-8859-14 iso-latin-8 latin-0
    latin-9 iso-8859-15 iso-latin-9 cp1250 windows-1250 cp1252 windows-1252 cp1254
    windows-1254 cp1257 windows-1257 cp256 ebcdic-int1 ibm256 cp273 ibm273
    cp274 ebcdic-be ibm274 cp275 ebcdic-br ibm275 cp277 ebcdic-cp-no
    ebcdic-cp-dk ibm277 cp278 ebcdic-cp-se ebcdic-cp-fi ibm278 cp280 ebcdic-cp-it
    ibm280 cp284 ebcdic-cp-es ibm284 cp285 ebcdic-cp-gb ibm285 cp297
    ebcdic-cp-fr ibm297 ibm775 cp775 ibm850 cp850 ibm852 cp852
    ibm857 cp857 cp858 ibm860 cp860 ibm861 cp861 ibm863
    cp863 ibm865 cp865 ibm437 cp437 macintosh mac-roman next
    roman8 hp-roman8 adobe-standard-encoding latin-10 iso-8859-16 iso-latin-10 iso-8859-7 greek-iso-8bit
    cp1253 windows-1253 cp737 ibm851 cp851 ibm869 cp869 iso-8859-8-i
    iso-8859-8-e iso-8859-8 hebrew-iso-8bit cp1255 windows-1255 ibm862 cp862 junet
    iso-2022-jp iso-2022-jp-2 sjis shift_jis japanese-shift-jis cp932 japanese-cp932 old-jis
    iso-2022-jp-1978-irv japanese-iso-7bit-1978-irv euc-jp euc-japan euc-japan-1990 japanese-iso-8bit eucjp-ms iso-2022-jp-3
    iso-2022-jp-2004 euc-jisx0213 euc-jis-2004 shift_jis-2004 japanese-shift-jis-2004 cp281 ebcdic-jp-e ibm281
    cp290 ebcdic-jp-kana ibm290 ks_c_5601-1987 euc-korea euc-kr korean-iso-8bit korean-iso-7bit-lock
    iso-2022-kr cp949 korean-cp949 lao tis-620 tis620 th-tis620 thai-tis620
    ibm874 cp874 iso-8859-11 tibetan tibetan-iso-8bit viscii vietnamese-viscii tcvn-5712
    tcvn vietnamese-tcvn vscii vietnamese-vscii viqr vietnamese-viqr cp1258 windows-1258
    iso-8859-6 cp1256 windows-1256 georgian-ps georgian-academy
    )
  "All built-in coding-system names (base systems and aliases), GNU Emacs 30.2.")

(defconst coding-system--alias-alist
  '(
    (binary . no-conversion) (latin-1 . iso-latin-1) (iso-8859-1 . iso-latin-1) (cp65001 . utf-8)
    (mule-utf-8 . utf-8) (utf-16-le . utf-16le-with-signature) (utf-16-be . utf-16be-with-signature) (iso-2022-int-1 . iso-2022-7bit-lock)
    (iso-2022-cjk . iso-2022-7bit-lock-ss2) (ctext . compound-text) (x-ctext . compound-text) (ctext-with-extensions . compound-text-with-extensions)
    (x-ctext-with-extensions . compound-text-with-extensions) (ascii . us-ascii) (iso-safe . us-ascii) (chinese-iso-7bit . iso-2022-cn)
    (gb2312 . chinese-iso-8bit) (cn-gb . chinese-iso-8bit) (euc-cn . chinese-iso-8bit) (euc-china . chinese-iso-8bit)
    (cn-gb-2312 . chinese-iso-8bit) (hz . chinese-hz) (hz-gb-2312 . chinese-hz) (cp950 . chinese-big5)
    (cn-big5 . chinese-big5) (big5 . chinese-big5) (cn-big5-hkscs . chinese-big5-hkscs) (big5-hkscs . chinese-big5-hkscs)
    (euc-taiwan . euc-tw) (windows-936 . chinese-gbk) (cp936 . chinese-gbk) (gbk . chinese-gbk)
    (gb18030 . chinese-gb18030) (iso-8859-5 . cyrillic-iso-8bit) (cp878 . cyrillic-koi8) (koi8 . cyrillic-koi8)
    (koi8-r . cyrillic-koi8) (alternativnyj . cyrillic-alternativnyj) (cp1251 . windows-1251) (cp866u . cp1125)
    (ruscii . cp1125) (ibm855 . cp855) (devanagari . in-is13194-devanagari) (cp1047 . ibm1047)
    (cp038 . ibm038) (ebcdic-int . ibm038) (latin-2 . iso-latin-2) (iso-8859-2 . iso-latin-2)
    (latin-3 . iso-latin-3) (iso-8859-3 . iso-latin-3) (latin-4 . iso-latin-4) (iso-8859-4 . iso-latin-4)
    (latin-5 . iso-latin-5) (iso-8859-9 . iso-latin-5) (latin-6 . iso-latin-6) (iso-8859-10 . iso-latin-6)
    (latin-7 . iso-latin-7) (iso-8859-13 . iso-latin-7) (latin-8 . iso-latin-8) (iso-8859-14 . iso-latin-8)
    (latin-0 . iso-latin-9) (latin-9 . iso-latin-9) (iso-8859-15 . iso-latin-9) (cp1250 . windows-1250)
    (cp1252 . windows-1252) (cp1254 . windows-1254) (cp1257 . windows-1257) (cp256 . ibm256)
    (ebcdic-int1 . ibm256) (cp273 . ibm273) (cp274 . ibm274) (ebcdic-be . ibm274)
    (cp275 . ibm275) (ebcdic-br . ibm275) (cp277 . ibm277) (ebcdic-cp-no . ibm277)
    (ebcdic-cp-dk . ibm277) (cp278 . ibm278) (ebcdic-cp-se . ibm278) (ebcdic-cp-fi . ibm278)
    (cp280 . ibm280) (ebcdic-cp-it . ibm280) (cp284 . ibm284) (ebcdic-cp-es . ibm284)
    (cp285 . ibm285) (ebcdic-cp-gb . ibm285) (cp297 . ibm297) (ebcdic-cp-fr . ibm297)
    (ibm775 . cp775) (ibm850 . cp850) (ibm852 . cp852) (ibm857 . cp857)
    (ibm860 . cp860) (ibm861 . cp861) (ibm863 . cp863) (ibm865 . cp865)
    (ibm437 . cp437) (macintosh . mac-roman) (roman8 . hp-roman8) (latin-10 . iso-latin-10)
    (iso-8859-16 . iso-latin-10) (iso-8859-7 . greek-iso-8bit) (cp1253 . windows-1253) (ibm851 . cp851)
    (ibm869 . cp869) (iso-8859-8-i . hebrew-iso-8bit) (iso-8859-8-e . hebrew-iso-8bit) (iso-8859-8 . hebrew-iso-8bit)
    (cp1255 . windows-1255) (ibm862 . cp862) (junet . iso-2022-jp) (sjis . japanese-shift-jis)
    (shift_jis . japanese-shift-jis) (cp932 . japanese-cp932) (old-jis . japanese-iso-7bit-1978-irv) (iso-2022-jp-1978-irv . japanese-iso-7bit-1978-irv)
    (euc-jp . japanese-iso-8bit) (euc-japan . japanese-iso-8bit) (euc-japan-1990 . japanese-iso-8bit) (iso-2022-jp-3 . iso-2022-jp-2004)
    (euc-jisx0213 . euc-jis-2004) (shift_jis-2004 . japanese-shift-jis-2004) (cp281 . ibm281) (ebcdic-jp-e . ibm281)
    (cp290 . ibm290) (ebcdic-jp-kana . ibm290) (ks_c_5601-1987 . korean-iso-8bit) (euc-korea . korean-iso-8bit)
    (euc-kr . korean-iso-8bit) (korean-iso-7bit-lock . iso-2022-kr) (cp949 . korean-cp949) (tis-620 . thai-tis620)
    (tis620 . thai-tis620) (th-tis620 . thai-tis620) (ibm874 . cp874) (tibetan . tibetan-iso-8bit)
    (viscii . vietnamese-viscii) (tcvn-5712 . vietnamese-vscii) (tcvn . vietnamese-vscii) (vietnamese-tcvn . vietnamese-vscii)
    (vscii . vietnamese-vscii) (viqr . vietnamese-viqr) (cp1258 . windows-1258) (cp1256 . windows-1256)
    )
  "Alist mapping each alias coding-system to its base coding-system, GNU Emacs 30.2.")

(defun coding-system--strip-eol (name)
  "Strip one trailing -unix/-dos/-mac EOL suffix from string NAME."
  (cond ((string-suffix-p "-unix" name) (substring name 0 -5))
        ((string-suffix-p "-dos" name) (substring name 0 -4))
        ((string-suffix-p "-mac" name) (substring name 0 -4))
        (t name)))

(defun coding-system-p (object)
  "Return t if OBJECT is nil or a coding system.
See the documentation of `define-coding-system' for information
about coding-system objects."
  (or (null object)
      (and (symbolp object)
           (and (memq (intern (coding-system--strip-eol (symbol-name object)))
                      coding-system--all)
                t))))

(defun coding-system-base (coding-system)
  "Return the base of CODING-SYSTEM.
Any alias or end-of-line variant resolves to its base coding system.
If CODING-SYSTEM is invalid, signal a `coding-system-error'."
  (if (null coding-system)
      'no-conversion
    (progn
      (check-coding-system coding-system)
      (let* ((base (intern (coding-system--strip-eol (symbol-name coding-system))))
             (resolved (assq base coding-system--alias-alist)))
        (if resolved (cdr resolved) base)))))

(defun coding-system-list (&optional base-only)
  "Return a list of all existing non-subsidiary coding systems.
If optional arg BASE-ONLY is non-nil, only base coding systems are listed."
  (if base-only
      (let ((result nil))
        (dolist (cs coding-system--all)
          (unless (assq cs coding-system--alias-alist)
            (push cs result)))
        (nreverse result))
    (copy-sequence coding-system--all)))

(defun check-coding-system (coding-system)
  "Check validity of CODING-SYSTEM.
If valid, return CODING-SYSTEM, else signal a `coding-system-error'."
  (if (coding-system-p coding-system)
      coding-system
    (signal 'coding-system-error (list coding-system))))

(defconst coding-system--eol-fixed
  '(no-conversion no-conversion-multibyte binary)
  "Registered coding systems whose EOL type is fixed to `unix' (0), GNU Emacs 30.2.
These have no -dos/-mac subsidiary variants, so `coding-system-eol-type'
returns the integer 0 for them rather than a vector, and no subsidiary
NAME-dos/NAME-mac coding system exists.")

(defun coding-system-eol-type (coding-system)
  "Return the EOL (end-of-line) conversion type of CODING-SYSTEM.
The value is an integer 0, 1, or 2 when CODING-SYSTEM has a fixed EOL
type (`unix', `dos', or `mac' respectively), or a vector
[BASE-unix BASE-dos BASE-mac] of the three subsidiary coding systems
when the EOL type is undecided.  BASE is the base of CODING-SYSTEM.
CODING-SYSTEM nil is treated as `no-conversion'.
Return nil if CODING-SYSTEM is not a valid coding system."
  (when (null coding-system)
    (setq coding-system 'no-conversion))
  (and (symbolp coding-system)
       (let ((name (symbol-name coding-system)))
         (cond
          ;; A directly registered base or alias (no EOL suffix to strip).
          ((memq coding-system coding-system--all)
           (if (memq coding-system coding-system--eol-fixed)
               0
             (let ((base (symbol-name (coding-system-base coding-system))))
               (vector (intern (concat base "-unix"))
                       (intern (concat base "-dos"))
                       (intern (concat base "-mac"))))))
          ;; A subsidiary NAME-unix/-dos/-mac of an EOL-undecided system.
          (t
           (let ((stem (coding-system--strip-eol name)))
             (and (not (string= stem name))
                  (let ((base (intern stem)))
                    (and (memq base coding-system--all)
                         (not (memq base coding-system--eol-fixed))
                         (cond ((string-suffix-p "-unix" name) 0)
                               ((string-suffix-p "-dos" name) 1)
                               (t 2)))))))))))

(defun coding-system-change-eol-conversion (coding-system eol-type)
  "Return a coding system which differs from CODING-SYSTEM in EOL conversion.
The returned coding system converts end-of-line by EOL-TYPE
but text as the same way as CODING-SYSTEM.
EOL-TYPE should be `unix', `dos', `mac', or nil.
If EOL-TYPE is nil, the returned coding system detects
how end-of-line is formatted automatically while decoding.

EOL-TYPE can be specified by an integer 0, 1, or 2.
They means `unix', `dos', and `mac' respectively."
  (if (symbolp eol-type)
      (setq eol-type (cond ((eq eol-type 'unix) 0)
                           ((eq eol-type 'dos) 1)
                           ((eq eol-type 'mac) 2)
                           (t eol-type))))
  ;; We call `coding-system-base' before `coding-system-eol-type',
  ;; because the coding-system may not be initialized until then.
  (let* ((base (coding-system-base coding-system))
         (orig-eol-type (coding-system-eol-type coding-system)))
    (cond ((vectorp orig-eol-type)
           (if (not eol-type)
               coding-system
             (aref orig-eol-type eol-type)))
          ((not eol-type)
           base)
          ((= eol-type orig-eol-type)
           coding-system)
          ((progn (setq orig-eol-type (coding-system-eol-type base))
                  (vectorp orig-eol-type))
           (aref orig-eol-type eol-type)))))

;;; ---- language environments (mule-cmds.el data surface) ----
;; Faithful port of GNU Emacs 30.2's `language-info-alist' machinery: the
;; registry that `set-language-info-alist' populates when a language/*.el file
;; declares a language environment.  `bindings--define-key' (bindings.el) and
;; `define-key-after' (subr.el) are the two supporting keymap helpers these
;; functions need for their menu-map bookkeeping; both are copied verbatim.
;; The heavy `set-language-environment*' switch functions are NOT ported here —
;; they only fire when a definition targets the CURRENT environment; declaring a
;; new environment (the load-time case) never touches them.  Bodies are verbatim
;; from mule-cmds.el / subr.el / bindings.el.

(defun bindings--define-key (map key item)
  "Define KEY in keymap MAP according to ITEM from a menu.
This is like `define-key', but it takes the definition from the
specified menu item, and makes pure copies of as much as possible
of the menu's data."
  (declare (indent 2))
  (define-key map key
    (cond
     ((not (consp item)) item)
     ((keymapp item) item)
     ((stringp (car item))
      (if (keymapp (cdr item))
          (cons (purecopy (car item)) (cdr item))
        (purecopy item)))
     ((eq 'menu-item (car item))
      (if (keymapp (nth 2 item))
          `(menu-item ,(purecopy (nth 1 item)) ,(nth 2 item)
                      ,@(purecopy (nthcdr 3 item)))
        (purecopy item)))
     (t (message "non-menu-item: %S" item) item))))

(defun define-key-after (keymap key definition &optional after)
  "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
This is like `define-key' except that the binding for KEY is placed
just after the binding for the event AFTER, instead of at the beginning
of the map.  Note that AFTER must be an event type (like KEY), NOT a command
\(like DEFINITION).

If AFTER is t or omitted, the new binding goes at the end of the keymap.
AFTER should be a single event type--a symbol or a character, not a sequence.

Bindings are always added before any inherited map.

The order of bindings in a keymap matters only when it is used as
a menu, so this function is not useful for non-menu keymaps."
  (declare (indent defun))
  (unless after (setq after t))
  (or (keymapp keymap)
      (signal 'wrong-type-argument (list 'keymapp keymap)))
  (setq key
	(if (<= (length key) 1) (aref key 0)
	  (setq keymap (lookup-key keymap
				   (apply #'vector
					  (butlast (mapcar #'identity key)))))
	  (aref key (1- (length key)))))
  (let ((tail keymap) done inserted)
    (while (and (not done) tail)
      ;; Delete any earlier bindings for the same key.
      (if (eq (car-safe (car (cdr tail))) key)
	  (setcdr tail (cdr (cdr tail))))
      ;; If we hit an included map, go down that one.
      (if (keymapp (car tail)) (setq tail (car tail)))
      ;; When we reach AFTER's binding, insert the new binding after.
      ;; If we reach an inherited keymap, insert just before that.
      ;; If we reach the end of this keymap, insert at the end.
      (if (or (and (eq (car-safe (car tail)) after)
		   (not (eq after t)))
	      (eq (car (cdr tail)) 'keymap)
	      (null (cdr tail)))
	  (progn
	    ;; Stop the scan only if we find a parent keymap.
	    ;; Keep going past the inserted element
	    ;; so we can delete any duplications that come later.
	    (if (eq (car (cdr tail)) 'keymap)
		(setq done t))
	    ;; Don't insert more than once.
	    (or inserted
		(setcdr tail (cons (cons key definition) (cdr tail))))
	    (setq inserted t)))
      (setq tail (cdr tail)))))

(defvar language-info-alist nil
  "Alist of language environment definitions.
Each element looks like:
	(LANGUAGE-NAME . ((KEY . INFO) ...))
where LANGUAGE-NAME is a string, the name of the language environment,
KEY is a symbol denoting the kind of information, and
INFO is the data associated with KEY.")

(defvar current-language-environment "English"
  "The last language environment specified with `set-language-environment'.")

(defvar describe-language-environment-map
  (let ((map (make-sparse-keymap "Describe Language Environment")))
    (bindings--define-key map
      [Default] '(menu-item "Default" describe-specified-language-support))
    map))

(defvar setup-language-environment-map
  (let ((map (make-sparse-keymap "Set Language Environment")))
    (bindings--define-key map
      [Default] '(menu-item "Default" setup-specified-language-environment))
    map))

(defun get-language-info (lang-env key)
  "Return information listed under KEY for language environment LANG-ENV.
KEY is a symbol denoting the kind of information.
For a list of useful values for KEY and their meanings,
see `language-info-alist'."
  (if (symbolp lang-env)
      (setq lang-env (symbol-name lang-env)))
  (let ((lang-slot (assoc-string lang-env language-info-alist t)))
    (if lang-slot
	(cdr (assq key (cdr lang-slot))))))

(defun set-language-info (lang-env key info)
  "Modify part of the definition of language environment LANG-ENV.
Specifically, this stores the information INFO under KEY
in the definition of this language environment.
KEY is a symbol denoting the kind of information.
INFO is the value for that information.

For a list of useful values for KEY and their meanings,
see `language-info-alist'."
  (if (symbolp lang-env)
      (setq lang-env (symbol-name lang-env)))
  (set-language-info-internal lang-env key info)
  (if (equal lang-env current-language-environment)
      (cond ((eq key 'coding-priority)
	     (set-language-environment-coding-systems lang-env)
	     (set-language-environment-charset lang-env))
	    ((eq key 'input-method)
	     (set-language-environment-input-method lang-env))
	    ((eq key 'nonascii-translation)
	     (set-language-environment-nonascii-translation lang-env))
	    ((eq key 'charset)
	     (set-language-environment-charset lang-env)))))

(defun set-language-info-internal (lang-env key info)
  "Internal use only.
Arguments are the same as `set-language-info'."
  (let (lang-slot key-slot)
    (setq lang-slot (assoc lang-env language-info-alist))
    (if (null lang-slot)		; If no slot for the language, add it.
	(setq lang-slot (list lang-env)
	      language-info-alist (cons lang-slot language-info-alist)))
    (setq key-slot (assq key lang-slot))
    (if (null key-slot)			; If no slot for the key, add it.
	(progn
	  (setq key-slot (list key))
	  (setcdr lang-slot (cons key-slot (cdr lang-slot)))))
    (setcdr key-slot (purecopy info))
    ;; Update the custom-type of `current-language-environment'.
    (put 'current-language-environment 'custom-type
	 (cons 'choice (mapcar
			(lambda (lang)
			  (list 'const lang))
			(sort (mapcar 'car language-info-alist) 'string<))))))

(defun set-language-info-setup-keymap (lang-env alist describe-map setup-map)
  "Setup menu items for LANG-ENV.
See `set-language-info-alist' for details of other arguments."
  (let ((doc (assq 'documentation alist)))
    (when doc
      (define-key-after describe-map (vector (intern lang-env))
	(cons lang-env 'describe-specified-language-support))))
  (define-key-after setup-map (vector (intern lang-env))
    (cons lang-env 'setup-specified-language-environment)))

(defun set-language-info-alist (lang-env alist &optional parents)
  "Store ALIST as the definition of language environment LANG-ENV.
ALIST is an alist of KEY and INFO values.  See the documentation of
`language-info-alist' for the meanings of KEY and INFO.

Optional arg PARENTS is a list of parent menu names; it specifies
where to put this language environment in the
Describe Language Environment and Set Language Environment menus.
For example, (\"European\") means to put this language environment
in the European submenu in each of those two menus."
  (cond ((symbolp lang-env)
	 (setq lang-env (symbol-name lang-env)))
	((stringp lang-env)
	 (setq lang-env (purecopy lang-env))))
  (if parents
      (while parents
	(let (describe-map setup-map parent-symbol parent prompt)
	  (if (symbolp (setq parent-symbol (car parents)))
	      (setq parent (symbol-name parent))
	    (setq parent parent-symbol parent-symbol (intern parent)))
	  (setq describe-map (lookup-key describe-language-environment-map
                                         (vector parent-symbol)))
	  ;; This prompt string is for define-prefix-command, so
	  ;; that the map it creates will be suitable for a menu.
	  (or describe-map (setq prompt (format "%s Environment" parent)))
	  (unless describe-map
	    (setq describe-map (intern (format "describe-%s-environment-map"
					       (downcase parent))))
	    (define-prefix-command describe-map nil prompt)
	    (define-key-after
              describe-language-environment-map
              (vector parent-symbol) (cons parent describe-map)))
	  (setq setup-map (lookup-key setup-language-environment-map
                                      (vector parent-symbol)))
	  (unless setup-map
	    (setq setup-map (intern (format "setup-%s-environment-map"
                                            (downcase parent))))
	    (define-prefix-command setup-map nil prompt)
	    (define-key-after
              setup-language-environment-map
              (vector parent-symbol) (cons parent setup-map)))
	  (setq parents (cdr parents))
          (set-language-info-setup-keymap
           lang-env alist
           (symbol-value describe-map) (symbol-value setup-map))))
    (set-language-info-setup-keymap
     lang-env alist
     describe-language-environment-map setup-language-environment-map))
  (dolist (elt alist)
    (set-language-info-internal lang-env (car elt) (cdr elt)))
  (if (equal lang-env current-language-environment)
      (set-language-environment lang-env)))

;;; ring.el --- handle rings of items  -*- lexical-binding: t -*-
;; Faithful port of emacs-lisp/ring.el (Emacs 30.2).  A ring is a fixed-size
;; circular buffer represented as the cons (HD LN . VEC): HD is the index of
;; the oldest element in VEC, LN the current element count, VEC the storage.

(defun ring-p (x)
  "Return t if X is a ring; nil otherwise."
  (and (consp x) (integerp (car x))
       (consp (cdr x)) (integerp (cadr x))
       (vectorp (cddr x))))

(defun make-ring (size)
  "Make a ring that can contain SIZE elements."
  (cons 0 (cons 0 (make-vector size nil))))

(defun ring-insert-at-beginning (ring item)
  "Add to RING the item ITEM, at the front, as the oldest item."
  (let* ((vec (cddr ring))
         (veclen (length vec))
         (hd (car ring))
         (ln (cadr ring)))
    (setq ln (min veclen (1+ ln))
          hd (ring-minus1 hd veclen))
    (aset vec hd item)
    (setcar ring hd)
    (setcar (cdr ring) ln)))

(defun ring-plus1 (index veclen)
  "Return INDEX+1, with wraparound."
  (let ((new-index (1+ index)))
    (if (= new-index veclen) 0 new-index)))

(defun ring-minus1 (index veclen)
  "Return INDEX-1, with wraparound."
  (- (if (zerop index) veclen index) 1))

(defun ring-length (ring)
  "Return the number of elements in the RING."
  (cadr ring))

(defun ring-index (index head ringlen veclen)
  "Convert nominal ring index INDEX to an internal index.
The internal index refers to the items ordered from newest to oldest.
HEAD is the index of the oldest element in the ring.
RINGLEN is the number of elements currently in the ring.
VECLEN is the size of the vector in the ring."
  (setq index (mod index ringlen))
  (mod (1- (+ head (- ringlen index))) veclen))

(defun ring-empty-p (ring)
  "Return t if RING is empty; nil otherwise."
  (zerop (cadr ring)))

(defun ring-size (ring)
  "Return the size of RING, the maximum number of elements it can contain."
  (length (cddr ring)))

(defun ring-copy (ring)
  "Return a copy of RING."
  (let ((vec (cddr ring))
	(hd  (car ring))
	(ln  (cadr ring)))
    (cons hd (cons ln (copy-sequence vec)))))

(defun ring-insert (ring item)
  "Insert onto ring RING the item ITEM, as the newest (last) item.
If the ring is full, dump the oldest item to make room."
  (let* ((vec (cddr ring))
         (veclen (length vec))
         (hd (car ring))
         (ln (cadr ring)))
    (prog1
        (aset vec (mod (+ hd ln) veclen) item)
      (if (= ln veclen)
          (setcar ring (ring-plus1 hd veclen))
        (setcar (cdr ring) (1+ ln))))))

(defun ring-remove (ring &optional index)
  "Remove an item from the RING.  Return the removed item.
If optional INDEX is nil, remove the oldest item.  If it's
numeric, remove the element indexed."
  (if (ring-empty-p ring)
      (error "Ring empty")
    (let* ((hd (car ring))
           (ln (cadr ring))
           (vec (cddr ring))
           (veclen (length vec))
           (tl (mod (1- (+ hd ln)) veclen))
           oldelt)
      (when (null index)
	(setq index (1- ln)))
      (setq index (ring-index index hd ln veclen))
      (setq oldelt (aref vec index))
      (while (/= index tl)
        (aset vec index (aref vec (ring-plus1 index veclen)))
        (setq index (ring-plus1 index veclen)))
      (aset vec tl nil)
      (setcar (cdr ring) (1- ln))
      oldelt)))

(defun ring-ref (ring index)
  "Return RING's INDEX element.
INDEX = 0 is the most recently inserted; higher indices
correspond to older elements.
INDEX need not be <= the ring length; the appropriate modulo operation
will be performed."
  (if (ring-empty-p ring)
      (error "Accessing an empty ring")
    (let ((hd (car ring))
	  (ln (cadr ring))
	  (vec (cddr ring)))
      (aref vec (ring-index index hd ln (length vec))))))

(defun ring-elements (ring)
  "Return a list of the elements of RING, in order, newest first."
  (let ((start (car ring))
	(size (ring-size ring))
	(vect (cddr ring))
	lst)
    (dotimes (var (cadr ring))
      (push (aref vect (mod (+ start var) size)) lst))
    lst))

(defun ring-member (ring item)
  "Return index of ITEM if on RING, else nil.
Comparison is done via `equal'.  The index is 0-based."
  (catch 'found
    (dotimes (ind (ring-length ring))
      (when (equal item (ring-ref ring ind))
	(throw 'found ind)))))

(defun ring-next (ring item)
  "Return the next item in the RING, after ITEM.
Raise error if ITEM is not in the RING."
  (let ((curr-index (ring-member ring item)))
    (unless curr-index (error "Item is not in the ring: `%s'" item))
    (ring-ref ring (ring-plus1 curr-index (ring-length ring)))))

(defun ring-previous (ring item)
  "Return the previous item in the RING, before ITEM.
Raise error if ITEM is not in the RING."
  (let ((curr-index (ring-member ring item)))
    (unless curr-index (error "Item is not in the ring: `%s'" item))
    (ring-ref ring (ring-minus1 curr-index (ring-length ring)))))

(defun ring-extend (ring x)
  "Increase the size of RING by X."
  (when (and (integerp x) (> x 0))
    (ring-resize ring (+ x (ring-size ring)))))

(defun ring-resize (ring size)
  "Set the size of RING to SIZE.
If the new size is smaller, then the oldest items in the ring are
discarded."
  (when (integerp size)
    (let ((length (ring-length ring))
	  (new-vec (make-vector size nil)))
      (if (= length 0)
          (setcdr ring (cons 0 new-vec))
        (let* ((hd (car ring))
	       (old-size (ring-size ring))
	       (old-vec (cddr ring))
               (copy-length (min size length))
               (copy-hd (mod (+ hd (- length copy-length)) length)))
          (setcdr ring (cons copy-length new-vec))
          (dotimes (j copy-length)
	    (aset new-vec j (aref old-vec (mod (+ copy-hd j) old-size))))
          (setcar ring 0))))))

(defun ring-insert+extend (ring item &optional grow-p)
  "Like `ring-insert', but if GROW-P is non-nil, then enlarge ring.
Insert onto ring RING the item ITEM, as the newest (last) item.
If the ring is full, behavior depends on GROW-P:
  If GROW-P is non-nil, enlarge the ring to accommodate the new item.
  If GROW-P is nil, dump the oldest item to make room for the new."
  (and grow-p
       (= (ring-length ring) (ring-size ring))
       (ring-extend ring 1))
  (ring-insert ring item))

(defun ring-remove+insert+extend (ring item &optional grow-p)
  "`ring-remove' ITEM from RING, then `ring-insert+extend' it.
This ensures that there is only one ITEM on RING.

If the RING is full, behavior depends on GROW-P:
  If GROW-P is non-nil, enlarge the ring to accommodate the new ITEM.
  If GROW-P is nil, dump the oldest item to make room for the new."
  (let (ind)
    (while (setq ind (ring-member ring item))
      (ring-remove ring ind)))
  (ring-insert+extend ring item grow-p))

(defun ring-convert-sequence-to-ring (seq)
  "Convert sequence SEQ to a ring.  Return the ring.
If SEQ is already a ring, return it."
  (if (ring-p seq)
      seq
    (let* ((size (length seq))
           (ring (make-ring size)))
      (dotimes (count size)
        (when (or (ring-empty-p ring)
		  (not (equal (ring-ref ring 0) (elt seq count))))
	  (ring-insert-at-beginning ring (elt seq count))))
      ring)))

;;; text-property-search.el --- search for text properties  -*- lexical-binding: t -*-
;; Faithful port of emacs-lisp/text-property-search.el (Emacs 30.2).

(cl-defstruct (prop-match)
  beginning end value)

(defun text-property-search-forward (property &optional value predicate
                                              not-current)
  "Search for next region of text where PREDICATE returns non-nil for PROPERTY.
PREDICATE is used to decide whether the value of PROPERTY at a given
buffer position should be considered as a match for VALUE.
VALUE defaults to nil if omitted.

If PREDICATE is a function, it will be called with two arguments:
VALUE and the value of PROPERTY at some buffer position.  The function
should return non-nil if these two values are to be considered a match.

Two special values of PREDICATE can also be used:
If PREDICATE is t, that means the value of PROPERTY must `equal' VALUE
to be considered a match.
If PREDICATE is nil (which is the default), the value of PROPERTY will
match if it is not `equal' to VALUE.  Furthermore, a nil PREDICATE
means that the match region ends where the value changes.  For
instance, this means that if you loop with

  (while (setq prop (text-property-search-forward \\='face))
    ...)

you will get all the distinct regions with non-nil `face' values in
the buffer, and the `prop' object will have the details about the
match.  See the manual for more details and examples about how
VALUE and PREDICATE interact.

If NOT-CURRENT is non-nil, current buffer position is not examined for
matches: the function will search for the first region that doesn't
include point and has a value of PROPERTY that matches VALUE.

If no matches can be found, return nil and don't move point.
If found, move point to the end of the region and return a
`prop-match' object describing the match.  To access the details
of the match, use `prop-match-beginning' and `prop-match-end' for
the buffer positions that limit the region, and `prop-match-value'
for the value of PROPERTY in the region."
  (interactive
   (list
    (let ((string (completing-read "Search for property: " obarray)))
      (when (> (length string) 0)
        (intern string obarray)))))
  (cond
   ((eobp)
    nil)
   ((and (text-property--match-p value (get-text-property (point) property)
                                 predicate)
         (not not-current))
    (text-property--find-end-forward (point) property value predicate))
   (t
    (let ((origin (point))
          (ended nil)
          pos)
      (while (not ended)
        (setq pos (next-single-property-change (point) property))
        (if (not pos)
            (progn
              (goto-char origin)
              (setq ended t))
          (goto-char pos)
          (if (text-property--match-p value (get-text-property (point) property)
                                      predicate)
              (setq ended
                    (text-property--find-end-forward
                     (point) property value predicate))
            (setq pos (next-single-property-change (point) property))
            (unless pos
              (goto-char origin)
              (setq ended t)))))
      (and (not (eq ended t))
           ended)))))

(defun text-property--find-end-forward (start property value predicate)
  (let (end)
    (if (and value
             (null predicate))
        (let ((ended nil))
          (while (not ended)
            (setq end (next-single-property-change (point) property))
            (if (not end)
                (progn
                  (goto-char (point-max))
                  (setq end (point)
                        ended t))
              (goto-char end)
              (unless (text-property--match-p
                       value (get-text-property (point) property) predicate)
                (setq ended t)))))
      (setq end (next-single-property-change (point) property nil (point-max)))
      (goto-char end))
    (make-prop-match :beginning start
                     :end end
                     :value (get-text-property start property))))

(defun text-property-search-backward (property &optional value predicate
                                               not-current)
  "Search for previous region of text where PREDICATE returns non-nil for PROPERTY.

Like `text-property-search-forward', which see, but searches backward,
and if a matching region is found, place point at the start of the region."
  (interactive
   (list
    (let ((string (completing-read "Search for property: " obarray)))
      (when (> (length string) 0)
        (intern string obarray)))))
  (cond
   ((bobp)
    nil)
   ((text-property--match-p
     value (get-text-property (1- (point)) property)
     predicate)
    (let ((origin (point))
          (match (text-property--find-end-backward
                  (1- (point)) property value predicate)))
      (if (and not-current
               (equal (get-text-property (point) property)
                      (get-text-property origin property)))
          (text-property-search-backward property value predicate)
        match)))
   (t
    (let ((origin (point))
          (ended nil)
          pos)
      (while (not ended)
        (setq pos (previous-single-property-change (point) property))
        (if (not pos)
            (progn
              (goto-char origin)
              (setq ended t))
          (goto-char (1- pos))
          (if (text-property--match-p value (get-text-property (point) property)
                                      predicate)
              (setq ended
                    (text-property--find-end-backward
                     (point) property value predicate))
            (setq pos (previous-single-property-change (point) property))
            (unless pos
              (goto-char origin)
              (setq ended t)))))
      (and (not (eq ended t))
           ended)))))

(defun text-property--find-end-backward (start property value predicate)
  (let (end)
    (if (and value
             (null predicate))
        (let ((ended nil))
          (while (not ended)
            (setq end (previous-single-property-change (point) property))
            (if (not end)
                (progn
                  (goto-char (point-min))
                  (setq end (point)
                        ended t))
              (goto-char (1- end))
              (unless (text-property--match-p
                       value (get-text-property (point) property) predicate)
                (goto-char end)
                (setq ended t)))))
      (setq end
            (if (and (> (point) (point-min))
                     (text-property--match-p
                      value (get-text-property (1- (point)) property)
                      predicate))
                (previous-single-property-change (point)
                                                 property nil (point-min))
              (point)))
      (goto-char end))
    (make-prop-match :beginning end
                     :end (1+ start)
                     :value (get-text-property end property))))

(defun text-property--match-p (value prop-value predicate)
  (cond
   ((eq predicate t)
    (setq predicate #'equal))
   ((eq predicate nil)
    (setq predicate (lambda (val p-val)
                      (not (equal val p-val))))))
  (funcall predicate value prop-value))

;; ---- cl-case / cl-typecase / cl-parse-integer / cl-list-length ----
;; cl-macs.el and cl-extra.el (emacs-31.1), verbatim.
(defmacro cl-case (expr &rest clauses)
  "Eval EXPR and choose among clauses on that value.
Each clause looks like (KEYLIST BODY...).  EXPR is evaluated and
compared against each key in each KEYLIST; the corresponding BODY
is evaluated.  If no clause succeeds, this macro returns nil.  A
single non-nil atom may be used in place of a KEYLIST of one
atom.  A KEYLIST of t or `otherwise' is allowed only in the final
clause, and matches if no other keys match.  Key values are
compared by `eql'.

\(fn EXPR (KEYLIST BODY...)...)"
  (declare (indent 1) (debug (form &rest (sexp body))))
  (macroexp-let2 macroexp-copyable-p temp expr
    (let* ((head-list nil)
           (has-otherwise nil))
      `(cond
        ,@(mapcar
           (lambda (c)
             (cons (cond (has-otherwise
                          (error "Misplaced t or `otherwise' clause"))
                         ((memq (car c) '(t otherwise))
                          (setq has-otherwise t)
                          t)
                         ((eq (car c) 'cl--ecase-error-flag)
                          `(error "cl-ecase failed: %s, %s"
                                  ,temp ',(reverse head-list)))
                         ((null (car c))
                          (macroexp-warn-and-return
                           "Case nil will never match"
                           nil 'suspicious))
                         ((and (consp (car c)) (cdar c) (not (cddar c))
                               (memq (caar c) '(quote function)))
                          (macroexp-warn-and-return
                           (format-message
                            (concat "Case %s will match `%s'.  If "
                                    "that's intended, write %s "
                                    "instead.  Otherwise, don't "
                                    "quote `%s'.")
                            (car c) (caar c) (list (cadar c) (caar c))
                            (cadar c))
                           `(cl-member ,temp ',(car c)) 'suspicious))
                         ((listp (car c))
                          (setq head-list (append (car c) head-list))
                          `(cl-member ,temp ',(car c)))
                         (t
                          (if (memq (car c) head-list)
                              (error "Duplicate key in case: %s"
                                     (car c)))
                          (push (car c) head-list)
                          `(eql ,temp ',(car c))))
                   (or (cdr c) '(nil))))
           clauses)))))

(defmacro cl-ecase (expr &rest clauses)
  "Like `cl-case', but error if no case fits.
`otherwise'-clauses are not allowed.
\n(fn EXPR (KEYLIST BODY...)...)"
  (declare (indent 1) (debug cl-case))
  `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))

(defmacro cl-typecase (expr &rest clauses)
  "Eval EXPR and choose among clauses on that value.
Each clause looks like (TYPE BODY...).  EXPR is evaluated and, if it
satisfies TYPE, the corresponding BODY is evaluated.  If no clause succeeds,
this macro returns nil.  A TYPE of t or `otherwise' is allowed only in the
final clause, and matches if no other keys match.
\n(fn EXPR (TYPE BODY...)...)"
  (declare (indent 1)
           (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
  (macroexp-let2 macroexp-copyable-p temp expr
    (let* ((type-list nil))
      (cons
       'cond
       (mapcar
        (lambda (c)
          (cons (cond ((eq (car c) 'otherwise) t)
                      ((eq (car c) 'cl--ecase-error-flag)
                       `(error "cl-etypecase failed: %s, %s"
                               ,temp ',(reverse type-list)))
                      (t
                       (push (car c) type-list)
                       `(cl-typep ,temp ',(car c))))
                (or (cdr c) '(nil))))
        clauses)))))

(defmacro cl-etypecase (expr &rest clauses)
  "Like `cl-typecase', but error if no case fits.
`otherwise'-clauses are not allowed.
\n(fn EXPR (TYPE BODY...)...)"
  (declare (indent 1) (debug cl-typecase))
  `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))

(defun cl-list-length (x)
  "Return the length of list X.  Return nil if list is circular."
  (declare (side-effect-free t))
  (cl-check-type x list)
  (condition-case nil
      (length x)
    (circular-list)))

(cl-defun cl-parse-integer (string &key start end radix junk-allowed)
  "Parse integer from the substring of STRING from START to END.
STRING may be surrounded by whitespace chars (chars with syntax ` ').
Other non-digit chars are considered junk.
RADIX is an integer between 2 and 36, the default is 10.  Signal
an error if the substring between START and END cannot be parsed
as an integer unless JUNK-ALLOWED is non-nil."
  (declare (side-effect-free t))
  (cl-check-type string string)
  (let* ((start (or start 0))
	 (len	(length string))
	 (end   (or end len))
	 (radix (or radix 10)))
    (or (<= start end len)
	(error "Bad interval: [%d, %d)" start end))
    (cl-flet ((skip-whitespace ()
		(while (and (< start end)
			    (= 32 (char-syntax (aref string start))))
		  (setq start (1+ start)))))
      (skip-whitespace)
      (let ((sign (cl-case (and (< start end) (aref string start))
                    (?+ (incf start) +1)
                    (?- (incf start) -1)
		    (t  +1)))
	    digit sum)
	(while (and (< start end)
		    (setq digit (cl-digit-char-p (aref string start) radix)))
	  (setq sum (+ (* (or sum 0) radix) digit)
		start (1+ start)))
	(skip-whitespace)
	(cond ((and junk-allowed (null sum)) sum)
	      (junk-allowed (* sign sum))
	      ((or (/= start end) (null sum))
	       (error "Not an integer string: `%s'" string))
	      (t (* sign sum)))))))


;; ---- cl-seq ----
;; cl-seq.el (emacs-31.1), verbatim, with the two compiler macros its
;; `declare' forms name (cl-macs.el).

;; Keyword parsing.
;; This is special-cased here so that we can compile
;; this file independent from cl-macs.

(defmacro cl--parsing-keywords (keywords other-keys &rest body)
  (declare (indent 2) (debug (sexp sexp &rest form)))
  `(let* ,(mapcar
           (lambda (x)
             (let* ((var (if (consp x) (car x) x))
                    (mem `(car (cdr (memq ',var cl-keys)))))
               (if (eq var :test-not)
                   (setq mem `(and ,mem (setq cl-test ,mem) t)))
               (if (eq var :if-not)
                   (setq mem `(and ,mem (setq cl-if ,mem) t)))
               (list (intern
                      (format "cl-%s" (substring (symbol-name var) 1)))
                     (if (consp x) `(or ,mem ,(cadr x)) mem))))
           keywords)
     ,@(append
        (and (not (eq other-keys t))
             `((let ((cl-keys-temp cl-keys))
                 (while cl-keys-temp
                   (or (memq (car cl-keys-temp)
                             (quote ,(mapcar
                                      (lambda (x)
                                        (if (consp x)
                                            (car x) x))
                                      (append keywords other-keys))))
                       (cadr (memq :allow-other-keys cl-keys))
                       (error "Bad keyword argument %s"
                              (car cl-keys-temp)))
                   (setq cl-keys-temp (cddr cl-keys-temp))))))
        body)))

(defmacro cl--check-key (x)     ;Expects `cl-key' in context of generated code.
  (declare (debug edebug-forms))
  `(if cl-key (funcall cl-key ,x) ,x))

(defmacro cl--check-test-nokey (item x) ;cl-test cl-if cl-test-not cl-if-not.
  (declare (debug edebug-forms))
  `(cond
    (cl-test (eq (not (funcall cl-test ,item ,x))
                 cl-test-not))
    (cl-if (eq (not (funcall cl-if ,x)) cl-if-not))
    (t (eql ,item ,x))))

(defmacro cl--check-test (item x)       ;all of the above.
  (declare (debug edebug-forms))
  `(cl--check-test-nokey ,item (cl--check-key ,x)))

(defmacro cl--check-match (x y)         ;cl-key cl-test cl-test-not
  (declare (debug edebug-forms))
  (setq x `(cl--check-key ,x) y `(cl--check-key ,y))
  `(if cl-test
       (eq (not (funcall cl-test ,x ,y)) cl-test-not)
     (eql ,x ,y)))

;; Yuck!  These vars are set/bound by cl--parsing-keywords to match :if :test
;; and :key keyword args, and they are also accessed (sometimes) via dynamic
;; scoping (and some of those accesses are from macro-expanded code).
(defvar cl-test) (defvar cl-test-not)
(defvar cl-if) (defvar cl-if-not)
(defvar cl-key)

;;;###autoload
(defun cl-endp (x)
  "Return true if X is the empty list; false if it is a cons.
Signal an error if X is not a list."
  (declare (side-effect-free t))
  (cl-check-type x list)
  (null x))

;;;###autoload
(defun cl-reduce (func seq &rest cl-keys)
  "Reduce two-argument FUNCTION across SEQ.
\nKeywords supported:  :start :end :from-end :initial-value :key

Return the result of calling FUNCTION with the first and the
second element of SEQ, then calling FUNCTION with that result and
the third element of SEQ, then with that result and the fourth
element of SEQ, etc.

If :INITIAL-VALUE is specified, it is logically added to the
front of SEQ (or the back if :FROM-END is non-nil).  If SEQ is
empty, return :INITIAL-VALUE and FUNCTION is not called.

If SEQ is empty and no :INITIAL-VALUE is specified, then return
the result of calling FUNCTION with zero arguments.  This is the
only case where FUNCTION is called with fewer than two arguments.

If SEQ contains exactly one element and no :INITIAL-VALUE is
specified, then just return that element without calling FUNCTION.

If :FROM-END is non-nil, the reduction occurs from the back of
the SEQ moving forward, and the order of arguments to the
FUNCTION is also reversed.

\n(fn FUNCTION SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords (:from-end (:start 0) :end :initial-value :key) ()
    (or (listp seq) (setq seq (append seq nil)))
    (setq seq (cl-subseq seq cl-start cl-end))
    (if cl-from-end (setq seq (nreverse seq)))
    (let ((accum (cond ((memq :initial-value cl-keys) cl-initial-value)
                       (seq (cl--check-key (pop seq)))
                       (t (funcall func)))))
      (if cl-from-end
          (while seq
            (setq accum (funcall func (cl--check-key (pop seq))
                                 accum)))
        (while seq
          (setq accum (funcall func accum
                               (cl--check-key (pop seq))))))
      accum)))

;;;###autoload
(defun cl-fill (seq item &rest cl-keys)
  "Fill the elements of SEQ with ITEM.
\nKeywords supported:  :start :end
\n(fn SEQ ITEM [KEYWORD VALUE]...)"
  (cl--parsing-keywords ((:start 0) :end) ()
    (if (listp seq)
        (let ((p (nthcdr cl-start seq))
	      (n (and cl-end (- cl-end cl-start))))
          (while (and p (or (null n) (>= (decf n) 0)))
            (setcar p item)
	    (setq p (cdr p))))
      (or cl-end (setq cl-end (length seq)))
      (if (and (= cl-start 0) (= cl-end (length seq)))
          (fillarray seq item)
	(while (< cl-start cl-end)
          (aset seq cl-start item)
	  (setq cl-start (1+ cl-start)))))
    seq))

;;;###autoload
(defun cl-replace (seq1 seq2 &rest cl-keys)
  "Replace the elements of SEQ1 with the elements of SEQ2.
SEQ1 is destructively modified, then returned.
\nKeywords supported:  :start1 :end1 :start2 :end2
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
  (cl--parsing-keywords ((:start1 0) :end1 (:start2 0) :end2) ()
    (if (and (eq seq1 seq2) (<= cl-start2 cl-start1))
	(or (= cl-start1 cl-start2)
            (let* ((len (length seq1))
                   (n (min (- (or cl-end1 len) cl-start1)
                           (- (or cl-end2 len) cl-start2))))
              (while (>= (setq n (1- n)) 0)
                (setf (elt seq1 (+ cl-start1 n))
                      (elt seq2 (+ cl-start2 n))))))
      (if (listp seq1)
          (let ((p1 (nthcdr cl-start1 seq1))
                (n1 (and cl-end1 (- cl-end1 cl-start1))))
            (if (listp seq2)
                (let ((p2 (nthcdr cl-start2 seq2))
                      (n (cond ((and n1 cl-end2)
                                (min n1 (- cl-end2 cl-start2)))
                               ((and n1 (null cl-end2)) n1)
                               ((and (null n1) cl-end2) (- cl-end2 cl-start2)))))
                  (while (and p1 p2 (or (null n) (>= (decf n) 0)))
                    (setcar p1 (car p2))
                    (setq p1 (cdr p1) p2 (cdr p2))))
              (setq cl-end2 (if (null n1)
                                (or cl-end2 (length seq2))
                              (min (or cl-end2 (length seq2))
                                   (+ cl-start2 n1))))
              (while (and p1 (< cl-start2 cl-end2))
                (setcar p1 (aref seq2 cl-start2))
                (setq p1 (cdr p1) cl-start2 (1+ cl-start2)))))
        (setq cl-end1 (min (or cl-end1 (length seq1))
                           (+ cl-start1 (- (or cl-end2 (length seq2))
					   cl-start2))))
        (if (listp seq2)
            (let ((p2 (nthcdr cl-start2 seq2)))
	      (while (< cl-start1 cl-end1)
                (aset seq1 cl-start1 (car p2))
                (setq p2 (cdr p2) cl-start1 (1+ cl-start1))))
	  (while (< cl-start1 cl-end1)
            (aset seq1 cl-start1 (aref seq2 cl-start2))
	    (setq cl-start2 (1+ cl-start2) cl-start1 (1+ cl-start1))))))
    seq1))

;;;###autoload
(defun cl-remove (item seq &rest cl-keys)
  "Remove all occurrences of ITEM in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :test :test-not :key :count :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :if :if-not :count :from-end
                          (:start 0) :end) ()
    (let ((len (length seq)))
      (if (<= (or cl-count (setq cl-count len)) 0)
          seq
        (if (or (nlistp seq) (and cl-from-end (< cl-count (/ len 2))))
            (let ((i (cl--position item seq cl-start cl-end
                                   cl-from-end)))
              (if i
                  (let ((res (apply #'cl-delete item (append seq nil)
                                    (append (if cl-from-end
                                                (list :end (1+ i))
                                              (list :start i))
                                            cl-keys))))
                    (if (listp seq) res
                      (if (stringp seq) (concat res) (vconcat res))))
                seq))
	  (setq cl-end (- (or cl-end len) cl-start))
          (if (= cl-start 0)
              (while (and seq (> cl-end 0)
                          (cl--check-test item (car seq))
                          (setq cl-end (1- cl-end) seq (cdr seq))
                          (> (setq cl-count (1- cl-count)) 0))))
          (if (and (> cl-count 0) (> cl-end 0))
              (let ((p (if (> cl-start 0) (nthcdr cl-start seq)
                         (setq cl-end (1- cl-end)) (cdr seq))))
                (while (and p (> cl-end 0)
                            (not (cl--check-test item (car p))))
                  (setq p (cdr p) cl-end (1- cl-end)))
                (if (and p (> cl-end 0))
                    (nconc (cl-ldiff seq p)
                           (if (= cl-count 1) (cdr p)
                             (and (cdr p)
                                  (apply #'cl-delete item
                                         (copy-sequence (cdr p))
                                         :start 0 :end (1- cl-end)
                                         :count (1- cl-count) cl-keys))))
                  seq))
            seq))))))

;;;###autoload
(defun cl-remove-if (pred list &rest cl-keys)
  "Remove all items satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-remove pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-remove-if-not (pred list &rest cl-keys)
  "Remove all items not satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-remove pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-delete (item seq &rest cl-keys)
  "Remove all occurrences of ITEM in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :test :test-not :key :count :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :if :if-not :count :from-end
                          (:start 0) :end) ()
    (let ((len (length seq)))
      (if (<= (or cl-count (setq cl-count len)) 0)
          seq
        (if (listp seq)
            (if (and cl-from-end (< cl-count (/ len 2)))
                (let (i)
                  (while (and (>= (setq cl-count (1- cl-count)) 0)
                              (setq i (cl--position item seq cl-start
                                                    cl-end cl-from-end)))
                    (if (= i 0) (setq seq (cdr seq))
                      (let ((tail (nthcdr (1- i) seq)))
                        (setcdr tail (cdr (cdr tail)))))
                    (setq cl-end i))
                  seq)
              (setq cl-end (- (or cl-end len) cl-start))
              (if (= cl-start 0)
                  (progn
                    (while (and seq
                                (> cl-end 0)
                                (cl--check-test item (car seq))
                                (setq cl-end (1- cl-end) seq (cdr seq))
                                (> (setq cl-count (1- cl-count)) 0)))
                    (setq cl-end (1- cl-end)))
                (setq cl-start (1- cl-start)))
              (if (and (> cl-count 0) (> cl-end 0))
                  (let ((p (nthcdr cl-start seq)))
                    (while (and (cdr p) (> cl-end 0))
                      (if (cl--check-test item (car (cdr p)))
                          (progn
                            (setcdr p (cdr (cdr p)))
                            (if (= (setq cl-count (1- cl-count)) 0)
                                (setq cl-end 1)))
                        (setq p (cdr p)))
                      (setq cl-end (1- cl-end)))))
              seq)
          (apply #'cl-remove item seq cl-keys))))))

;;;###autoload
(defun cl-delete-if (pred list &rest cl-keys)
  "Remove all items satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-delete pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-delete-if-not (pred list &rest cl-keys)
  "Remove all items not satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-delete pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-remove-duplicates (seq &rest cl-keys)
  "Return a copy of SEQ with all duplicate elements removed.
\nKeywords supported:  :test :test-not :key :start :end :from-end
\n(fn SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--delete-duplicates seq cl-keys t))

;;;###autoload
(defun cl-delete-duplicates (seq &rest cl-keys)
  "Remove all duplicate elements from SEQ (destructively).
\nKeywords supported:  :test :test-not :key :start :end :from-end
\n(fn SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--delete-duplicates seq cl-keys nil))

(defun cl--delete-duplicates (seq cl-keys copy)
  (if (listp seq)
      (cl--parsing-keywords
          ;; We need to parse :if, otherwise `cl-if' is unbound.
          (:test :test-not :key (:start 0) :end :from-end :if)
	  ()
	(if cl-from-end
            (let ((p (nthcdr cl-start seq)) i)
              (setq cl-end (- (or cl-end (length seq)) cl-start))
	      (while (> cl-end 1)
                (setq i 0)
                (while (setq i (cl--position (cl--check-key (car p))
                                             (cdr p) i (1- cl-end)))
                  (if copy (setq seq (copy-sequence seq)
                                 p (nthcdr cl-start seq) copy nil))
                  (let ((tail (nthcdr i p)))
                    (setcdr tail (cdr (cdr tail))))
		  (setq cl-end (1- cl-end)))
                (setq p (cdr p) cl-end (1- cl-end)
		      cl-start (1+ cl-start)))
              seq)
          (setq cl-end (- (or cl-end (length seq)) cl-start))
          (while (and (cdr seq) (= cl-start 0) (> cl-end 1)
                      (cl--position (cl--check-key (car seq))
                                    (cdr seq) 0 (1- cl-end)))
            (setq seq (cdr seq) cl-end (1- cl-end)))
          (let ((p (if (> cl-start 0) (nthcdr (1- cl-start) seq)
                     (setq cl-end (1- cl-end) cl-start 1) seq)))
            (while (and (cdr (cdr p)) (> cl-end 1))
              (if (cl--position (cl--check-key (car (cdr p)))
                                (cdr (cdr p)) 0 (1- cl-end))
		  (progn
                    (if copy (setq seq (copy-sequence seq)
                                   p (nthcdr (1- cl-start) seq)
                                   copy nil))
                    (setcdr p (cdr (cdr p))))
                (setq p (cdr p)))
	      (setq cl-end (1- cl-end) cl-start (1+ cl-start)))
            seq)))
    (let ((res (cl--delete-duplicates (append seq nil) cl-keys nil)))
      (if (stringp seq) (concat res) (vconcat res)))))

;;;###autoload
(defun cl-substitute (new old seq &rest cl-keys)
  "Substitute NEW for OLD in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :test :test-not :key :count :start :end :from-end
\n(fn NEW OLD SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :if :if-not :count
                          (:start 0) :end :from-end) ()
    (if (or (eq old new)
	    (<= (or cl-count (setq cl-from-end nil
                                   cl-count (length seq))) 0))
        seq
      (let ((i (cl--position old seq cl-start cl-end)))
        (if (not i)
            seq
          (setq seq (copy-sequence seq))
	  (unless cl-from-end
            (setf (elt seq i) new)
            (incf i)
	    (decf cl-count))
          (apply #'cl-nsubstitute new old seq :count cl-count
                 :start i cl-keys))))))

;;;###autoload
(defun cl-substitute-if (new pred seq &rest cl-keys)
  "Substitute NEW for all items satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-substitute new pred seq :test #'funcall cl-keys))

;;;###autoload
(defun cl-substitute-if-not (new pred seq &rest cl-keys)
  "Substitute NEW for all items not satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-substitute new pred seq :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-nsubstitute (new old seq &rest cl-keys)
  "Substitute NEW for OLD in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :test :test-not :key :count :start :end :from-end
\n(fn NEW OLD SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :if :if-not :count
                          (:start 0) :end :from-end) ()
    (let* ((stringp (stringp seq))
           (seq (if (stringp seq) (string-to-vector seq) seq))
           (len (length seq)))
      (or (eq old new) (<= (or cl-count (setq cl-count len)) 0)
          (if (and (listp seq) (or (not cl-from-end) (> cl-count (/ len 2))))
              (let ((p (nthcdr cl-start seq)))
                (setq cl-end (- (or cl-end len) cl-start))
                (while (and p (> cl-end 0) (> cl-count 0))
                  (if (cl--check-test old (car p))
                      (progn
                        (setcar p new)
                        (setq cl-count (1- cl-count))))
                  (setq p (cdr p) cl-end (1- cl-end))))
	    (or cl-end (setq cl-end len))
            (if cl-from-end
                (while (and (< cl-start cl-end) (> cl-count 0))
                  (setq cl-end (1- cl-end))
                  (if (cl--check-test old (elt seq cl-end))
                      (progn
                        (setf (elt seq cl-end) new)
                        (setq cl-count (1- cl-count)))))
              (while (and (< cl-start cl-end) (> cl-count 0))
                (if (cl--check-test old (aref seq cl-start))
                    (progn
                      (aset seq cl-start new)
                      (setq cl-count (1- cl-count))))
                (setq cl-start (1+ cl-start))))))
      (if stringp (concat seq) seq))))

;;;###autoload
(defun cl-nsubstitute-if (new pred list &rest cl-keys)
  "Substitute NEW for all items satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-nsubstitute new pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-nsubstitute-if-not (new pred list &rest cl-keys)
  "Substitute NEW for all items not satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported:  :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-nsubstitute new pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-find (item seq &rest cl-keys)
  "Find the first occurrence of ITEM in SEQ.
Return the matching ITEM, or nil if not found.
\nKeywords supported:  :test :test-not :key :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (let ((pos (apply #'cl-position item seq cl-keys)))
    (and pos (elt seq pos))))

;;;###autoload
(defun cl-find-if (pred list &rest cl-keys)
  "Find the first item satisfying PREDICATE in SEQ.
Return the matching item, or nil if not found.
\nKeywords supported:  :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-find pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-find-if-not (pred list &rest cl-keys)
  "Find the first item not satisfying PREDICATE in SEQ.
Return the matching item, or nil if not found.
\nKeywords supported:  :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-find pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-position (item seq &rest cl-keys)
  "Find the first occurrence of ITEM in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported:  :test :test-not :key :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :if :if-not
                          (:start 0) :end :from-end) ()
    (cl--position item seq cl-start cl-end cl-from-end)))

(defun cl--position (item seq start &optional end from-end)
  (if (listp seq)
      (let ((p (nthcdr start seq))
            res)
        (while (and p (or (null end) (< start end)) (or (null res) from-end))
          (if (cl--check-test item (car p))
              (setq res start))
          (setq p (cdr p) start (1+ start)))
        res)
    (or end (setq end (length seq)))
    (if from-end
	(progn
          (while (and (>= (setq end (1- end)) start)
                      (not (cl--check-test item (aref seq end)))))
          (and (>= end start) end))
      (while (and (< start end)
                  (not (cl--check-test item (aref seq start))))
        (setq start (1+ start)))
      (and (< start end) start))))

;;;###autoload
(defun cl-position-if (pred list &rest cl-keys)
  "Find the first item satisfying PREDICATE in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported:  :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-position pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-position-if-not (pred list &rest cl-keys)
  "Find the first item not satisfying PREDICATE in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported:  :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-position pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-count (item seq &rest cl-keys)
  "Count the number of occurrences of ITEM in SEQ.
\nKeywords supported:  :test :test-not :key :start :end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords (:test :test-not :key :if :if-not (:start 0) :end) ()
    (let ((count 0) x)
      (or cl-end (setq cl-end (length seq)))
      (if (consp seq) (setq seq (nthcdr cl-start seq)))
      (while (< cl-start cl-end)
        (setq x (if (consp seq) (pop seq) (aref seq cl-start)))
        (if (cl--check-test item x) (incf count))
	(setq cl-start (1+ cl-start)))
      count)))

;;;###autoload
(defun cl-count-if (pred list &rest cl-keys)
  "Count the number of items satisfying PREDICATE in SEQ.
\nKeywords supported:  :key :start :end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-count pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-count-if-not (pred list &rest cl-keys)
  "Count the number of items not satisfying PREDICATE in SEQ.
\nKeywords supported:  :key :start :end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-count pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-mismatch (seq1 seq2 &rest cl-keys)
  "Compare SEQ1 with SEQ2, return index of first mismatching element.
Return nil if the sequences match.  If one sequence is a prefix of the
other, the return value indicates the end of the shorter sequence.
\nKeywords supported:  :test :test-not :key :start1 :end1 :start2 :end2 :from-end
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :from-end
                          (:start1 0) :end1 (:start2 0) :end2) ()
    (or cl-end1 (setq cl-end1 (length seq1)))
    (or cl-end2 (setq cl-end2 (length seq2)))
    (if cl-from-end
	(progn
	  (while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
                      (cl--check-match (elt seq1 (1- cl-end1))
                                       (elt seq2 (1- cl-end2))))
	    (setq cl-end1 (1- cl-end1) cl-end2 (1- cl-end2)))
	  (and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
	       (1- cl-end1)))
      (let ((p1 (and (listp seq1) (nthcdr cl-start1 seq1)))
            (p2 (and (listp seq2) (nthcdr cl-start2 seq2))))
	(while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
                    (cl--check-match (if p1 (car p1)
                                       (aref seq1 cl-start1))
                                     (if p2 (car p2)
                                       (aref seq2 cl-start2))))
          (setq p1 (cdr p1) p2 (cdr p2)
		cl-start1 (1+ cl-start1) cl-start2 (1+ cl-start2)))
	(and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
	     cl-start1)))))

;;;###autoload
(defun cl-search (seq1 seq2 &rest cl-keys)
  "Search for SEQ1 as a subsequence of SEQ2.
Return the index of the leftmost element of the first match found;
return nil if there are no matches.
\nKeywords supported:  :test :test-not :key :start1 :end1 :start2 :end2 :from-end
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords ( :test :test-not :key :from-end
                          (:start1 0) :end1 (:start2 0) :end2) ()
    (or cl-end1 (setq cl-end1 (length seq1)))
    (or cl-end2 (setq cl-end2 (length seq2)))
    (if (>= cl-start1 cl-end1)
	(if cl-from-end cl-end2 cl-start2)
      (let* ((len (- cl-end1 cl-start1))
             (first (cl--check-key (elt seq1 cl-start1)))
             (cl-if nil) pos)
        (setq cl-end2 (- cl-end2 (1- len)))
	(while (and (< cl-start2 cl-end2)
                    (setq pos (cl--position first seq2
                                            cl-start2 cl-end2 cl-from-end))
                    (apply #'cl-mismatch seq1 seq2
			   :start1 (1+ cl-start1) :end1 cl-end1
                           :start2 (1+ pos) :end2 (+ pos len)
			   :from-end nil cl-keys))
          (if cl-from-end (setq cl-end2 pos) (setq cl-start2 (1+ pos))))
        (and (< cl-start2 cl-end2) pos)))))

;;;###autoload
(defun cl-sort (seq pred &rest cl-keys)
  "Sort the argument SEQ according to PREDICATE.
This is a destructive function; it reuses the storage of SEQ if possible.
\nKeywords supported:  :key
\n(fn SEQ PREDICATE [KEYWORD VALUE]...)"
  ;; It's safe to ignore the return value when used on arrays,
  ;; but most calls pass lists.
  (declare (important-return-value t))
  (if (nlistp seq)
      (if (stringp seq)
          (concat (apply #'cl-sort (vconcat seq) pred cl-keys))
        (cl-replace seq
                    (apply #'cl-sort (append seq nil) pred cl-keys)))
    (cl--parsing-keywords (:key) ()
      (if (memq cl-key '(nil identity))
          (sort seq pred)
        (sort seq (lambda (x y)
                    (funcall pred (funcall cl-key x)
                             (funcall cl-key y))))))))

;;;###autoload
(defun cl-stable-sort (seq pred &rest cl-keys)
  "Sort the argument SEQ stably according to PREDICATE.
This is a destructive function; it reuses the storage of SEQ if possible.
\nKeywords supported:  :key
\n(fn SEQ PREDICATE [KEYWORD VALUE]...)"
  ;; It's safe to ignore the return value when used on arrays,
  ;; but most calls pass lists.
  (declare (important-return-value t))
  (apply #'cl-sort seq pred cl-keys))

;;;###autoload
(defun cl-merge (type seq1 seq2 pred &rest cl-keys)
  "Destructively merge the two sequences to produce a new sequence.
TYPE is the sequence type to return, SEQ1 and SEQ2 are the two argument
sequences, and PREDICATE is a `less-than' predicate on the elements.
\nKeywords supported:  :key
\n(fn TYPE SEQ1 SEQ2 PREDICATE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (or (listp seq1) (setq seq1 (append seq1 nil)))
  (or (listp seq2) (setq seq2 (append seq2 nil)))
  (cl--parsing-keywords (:key) ()
    (let ((res nil))
      (while (and seq1 seq2)
        (if (funcall pred (cl--check-key (car seq2))
                     (cl--check-key (car seq1)))
            (push (pop seq2) res)
          (push (pop seq1) res)))
      (cl-coerce (nconc (nreverse res) seq1 seq2) type))))

;;;###autoload
(defun cl-member (item list &rest cl-keys)
  "Find the first occurrence of ITEM in LIST.
Return the sublist of LIST whose car is ITEM.
\nKeywords supported:  :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t)
           (compiler-macro cl--compiler-macro-member))
  (if cl-keys
      (cl--parsing-keywords (:test :test-not :key :if :if-not) ()
        (while (and list (not (cl--check-test item (car list))))
          (setq list (cdr list)))
        list)
    (memql item list)))

;;;###autoload
(defun cl-member-if (pred list &rest cl-keys)
  "Find the first item satisfying PREDICATE in LIST.
Return the sublist of LIST whose car matches.

This function is obsolete: use `member-if'.  The new function does not
support the old `:key KEY-FN' argument, but it is better to compose any
KEY-FN into PRED.  For example, you can replace

    (cl-member-if #\\='foo items :key #\\='bar)

with

    (member-if (lambda (x) (foo (bar x))) items)

(fn PREDICATE LIST [:KEY KEY-FN])"
  (declare (important-return-value t))
  (apply #'cl-member pred list :test #'funcall cl-keys))
(make-obsolete 'cl-member-if 'member-if "31.1")

;;;###autoload
(defun cl-member-if-not (pred list &rest cl-keys)
  "Find the first item not satisfying PREDICATE in LIST.
Return the sublist of LIST whose car matches.
This function is deprecated in the Common Lisp standard.
Prefer `member-if' with a negated predicate, and composing any `:key'
function into the predicate.
\nKeywords supported:  :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-member pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl--adjoin (item list &rest cl-keys)
  (if (cl--parsing-keywords (:key) t
        (apply #'cl-member (cl--check-key item) list cl-keys))
      list
    (cons item list)))

;;;###autoload
(defun cl-assoc (item alist &rest cl-keys)
  "Find the first item whose car matches ITEM in LIST.
\nKeywords supported:  :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t)
           (compiler-macro cl--compiler-macro-assoc))
  (if cl-keys
      (cl--parsing-keywords (:test :test-not :key :if :if-not) ()
        (while (and alist
                    (or (not (consp (car alist)))
                        (not (cl--check-test item (car (car alist))))))
          (setq alist (cdr alist)))
        (and alist (car alist)))
    (if (and (numberp item) (not (fixnump item)))
        (assoc item alist)
      (assq item alist))))

;;;###autoload
(defun cl-assoc-if (pred list &rest cl-keys)
  "Find the first item whose car satisfies PREDICATE in LIST.
\nKeywords supported:  :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-assoc pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-assoc-if-not (pred list &rest cl-keys)
  "Find the first item whose car does not satisfy PREDICATE in LIST.
\nKeywords supported:  :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-assoc pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-rassoc (item alist &rest cl-keys)
  "Find the first item whose cdr matches ITEM in LIST.
\nKeywords supported:  :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (if (or cl-keys (numberp item))
      (cl--parsing-keywords (:test :test-not :key :if :if-not) ()
        (while (and alist
                    (or (not (consp (car alist)))
                        (not (cl--check-test item (cdr (car alist))))))
          (setq alist (cdr alist)))
        (and alist (car alist)))
    (rassq item alist)))

;;;###autoload
(defun cl-rassoc-if (pred list &rest cl-keys)
  "Find the first item whose cdr satisfies PREDICATE in LIST.
\nKeywords supported:  :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-rassoc pred list :test #'funcall cl-keys))

;;;###autoload
(defun cl-rassoc-if-not (pred list &rest cl-keys)
  "Find the first item whose cdr does not satisfy PREDICATE in LIST.
\nKeywords supported:  :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-rassoc pred list :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-union (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-union operation.
The resulting list contains all items that appear in either LIST1 or LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cond ((null list1) list2) ((null list2) list1)
        ((and (not cl-keys) (equal list1 list2)) list1)
	(t
         (or (>= (length list1) (length list2))
             (setq list1 (prog1 list2 (setq list2 list1))))
         (while list2
           (if (or cl-keys (numberp (car list2)))
               (setq list1
                     (apply #'cl-adjoin (car list2) list1 cl-keys))
             (or (memq (car list2) list1)
                 (push (car list2) list1)))
           (pop list2))
         list1)))

;;;###autoload
(defun cl-nunion (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-union operation.
The resulting list contains all items that appear in either LIST1 or LIST2.
This is a destructive function; it reuses the storage of LIST1 and LIST2
whenever possible.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cond ((null list1) list2) ((null list2) list1)
        (t (apply #'cl-union list1 list2 cl-keys))))

;;;###autoload
(defun cl-intersection (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-intersection operation.
The resulting list contains all items that appear in both LIST1 and LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (and list1 list2
       (if (equal list1 list2) list1
	 (cl--parsing-keywords (:key) (:test :test-not)
           (let ((res nil))
             (or (>= (length list1) (length list2))
                 (setq list1 (prog1 list2 (setq list2 list1))))
             (while list2
               (if (if (or cl-keys (numberp (car list2)))
                       (apply #'cl-member (cl--check-key (car list2))
                              list1 cl-keys)
                     (memq (car list2) list1))
                   (push (car list2) res))
               (pop list2))
             res)))))

;;;###autoload
(defun cl-nintersection (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-intersection operation.
The resulting list contains all items that appear in both LIST1 and LIST2.
This is a destructive function; it reuses the storage of LIST1 (but not
LIST2) whenever possible.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (and list1 list2 (apply #'cl-intersection list1 list2 cl-keys)))

;;;###autoload
(defun cl-set-difference (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-difference operation.
The resulting list contains all items that appear in LIST1 but not LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (if (or (null list1) (null list2)) list1
    (cl--parsing-keywords (:key) (:test :test-not)
      (let ((res nil))
        (while list1
          (or (if (or cl-keys (numberp (car list1)))
                  (apply #'cl-member (cl--check-key (car list1))
                         list2 cl-keys)
                (memq (car list1) list2))
              (push (car list1) res))
          (pop list1))
        (nreverse res)))))

;;;###autoload
(defun cl-nset-difference (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-difference operation.
The resulting list contains all items that appear in LIST1 but not LIST2.
This is a destructive function; it reuses the storage of LIST1 (but not
LIST2) whenever possible.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (if (or (null list1) (null list2)) list1
    (apply #'cl-set-difference list1 list2 cl-keys)))

;;;###autoload
(defun cl-set-exclusive-or (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-exclusive-or operation.
The resulting list contains all items appearing in exactly one of LIST1, LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cond ((null list1) list2) ((null list2) list1)
        ((equal list1 list2) nil)
        (t (append (apply #'cl-set-difference list1 list2 cl-keys)
                   (apply #'cl-set-difference list2 list1 cl-keys)))))

;;;###autoload
(defun cl-nset-exclusive-or (list1 list2 &rest cl-keys)
  "Combine LIST1 and LIST2 using a set-exclusive-or operation.
The resulting list contains all items appearing in exactly one of LIST1, LIST2.
This is a destructive function; it reuses the storage of LIST1 and LIST2
whenever possible.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cond ((null list1) list2) ((null list2) list1)
        ((equal list1 list2) nil)
        (t (nconc (apply #'cl-nset-difference list1 list2 cl-keys)
                  (apply #'cl-nset-difference list2 list1 cl-keys)))))

;;;###autoload
(defun cl-subsetp (list1 list2 &rest cl-keys)
  "Return true if LIST1 is a subset of LIST2.
I.e., if every element of LIST1 also appears in LIST2.
\nKeywords supported:  :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cond ((null list1) t) ((null list2) nil)
        ((equal list1 list2) t)
	(t (cl--parsing-keywords (:key) (:test :test-not)
             (while (and list1
                         (apply #'cl-member (cl--check-key (car list1))
                                list2 cl-keys))
               (pop list1))
             (null list1)))))

;;;###autoload
(defun cl-subst-if (new pred tree &rest cl-keys)
  "Substitute NEW for elements matching PREDICATE in TREE (non-destructively).
Return a copy of TREE with all matching elements replaced by NEW.
\nKeywords supported:  :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-sublis (list (cons pred new)) tree :test #'funcall cl-keys))

;;;###autoload
(defun cl-subst-if-not (new pred tree &rest cl-keys)
  "Substitute NEW for elts not matching PREDICATE in TREE (non-destructively).
Return a copy of TREE with all non-matching elements replaced by NEW.
\nKeywords supported:  :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-sublis (list (cons pred new)) tree :test-not #'funcall cl-keys))

;;;###autoload
(defun cl-nsubst (new old tree &rest cl-keys)
  "Substitute NEW for OLD everywhere in TREE (destructively).
Any element of TREE which is `eql' to OLD is changed to NEW (via a call
to `setcar').
\nKeywords supported:  :test :test-not :key
\n(fn NEW OLD TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-nsublis (list (cons old new)) tree cl-keys))

;;;###autoload
(defun cl-nsubst-if (new pred tree &rest cl-keys)
  "Substitute NEW for elements matching PREDICATE in TREE (destructively).
Any element of TREE which matches is changed to NEW (via a call to `setcar').
\nKeywords supported:  :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-nsublis (list (cons pred new)) tree :test #'funcall cl-keys))

;;;###autoload
(defun cl-nsubst-if-not (new pred tree &rest cl-keys)
  "Substitute NEW for elements not matching PREDICATE in TREE (destructively).
Any element of TREE which matches is changed to NEW (via a call to `setcar').
\nKeywords supported:  :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (apply #'cl-nsublis (list (cons pred new)) tree :test-not #'funcall cl-keys))

(defvar cl--alist)

;;;###autoload
(defun cl-sublis (alist tree &rest cl-keys)
  "Perform substitutions indicated by ALIST in TREE (non-destructively).
Return a copy of TREE with all matching elements replaced.
\nKeywords supported:  :test :test-not :key
\n(fn ALIST TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords (:test :test-not :key :if :if-not) ()
    (let ((cl--alist alist))
      (cl--sublis-rec tree))))

(defun cl--sublis-rec (tree)   ;Uses cl--alist cl-key/test*/if*.
  (let ((temp (cl--check-key tree))
        (p cl--alist))
    (while (and p (not (cl--check-test-nokey (car (car p)) temp)))
      (setq p (cdr p)))
    (if p (cdr (car p))
      (if (consp tree)
          (let ((a (cl--sublis-rec (car tree)))
                (d (cl--sublis-rec (cdr tree))))
            (if (and (eq a (car tree)) (eq d (cdr tree)))
                tree
              (cons a d)))
        tree))))

;;;###autoload
(defun cl-nsublis (alist tree &rest cl-keys)
  "Perform substitutions indicated by ALIST in TREE (destructively).
Any matching element of TREE is changed via a call to `setcar'.
\nKeywords supported:  :test :test-not :key
\n(fn ALIST TREE [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords (:test :test-not :key :if :if-not) ()
    (let ((hold (list tree))
          (cl--alist alist))
      (cl--nsublis-rec hold)
      (car hold))))

(defun cl--nsublis-rec (tree)   ;Uses cl--alist cl-key/test*/if*.
  (while (consp tree)
    (let ((temp (cl--check-key (car tree)))
          (p cl--alist))
      (while (and p (not (cl--check-test-nokey (car (car p)) temp)))
        (setq p (cdr p)))
      (if p (setcar tree (cdr (car p)))
        (if (consp (car tree)) (cl--nsublis-rec (car tree))))
      (setq temp (cl--check-key (cdr tree)) p cl--alist)
      (while (and p (not (cl--check-test-nokey (car (car p)) temp)))
        (setq p (cdr p)))
      (if p
          (progn (setcdr tree (cdr (car p))) (setq tree nil))
        (setq tree (cdr tree))))))

;;;###autoload
(defun cl-tree-equal (x y &rest cl-keys)
  "Return t if trees TREE1 and TREE2 have `eql' leaves.
Atoms are compared by `eql'; cons cells are compared recursively.
\nKeywords supported:  :test :test-not :key
\n(fn TREE1 TREE2 [KEYWORD VALUE]...)"
  (declare (important-return-value t))
  (cl--parsing-keywords (:test :test-not :key) ()
    (cl--tree-equal-rec x y)))

(defun cl--tree-equal-rec (x y)   ;Uses cl-key/test*.
  (while (and (consp x) (consp y)
              (cl--tree-equal-rec (car x) (car y)))
    (setq x (cdr x) y (cdr y)))
  (and (not (consp x)) (not (consp y)) (cl--check-match x y)))


(make-obsolete-variable 'cl-seq-load-hook
                        "use `with-eval-after-load' instead." "28.1")
(run-hooks 'cl-seq-load-hook)

;; Local variables:
;; generated-autoload-file: "cl-loaddefs.el"
;; End:

(defun cl--compiler-macro-member (form a list &rest keys)
  (let ((test (and (= (length keys) 2) (eq (car keys) :test)
		   (cl--const-expr-val (nth 1 keys)))))
    (cond ((eq test 'eq) `(memq ,a ,list))
	  ((eq test 'equal) `(member ,a ,list))
	  ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
	  (t form))))

(defun cl--compiler-macro-assoc (form a list &rest keys)
  (let ((test (and (= (length keys) 2) (eq (car keys) :test)
		   (cl--const-expr-val (nth 1 keys)))))
    (cond ((eq test 'eq) `(assq ,a ,list))
	  ((eq test 'equal) `(assoc ,a ,list))
	  ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
	   (if (floatp (cl--const-expr-val a))
	       `(assoc ,a ,list) `(assq ,a ,list)))
	  (t form))))

;; ---- cl-loop ----
;; cl-macs.el's loop machinery (emacs-31.1), verbatim: the clause parser, the
;; binding builder and the `and'-chain builder, so every clause the Emacs macro
;; accepts expands the way Emacs expands it. `cl--map-intervals' and
;; `cl--map-overlays' are cl-extra.el's, used by `being the intervals/overlays'.
(defun cl--expr-contains (x y)
  "Count number of times X refers to Y.  Return nil for 0 times."
  ;; FIXME: This is naive, and it will cl-count Y as referred twice in
  ;; (let ((Y 1)) Y) even though it should be 0.  Also it is often called on
  ;; non-macroexpanded code, so it may also miss some occurrences that would
  ;; only appear in the expanded code.
  (cond ((equal y x) 1)
	((and (consp x) (not (memq (car x) '(quote function cl-function))))
	 (let ((sum 0))
	   (while (consp x)
	     (setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
	   (setq sum (+ sum (or (cl--expr-contains x y) 0)))
	   (and (> sum 0) sum)))
	(t nil)))

(defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
(defvar cl--loop-bindings) (defvar cl--loop-body) (defvar cl--loop-conditions)
(defvar cl--loop-finally)
(defvar cl--loop-finish-flag)           ;Symbol set to nil to exit the loop?
(defvar cl--loop-first-flag)
(defvar cl--loop-initially) (defvar cl--loop-iterator-function)
(defvar cl--loop-name)
(defvar cl--loop-result) (defvar cl--loop-result-explicit)
(defvar cl--loop-result-var) (defvar cl--loop-steps)
(defvar cl--loop-symbol-macs)

(defun cl--loop-set-iterator-function (kind iterator)
  (if cl--loop-iterator-function
      ;; FIXME: Of course, we could make it work, but why bother.
      (error "Iteration on %S does not support this combination" kind)
    (setq cl--loop-iterator-function iterator)))

;;;###autoload
(defmacro cl-loop (&rest loop-args)
  "The Common Lisp `loop' macro.
Valid clauses include:
  For clauses:
    for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2
        [by EXPR3]
    for VAR = EXPR1 then EXPR2
    for VAR in/on/in-ref LIST [by FUNC]
    for VAR across/across-ref ARRAY
    for VAR being:
      the elements of/of-ref SEQUENCE [using (index VAR2)]
      the symbols [of OBARRAY]
      the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
      the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
      the overlays/intervals [of BUFFER] [from POS1] [to POS2]
      the frames/buffers
      the windows [of FRAME]
  Iteration clauses:
    repeat INTEGER
    while/until/always/never/thereis CONDITION
  Accumulation clauses:
    collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
      [into VAR]
  Miscellaneous clauses:
    with VAR = INIT
    if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
    named NAME
    initially/finally [do] EXPRS...
    do EXPRS...
    [finally] return EXPR

For more details, see Info node `(cl)Loop Facility'.

\(fn CLAUSE...)"
  (declare (debug (&rest &or
                         ;; These are usually followed by a symbol, but it can
                         ;; actually be any destructuring-bind pattern, which
                         ;; would erroneously match `form'.
                         [[&or "for" "as" "with" "and"] sexp]
                         ;; These are followed by expressions which could
                         ;; erroneously match `symbolp'.
                         [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
                               "above" "below" "by" "in" "on" "=" "across"
                               "repeat" "while" "until" "always" "never"
                               "thereis" "collect" "append" "nconc" "sum"
                               "count" "maximize" "minimize"
                               "if" "when" "unless"
                               "return"]
                          form]
                         ["using" (symbolp symbolp)]
                         ;; Simple default, which covers 99% of the cases.
                         symbolp form)))
  (if (not (memq t (mapcar #'symbolp
                           (delq nil (delq t (cl-copy-list loop-args))))))
      `(cl-block nil (while t ,@loop-args))
    (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
	  (cl--loop-body nil)		(cl--loop-steps nil)
	  (cl--loop-result nil)		(cl--loop-result-explicit nil)
	  (cl--loop-result-var nil)	(cl--loop-finish-flag nil)
	  (cl--loop-accum-var nil)	(cl--loop-accum-vars nil)
	  (cl--loop-initially nil)	(cl--loop-finally nil)
	  (cl--loop-iterator-function nil) (cl--loop-first-flag nil)
          (cl--loop-symbol-macs nil)
          (cl--loop-conditions nil))
      ;; Here is more or less how those dynbind vars are used after looping
      ;; over cl--parse-loop-clause:
      ;;
      ;; (cl-block ,cl--loop-name
      ;;   (cl-symbol-macrolet ,cl--loop-symbol-macs
      ;;     (foldl #'cl--loop-let
      ;;            `((,cl--loop-result-var)
      ;;              ((,cl--loop-first-flag t))
      ;;              ((,cl--loop-finish-flag t))
      ;;              ,@cl--loop-bindings)
      ;;           ,@(nreverse cl--loop-initially)
      ;;           (while                   ;(well: cl--loop-iterator-function)
      ;;               ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
      ;;             ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
      ;;             ,@(nreverse cl--loop-steps)
      ;;             (setq ,cl--loop-first-flag nil))
      ;;           (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
      ;;               ,cl--loop-result-var
      ;;             ,@(nreverse cl--loop-finally)
      ;;             ,(or cl--loop-result-explicit
      ;;                  cl--loop-result)))))
      ;;
      (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
      (while (not (eq (car cl--loop-args) 'cl-end-loop))
        (cl--parse-loop-clause))
      (if cl--loop-finish-flag
	  (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
      (if cl--loop-first-flag
	  (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
		 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
      (let* ((epilogue (nconc (nreverse cl--loop-finally)
			      (list (or cl--loop-result-explicit
                                        cl--loop-result))))
	     (ands (cl--loop-build-ands (nreverse cl--loop-body)))
	     (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
	     (body (append
		    (nreverse cl--loop-initially)
		    (list (if cl--loop-iterator-function
			      `(cl-block --cl-finish--
                                 ,(funcall cl--loop-iterator-function
                                           (if (eq (car ands) t) while-body
                                             (cons `(or ,(car ands)
                                                        (cl-return-from
                                                            --cl-finish--
                                                          nil))
                                                   while-body))))
			    `(while ,(car ands) ,@while-body)))
		    (if cl--loop-finish-flag
			(if (equal epilogue '(nil)) (list cl--loop-result-var)
			  `((if ,cl--loop-finish-flag
				(progn ,@epilogue) ,cl--loop-result-var)))
		      epilogue))))
	(if cl--loop-result-var
            (push (list cl--loop-result-var) cl--loop-bindings))
	(while cl--loop-bindings
	  (if (cdar cl--loop-bindings)
	      (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
	    (let ((lets nil))
	      (while (and cl--loop-bindings
			  (not (cdar cl--loop-bindings)))
		(push (car (pop cl--loop-bindings)) lets))
	      (setq body (list (cl--loop-let lets body nil))))))
	(if cl--loop-symbol-macs
	    (setq body
                  (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
	`(cl-block ,cl--loop-name ,@body)))))

(defmacro cl--push-clause-loop-body (clause)
  "Apply CLAUSE to both `cl--loop-conditions' and `cl--loop-body'."
  (macroexp-let2 nil sym clause
    `(progn
       (push ,sym cl--loop-conditions)
       (push ,sym cl--loop-body))))

;; Below is a complete spec for cl-loop, in several parts that correspond
;; to the syntax given in CLtL2.  The specs do more than specify where
;; the forms are; it also specifies, as much as Edebug allows, all the
;; syntactically valid cl-loop clauses.  The disadvantage of this
;; completeness is rigidity, but the "for ... being" clause allows
;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].

;; (def-edebug-spec cl-loop
;;   ([&optional ["named" symbolp]]
;;    [&rest
;;     &or
;;     ["repeat" form]
;;     loop-for-as
;;     loop-with
;;     loop-initial-final]
;;    [&rest loop-clause]
;;    ))

;; (def-edebug-elem-spec 'loop-with
;;  '("with" loop-var
;;    loop-type-spec
;;    [&optional ["=" form]]
;;    &rest ["and" loop-var
;; 	  loop-type-spec
;; 	  [&optional ["=" form]]]))

;; (def-edebug-elem-spec 'loop-for-as
;;  '([&or "for" "as"] loop-for-as-subclause
;;    &rest ["and" loop-for-as-subclause]))

;; (def-edebug-elem-spec 'loop-for-as-subclause
;;  '(loop-var
;;    loop-type-spec
;;    &or
;;    [[&or "in" "on" "in-ref" "across-ref"]
;;     form &optional ["by" function-form]]

;;    ["=" form &optional ["then" form]]
;;    ["across" form]
;;    ["being"
;;     [&or "the" "each"]
;;     &or
;;     [[&or "element" "elements"]
;;      [&or "of" "in" "of-ref"] form
;;      &optional "using" ["index" symbolp]];; is this right?
;;     [[&or "hash-key" "hash-keys"
;; 	  "hash-value" "hash-values"]
;;      [&or "of" "in"]
;;      hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
;; 					   "hash-key" "hash-keys"] sexp)]]

;;     [[&or "symbol" "present-symbol" "external-symbol"
;; 	  "symbols" "present-symbols" "external-symbols"]
;;      [&or "in" "of"] package-p]

;;     ;; Extensions for Emacs Lisp, including Lucid Emacs.
;;     [[&or "frame" "frames"
;; 	  "screen" "screens"
;; 	  "buffer" "buffers"]]

;;     [[&or "window" "windows"]
;;      [&or "of" "in"] form]

;;     [[&or "overlay" "overlays"
;; 	  "extent" "extents"]
;;      [&or "of" "in"] form
;;      &optional [[&or "from" "to"] form]]

;;     [[&or "interval" "intervals"]
;;      [&or "in" "of"] form
;;      &optional [[&or "from" "to"] form]
;;      ["property" form]]

;;     [[&or "key-code" "key-codes"
;; 	  "key-seq" "key-seqs"
;; 	  "key-binding" "key-bindings"]
;;      [&or "in" "of"] form
;;      &optional ["using" ([&or "key-code" "key-codes"
;; 			      "key-seq" "key-seqs"
;; 			      "key-binding" "key-bindings"]
;; 			 sexp)]]
;;     ;; For arbitrary extensions, recognize anything else.
;;     [symbolp &rest &or symbolp form]
;;     ]

;;    ;; arithmetic - must be last since all parts are optional.
;;    [[&optional [[&or "from" "downfrom" "upfrom"] form]]
;;     [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
;;     [&optional ["by" form]]
;;     ]))

;; (def-edebug-elem-spec 'loop-initial-final
;;  '(&or ["initially"
;; 	;; [&optional &or "do" "doing"]  ;; CLtL2 doesn't allow this.
;; 	&rest loop-non-atomic-expr]
;;        ["finally" &or
;; 	[[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
;; 	["return" form]]))

;; (def-edebug-elem-spec 'loop-and-clause
;;   '(loop-clause &rest ["and" loop-clause]))

;; (def-edebug-elem-spec 'loop-clause
;;  '(&or
;;    [[&or "while" "until" "always" "never" "thereis"] form]

;;    [[&or "collect" "collecting"
;; 	 "append" "appending"
;; 	 "nconc" "nconcing"
;; 	 "concat" "vconcat"] form
;; 	 [&optional ["into" loop-var]]]

;;    [[&or "count" "counting"
;; 	 "sum" "summing"
;; 	 "maximize" "maximizing"
;; 	 "minimize" "minimizing"] form
;; 	 [&optional ["into" loop-var]]
;; 	 loop-type-spec]

;;    [[&or "if" "when" "unless"]
;;     form loop-and-clause
;;     [&optional ["else" loop-and-clause]]
;;     [&optional "end"]]

;;    [[&or "do" "doing"] &rest loop-non-atomic-expr]

;;    ["return" form]
;;    loop-initial-final
;;    ))

;; (def-edebug-elem-spec 'loop-non-atomic-expr
;;   '([&not atom] form))

;; (def-edebug-elem-spec 'loop-var
;;   ;; The symbolp must be last alternative to recognize e.g. (a b . c)
;;   ;; loop-var =>
;;   ;; (loop-var . [&or nil loop-var])
;;   ;; (symbolp . [&or nil loop-var])
;;   ;; (symbolp . loop-var)
;;   ;; (symbolp . (symbolp . [&or nil loop-var]))
;;   ;; (symbolp . (symbolp . loop-var))
;;   ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
;;   '(&or (loop-var . [&or nil loop-var]) [gate symbolp]))

;; (def-edebug-elem-spec 'loop-type-spec
;;   '(&optional ["of-type" loop-d-type-spec]))

;; (def-edebug-elem-spec 'loop-d-type-spec
;;   '(&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))

(defun cl--parse-loop-clause ()		; uses loop-*
  (let ((word (pop cl--loop-args))
	(hash-types '(hash-key hash-keys hash-value hash-values))
	(key-types '(key-code key-codes key-seq key-seqs
		     key-binding key-bindings)))
    (cond

     ((null cl--loop-args)
      (error "Malformed `cl-loop' macro"))

     ((eq word 'named)
      (setq cl--loop-name (pop cl--loop-args)))

     ((eq word 'initially)
      (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
      (or (consp (car cl--loop-args))
          (error "Syntax error on `initially' clause"))
      (while (consp (car cl--loop-args))
	(push (pop cl--loop-args) cl--loop-initially)))

     ((eq word 'finally)
      (if (eq (car cl--loop-args) 'return)
	  (setq cl--loop-result-explicit
                (or (cl--pop2 cl--loop-args) '(quote nil)))
	(if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
	(or (consp (car cl--loop-args))
            (error "Syntax error on `finally' clause"))
	(if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
	    (setq cl--loop-result-explicit
                  (or (nth 1 (pop cl--loop-args)) '(quote nil)))
	  (while (consp (car cl--loop-args))
	    (push (pop cl--loop-args) cl--loop-finally)))))

     ((memq word '(for as))
      (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
	    (ands nil))
	(while
            ;; Use `gensym' rather than `make-symbol'.  It's important that
	    ;; (not (eq (symbol-name var1) (symbol-name var2))) because
	    ;; these vars get added to the macro-environment.
            (let ((var (or (pop cl--loop-args) (gensym "--cl-var--"))))
	      (setq word (pop cl--loop-args))
	      (if (eq word 'being) (setq word (pop cl--loop-args)))
	      (if (memq word '(the each)) (setq word (pop cl--loop-args)))
	      (if (memq word '(buffer buffers))
		  (setq word 'in
                        cl--loop-args (cons '(buffer-list) cl--loop-args)))
	      (cond

	       ((memq word '(from downfrom upfrom to downto upto
			     above below by))
		(push word cl--loop-args)
		(if (memq (car cl--loop-args) '(downto above))
		    (error "Must specify `from' value for downward cl-loop"))
		(let* ((down (or (eq (car cl--loop-args) 'downfrom)
				 (memq (nth 2 cl--loop-args)
                                       '(downto above))))
		       (excl (or (memq (car cl--loop-args) '(above below))
				 (memq (nth 2 cl--loop-args)
                                       '(above below))))
		       (start (and (memq (car cl--loop-args)
                                         '(from upfrom downfrom))
				   (cl--pop2 cl--loop-args)))
		       (end (and (memq (car cl--loop-args)
				       '(to upto downto above below))
				 (cl--pop2 cl--loop-args)))
		       (step (and (eq (car cl--loop-args) 'by)
                                  (cl--pop2 cl--loop-args)))
		       (end-var (and (not (macroexp-const-p end))
				     (make-symbol "--cl-var--")))
		       (step-var (and (not (macroexp-const-p step))
				      (make-symbol "--cl-var--"))))
		  (and step (numberp step) (<= step 0)
		       (error "Loop `by' value is not positive: %s" step))
		  (push (list var (or start 0)) loop-for-bindings)
		  (if end-var (push (list end-var end) loop-for-bindings))
		  (if step-var (push (list step-var step)
				     loop-for-bindings))
		  (when end
                    (cl--push-clause-loop-body
                     (list
                      (if down (if excl '> '>=) (if excl '< '<=))
                      var (or end-var end))))
		  (push (list var (list (if down '- '+) var
					(or step-var step 1)))
			loop-for-steps)))

	       ((memq word '(in in-ref on))
		(let* ((on (eq word 'on))
		       (temp (if (and on (symbolp var))
				 var (make-symbol "--cl-var--"))))
		  (push (list temp (pop cl--loop-args)) loop-for-bindings)
                  (cl--push-clause-loop-body `(consp ,temp))
		  (if (eq word 'in-ref)
		      (push (list var `(car ,temp)) cl--loop-symbol-macs)
		    (or (eq temp var)
			(progn
			  (push (list var nil) loop-for-bindings)
			  (push (list var (if on temp `(car ,temp)))
				loop-for-sets))))
		  (push (list temp
			      (if (eq (car cl--loop-args) 'by)
				  (let ((step (cl--pop2 cl--loop-args)))
				    (if (and (memq (car-safe step)
						   '(quote function
							   cl-function))
					     (symbolp (nth 1 step)))
					(list (nth 1 step) temp)
				      `(funcall ,step ,temp)))
				`(cdr ,temp)))
			loop-for-steps)))

	       ((eq word '=)
		(let* ((start (pop cl--loop-args))
		       (then (if (eq (car cl--loop-args) 'then)
                                 (cl--pop2 cl--loop-args) start))
                       (first-assign (or cl--loop-first-flag
					 (setq cl--loop-first-flag
					       (make-symbol "--cl-var--")))))
		  (push (list var nil) loop-for-bindings)
		  (if (or ands (eq (car cl--loop-args) 'and))
		      (progn
			(push `(,var (if ,first-assign ,start ,var)) loop-for-sets)
			(push `(,var (if ,(car (cl--loop-build-ands
                                                (nreverse cl--loop-conditions)))
                                         ,then ,var))
                              loop-for-steps))
                    (push (if (eq start then)
		              `(,var ,then)
                            `(,var (if ,first-assign ,start ,then)))
                          loop-for-sets))))

	       ((memq word '(across across-ref))
		(let ((temp-vec (make-symbol "--cl-vec--"))
		      (temp-idx (make-symbol "--cl-idx--")))
		  (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
		  (push (list temp-idx -1) loop-for-bindings)
                  (push `(setq ,temp-idx (1+ ,temp-idx)) cl--loop-body)
		  (cl--push-clause-loop-body
                   `(< ,temp-idx (length ,temp-vec)))
		  (if (eq word 'across-ref)
		      (push (list var `(aref ,temp-vec ,temp-idx))
			    cl--loop-symbol-macs)
		    (push (list var nil) loop-for-bindings)
		    (push (list var `(aref ,temp-vec ,temp-idx))
			  loop-for-sets))))

	       ((memq word '(element elements))
		(let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
			       (and (not (memq (car cl--loop-args) '(in of)))
				    (error "Expected `of'"))))
		      (seq (cl--pop2 cl--loop-args))
		      (temp-seq (make-symbol "--cl-seq--"))
		      (temp-idx
                       (if (eq (car cl--loop-args) 'using)
                           (if (and (= (length (cadr cl--loop-args)) 2)
                                    (eq (caadr cl--loop-args) 'index))
                               (cadr (cl--pop2 cl--loop-args))
                             (error "Bad `using' clause"))
                         (make-symbol "--cl-idx--"))))
		  (push (list temp-seq seq) loop-for-bindings)
		  (push (list temp-idx 0) loop-for-bindings)
		  (if ref
                      (let ((temp-len (make-symbol "--cl-len--")))
			(push (list temp-len `(length ,temp-seq))
			      loop-for-bindings)
			(push (list var `(elt ,temp-seq ,temp-idx))
			      cl--loop-symbol-macs)
                        (cl--push-clause-loop-body `(< ,temp-idx ,temp-len)))
		    (push (list var nil) loop-for-bindings)
		    (cl--push-clause-loop-body `(and ,temp-seq
                                                     (or (consp ,temp-seq)
                                                         (< ,temp-idx (length ,temp-seq)))))
		    (push (list var `(if (consp ,temp-seq)
                                         (pop ,temp-seq)
                                       (aref ,temp-seq ,temp-idx)))
			  loop-for-sets))
		  (push (list temp-idx `(1+ ,temp-idx))
			loop-for-steps)))

	       ((memq word hash-types)
		(or (memq (car cl--loop-args) '(in of))
                    (error "Expected `of'"))
		(let* ((table (cl--pop2 cl--loop-args))
		       (other
                        (if (eq (car cl--loop-args) 'using)
                            (if (and (= (length (cadr cl--loop-args)) 2)
                                     (memq (caadr cl--loop-args) hash-types)
                                     (not (eq (caadr cl--loop-args) word)))
                                (cadr (cl--pop2 cl--loop-args))
                              (error "Bad `using' clause"))
                          (make-symbol "--cl-var--"))))
		  (if (memq word '(hash-value hash-values))
		      (setq var (prog1 other (setq other var))))
		  (cl--loop-set-iterator-function
                   'hash-tables (lambda (body)
                                  `(maphash (lambda (,var ,other) . ,body)
                                            ,table)))))

	       ((memq word '(symbol present-symbol external-symbol
			     symbols present-symbols external-symbols))
		(let ((ob (and (memq (car cl--loop-args) '(in of))
                               (cl--pop2 cl--loop-args))))
		  (cl--loop-set-iterator-function
                   'symbols (lambda (body)
                              `(mapatoms (lambda (,var) . ,body) ,ob)))))

	       ((memq word '(overlay overlays extent extents))
		(let ((buf nil) (from nil) (to nil))
		  (while (memq (car cl--loop-args) '(in of from to))
		    (cond ((eq (car cl--loop-args) 'from)
                           (setq from (cl--pop2 cl--loop-args)))
			  ((eq (car cl--loop-args) 'to)
                           (setq to (cl--pop2 cl--loop-args)))
			  (t (setq buf (cl--pop2 cl--loop-args)))))
		  (cl--loop-set-iterator-function
                   'overlays (lambda (body)
                               `(cl--map-overlays
                                 (lambda (,var ,(make-symbol "--cl-var--"))
                                   (progn . ,body) nil)
                                 ,buf ,from ,to)))))

	       ((memq word '(interval intervals))
		(let ((buf nil) (prop nil) (from nil) (to nil)
		      (var1 (make-symbol "--cl-var1--"))
		      (var2 (make-symbol "--cl-var2--")))
		  (while (memq (car cl--loop-args) '(in of property from to))
		    (cond ((eq (car cl--loop-args) 'from)
                           (setq from (cl--pop2 cl--loop-args)))
			  ((eq (car cl--loop-args) 'to)
                           (setq to (cl--pop2 cl--loop-args)))
			  ((eq (car cl--loop-args) 'property)
			   (setq prop (cl--pop2 cl--loop-args)))
			  (t (setq buf (cl--pop2 cl--loop-args)))))
		  (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
		      (setq var1 (car var) var2 (cdr var))
		    (push (list var nil) loop-for-bindings)
		    (push (list var `(cons ,var1 ,var2)) loop-for-sets))
		  (cl--loop-set-iterator-function
                   'intervals (lambda (body)
                                `(cl--map-intervals
                                  (lambda (,var1 ,var2) . ,body)
                                  ,buf ,prop ,from ,to)))))

	       ((memq word key-types)
		(or (memq (car cl--loop-args) '(in of))
                    (error "Expected `of'"))
                (let ((map (cl--pop2 cl--loop-args))
		      (other
                       (if (eq (car cl--loop-args) 'using)
                           (if (and (= (length (cadr cl--loop-args)) 2)
                                    (memq (caadr cl--loop-args) key-types)
                                    (not (eq (caadr cl--loop-args) word)))
                               (cadr (cl--pop2 cl--loop-args))
                             (error "Bad `using' clause"))
                         (make-symbol "--cl-var--"))))
		  (if (memq word '(key-binding key-bindings))
		      (setq var (prog1 other (setq other var))))
		  (cl--loop-set-iterator-function
                   'keys (lambda (body)
                           `(,(if (memq word '(key-seq key-seqs))
                                  'cl--map-keymap-recursively 'map-keymap)
                             (lambda (,var ,other) . ,body) ,map)))))

	       ((memq word '(frame frames screen screens))
		(let ((temp (make-symbol "--cl-var--")))
		  (push (list var  '(selected-frame))
			loop-for-bindings)
		  (push (list temp nil) loop-for-bindings)
		  (cl--push-clause-loop-body `(prog1 (not (eq ,var ,temp))
                                                (or ,temp (setq ,temp ,var))))
		  (push (list var `(next-frame ,var))
			loop-for-steps)))

	       ((memq word '(window windows))
		(let ((scr (and (memq (car cl--loop-args) '(in of))
                                (cl--pop2 cl--loop-args)))
		      (temp (make-symbol "--cl-var--"))
		      (minip (make-symbol "--cl-minip--")))
		  (push (list var (if scr
				      `(frame-selected-window ,scr)
				    '(selected-window)))
			loop-for-bindings)
		  ;; If we started in the minibuffer, we need to
		  ;; ensure that next-window will bring us back there
		  ;; at some point.  (Bug#7492).
		  ;; (Consider using walk-windows instead of cl-loop if
		  ;; you care about such things.)
		  (push (list minip `(minibufferp (window-buffer ,var)))
			loop-for-bindings)
		  (push (list temp nil) loop-for-bindings)
		  (cl--push-clause-loop-body `(prog1 (not (eq ,var ,temp))
                                                (or ,temp (setq ,temp ,var))))
		  (push (list var `(next-window ,var ,minip))
			loop-for-steps)))

	       (t
		;; This is an advertised interface: (info "(cl)Other Clauses").
		(let ((handler (and (symbolp word)
				    (get word 'cl-loop-for-handler))))
		  (if handler
		      (funcall handler var)
		    (error "Expected a `for' preposition, found %s" word)))))
	      (eq (car cl--loop-args) 'and))
	  (setq ands t)
	  (pop cl--loop-args))
	(if (and ands loop-for-bindings)
	    (push (nreverse loop-for-bindings) cl--loop-bindings)
	  (setq cl--loop-bindings (nconc (mapcar #'list loop-for-bindings)
				         cl--loop-bindings)))
	(if loop-for-sets
	    (push `(progn
                     ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
                     t)
                  cl--loop-body))
	(when loop-for-steps
	  (push (cons (if ands 'cl-psetq 'setq)
		      (apply #'append (nreverse loop-for-steps)))
		cl--loop-steps))))

     ((eq word 'repeat)
      (let ((temp (make-symbol "--cl-var--")))
	(push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
	(push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))

     ((memq word '(collect collecting))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum nil 'nreverse)))
	(if (eq var cl--loop-accum-var)
	    (push `(progn (push ,what ,var) t) cl--loop-body)
	  (push `(progn
                   (setq ,var (nconc ,var (list ,what)))
                   t)
                cl--loop-body))))

     ((memq word '(nconc nconcing append appending))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum nil 'nreverse)))
	(push `(progn
                 (setq ,var
                       ,(if (eq var cl--loop-accum-var)
                            `(nconc
                              (,(if (memq word '(nconc nconcing))
                                    #'nreverse #'reverse)
                               ,what)
                              ,var)
                          `(,(if (memq word '(nconc nconcing))
                                 #'nconc #'append)
                            ,var ,what)))
                 t)
              cl--loop-body)))

     ((memq word '(concat concating))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum "")))
	(push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))

     ((memq word '(vconcat vconcating))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum [])))
	(push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))

     ((memq word '(sum summing))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum 0)))
        (push `(progn (incf ,var ,what) t) cl--loop-body)))

     ((memq word '(count counting))
      (let ((what (pop cl--loop-args))
	    (var (cl--loop-handle-accum 0)))
        (push `(progn (if ,what (incf ,var)) t) cl--loop-body)))

     ((memq word '(minimize minimizing maximize maximizing))
      (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
                                    (pop cl--loop-args)
                       (let* ((var (cl--loop-handle-accum nil))
                              (func (intern (substring (symbol-name word)
                                                       0 3))))
                         `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
                    t)
            cl--loop-body))

     ((eq word 'with)
      (let ((bindings nil))
	(while (progn (push (list (pop cl--loop-args)
				  (and (eq (car cl--loop-args) '=)
                                       (cl--pop2 cl--loop-args)))
			    bindings)
		      (eq (car cl--loop-args) 'and))
	  (pop cl--loop-args))
	(push (nreverse bindings) cl--loop-bindings)))

     ((eq word 'while)
      (push (pop cl--loop-args) cl--loop-body))

     ((eq word 'until)
      (push `(not ,(pop cl--loop-args)) cl--loop-body))

     ((eq word 'always)
      (or cl--loop-finish-flag
          (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
      (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
      (setq cl--loop-result t))

     ((eq word 'never)
      (or cl--loop-finish-flag
          (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
      (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
	    cl--loop-body)
      (setq cl--loop-result t))

     ((eq word 'thereis)
      (or cl--loop-finish-flag
          (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
      (or cl--loop-result-var
          (setq cl--loop-result-var (make-symbol "--cl-var--")))
      (push `(setq ,cl--loop-finish-flag
                   (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
	    cl--loop-body))

     ((memq word '(if when unless))
      (let* ((cond (pop cl--loop-args))
	     (then (let ((cl--loop-body nil))
		     (cl--parse-loop-clause)
		     (cl--loop-build-ands (nreverse cl--loop-body))))
	     (else (let ((cl--loop-body nil))
		     (if (eq (car cl--loop-args) 'else)
			 (progn (pop cl--loop-args) (cl--parse-loop-clause)))
		     (cl--loop-build-ands (nreverse cl--loop-body))))
	     (simple (and (eq (car then) t) (eq (car else) t))))
	(if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
	(if (eq word 'unless) (setq then (prog1 else (setq else then))))
	(let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
			  (if simple (nth 1 else) (list (nth 2 else))))))
	  (setq form (if (cl--expr-contains form 'it)
                         `(let ((it ,cond)) (if it ,@form))
                       `(if ,cond ,@form)))
	  (push (if simple `(progn ,form t) form) cl--loop-body))))

     ((memq word '(do doing))
      (let ((body nil))
	(or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
	(while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
	(push (cons 'progn (nreverse (cons t body))) cl--loop-body)))

     ((eq word 'return)
      (or cl--loop-finish-flag
          (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
      (or cl--loop-result-var
          (setq cl--loop-result-var (make-symbol "--cl-var--")))
      (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
                   ,cl--loop-finish-flag nil)
            cl--loop-body))

     (t
      ;; This is an advertised interface: (info "(cl)Other Clauses").
      (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
	(or handler (error "Expected a cl-loop keyword, found %s" word))
	(funcall handler))))
    (if (eq (car cl--loop-args) 'and)
	(progn (pop cl--loop-args) (cl--parse-loop-clause)))))

(defun cl--unused-var-p (sym)
  (or (null sym) (eq ?_ (aref (symbol-name sym) 0))))

(defun cl--loop-let (specs body par)    ; modifies cl--loop-bindings
  "Build an expression equivalent to (let SPECS BODY).
SPECS can include bindings using `cl-loop's destructuring (not to be
confused with the patterns of `cl-destructuring-bind').
If PAR is nil, do the bindings step by step, like `let*'.
If BODY is `setq', then use SPECS for assignments rather than for bindings."
  (let ((temps nil) (new nil))
    (when par
      (let ((p specs))
        (while (and p (or (symbolp (car-safe (car p))) (null (cadar p))))
          (setq p (cdr p)))
        (when p
          (setq par nil)
          (dolist (spec specs)
            (or (macroexp-const-p (cadr spec))
                (let ((temp (make-symbol "--cl-var--")))
                  (push (list temp (cadr spec)) temps)
                  (setcar (cdr spec) temp)))))))
    (while specs
      (let* ((binding (pop specs))
             (spec (car-safe binding)))
        (if (and (consp binding) (or (consp spec) (cl--unused-var-p spec)))
            (let* ((nspecs nil)
                   (expr (car (cdr-safe binding)))
                   (temp (last spec 0)))
              (if (and (cl--unused-var-p temp) (null expr))
                  nil ;; Don't bother declaring/setting `temp' since it won't
		      ;; be used when `expr' is nil, anyway.
		(when (or (null temp)
                          (and (eq body 'setq) (cl--unused-var-p temp)))
                  ;; Prefer a fresh uninterned symbol over "_to", to avoid
                  ;; warnings that we set an unused variable.
                  (setq temp (make-symbol "--cl-var--"))
                  ;; Make sure this temp variable is locally declared.
                  (when (eq body 'setq)
                    (push (list (list temp)) cl--loop-bindings)))
                (push (list temp expr) new))
              (while (consp spec)
                (push (list (pop spec)
                            (and expr (list (if spec 'pop 'car) temp)))
                      nspecs))
              (setq specs (nconc (nreverse nspecs) specs)))
          (push binding new))))
    (if (eq body 'setq)
	(let ((set (cons (if par 'cl-psetq 'setq)
                         (apply #'nconc (nreverse new)))))
	  (if temps `(let* ,(nreverse temps) ,set) set))
      `(,(if par 'let 'let*)
        ,(nconc (nreverse temps) (nreverse new)) ,@body))))

(defun cl--loop-handle-accum (def &optional func) ; uses loop-*
  (if (eq (car cl--loop-args) 'into)
      (let ((var (cl--pop2 cl--loop-args)))
	(or (memq var cl--loop-accum-vars)
	    (progn (push (list (list var def)) cl--loop-bindings)
		   (push var cl--loop-accum-vars)))
	var)
    (or cl--loop-accum-var
	(progn
	  (push (list (list
                       (setq cl--loop-accum-var (make-symbol "--cl-var--"))
                       def))
                cl--loop-bindings)
	  (setq cl--loop-result (if func (list func cl--loop-accum-var)
                                  cl--loop-accum-var))
	  cl--loop-accum-var))))

(defun cl--loop-build-ands (clauses)
  "Return various representations of (and . CLAUSES).
CLAUSES is a list of Elisp expressions, where clauses of the form
\(progn E1 E2 E3 .. t) are the focus of particular optimizations.
The return value has shape (COND BODY COMBO)
such that COMBO is equivalent to (and . CLAUSES)."
  (let ((ands nil)
	(body nil))
    ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
    ;; into (progn ,@A ,@B) ,@C.
    (while clauses
      (if (and (eq (car-safe (car clauses)) 'progn)
	       (eq (car (last (car clauses))) t))
	  (if (cdr clauses)
	      (setq clauses (cons (nconc (butlast (car clauses))
					 (if (eq (car-safe (cadr clauses))
						 'progn)
                                             (cdadr clauses)
					   (list (cadr clauses))))
				  (cddr clauses)))
            ;; A final (progn ,@A t) is moved outside of the `and'.
	    (setq body (cdr (butlast (pop clauses)))))
	(push (pop clauses) ands)))
    (setq ands (or (nreverse ands) (list t)))
    (list (if (cdr ands) (cons 'and ands) (car ands))
	  body
	  (let ((full (if body
			  (append ands (list (cons 'progn (append body '(t)))))
			ands)))
	    (if (cdr full) (cons 'and full) (car full))))))


(defun cl--map-intervals (func &optional what prop start end)
  (or what (setq what (current-buffer)))
  (if (bufferp what)
      (let (mark mark2 (next t) next2)
        (with-current-buffer what
          (setq mark (copy-marker (or start (point-min))))
          (setq mark2 (and end (copy-marker end))))
        (while (and next (or (not mark2) (< mark mark2)))
          (setq next (if prop (next-single-property-change
                               mark prop what)
                       (next-property-change mark what))
                next2 (or next (with-current-buffer what
                                 (point-max))))
          (funcall func (prog1 (marker-position mark)
                          (set-marker mark next2))
                   (if mark2 (min next2 mark2) next2)))
        (set-marker mark nil) (if mark2 (set-marker mark2 nil)))
    (or start (setq start 0))
    (or end (setq end (length what)))
    (while (< start end)
      (let ((next (or (if prop (next-single-property-change
                                start prop what)
                        (next-property-change start what))
                      end)))
        (funcall func start (min next end))
        (setq start next)))))

;;;###autoload
(defun cl--map-overlays (func &optional buffer start end arg)
  (or buffer (setq buffer (current-buffer)))
  (let (ovl)
    (with-current-buffer buffer
      (setq ovl (overlay-lists))
      (if start (setq start (copy-marker start)))
      (if end (setq end (copy-marker end))))
    (setq ovl (nconc (car ovl) (cdr ovl)))
    (while (and ovl
                (or (not (overlay-start (car ovl)))
                    (and end (>= (overlay-start (car ovl)) end))
                    (and start (<= (overlay-end (car ovl)) start))
                    (not (funcall func (car ovl) arg))))
      (setq ovl (cdr ovl)))
    (if start (set-marker start nil))
    (if end (set-marker end nil))))

;;; ---- cl-macs.el / cl-extra.el: the remaining macro and number surface ----
;; Ported from GNU Emacs 31.1's cl-macs.el, cl-extra.el and cl-lib.el.

(defmacro cl-with-gensyms (names &rest body)
  "Bind each of NAMES to an uninterned symbol and evaluate BODY."
  (declare (debug (sexp body)) (indent 1))
  `(let ,(cl-loop for name in names collect
                  `(,name (gensym (symbol-name ',name))))
     ,@body))

(defmacro cl-once-only (names &rest body)
  "Generate code to evaluate each of NAMES just once in BODY."
  (declare (debug (sexp body)) (indent 1))
  (setq names (mapcar #'ensure-list names))
  (let ((our-gensyms (cl-loop for _ in names collect (gensym))))
    `(let ,(cl-loop for sym in our-gensyms collect `(,sym (gensym)))
       `(let ,(list
               ,@(cl-loop for name in names for gensym in our-gensyms
                          for to-eval = (or (cadr name) (car name))
                          collect ``(,,gensym ,,to-eval)))
          ,(let ,(cl-loop for name in names for gensym in our-gensyms
                          collect `(,(car name) ,gensym))
             ,@body)))))

(defmacro cl-with-accessors (bindings instance &rest body)
  "Use BINDINGS as function calls on INSTANCE inside BODY."
  (declare (debug [(&rest (symbolp symbolp)) form body])
           (indent 2))
  (cond ((null body)
         (macroexp-warn-and-return "`cl-with-accessors' used with empty body"
                                   nil 'empty-body))
        ((null bindings)
         (macroexp-warn-and-return "`cl-with-accessors' used without accessors"
                                   (macroexp-progn body)
                                   'suspicious))
        (t
         (cl-once-only (instance)
           (let ((symbol-macros))
             (dolist (b bindings)
               (pcase b
                 (`(,(and (pred symbolp) var)
                    ,(and (pred symbolp) accessor))
                  (push `(,var (,accessor ,instance))
                        symbol-macros))
                 (_
                  (error "Malformed `cl-with-accessors' binding: %S" b))))
             `(cl-symbol-macrolet
                  ,symbol-macros
                ,@body))))))

;; `cl-tagbody': each label starts a block of a `cl-case' dispatched from a
;; `while' loop; `go' is a local macro, supplied through `macroexpand-all''s
;; ENVIRONMENT, that throws the next label to the loop's catch.
(defvar cl--tagbody-alist nil)
(defmacro cl-tagbody (&rest labels-or-stmts)
  "Execute statements while providing for control transfers to labels."
  (let ((blocks '())
        (first-label (if (consp (car labels-or-stmts))
                         'cl--preamble (pop labels-or-stmts))))
    (let ((block (list first-label)))
      (dolist (label-or-stmt labels-or-stmts)
        (if (consp label-or-stmt) (push label-or-stmt block)
          (unless (eq 'go (car-safe (car-safe block)))
            (push `(go ,label-or-stmt) block))
          (push (nreverse block) blocks)
          (setq block (list label-or-stmt))))
      (unless (eq 'go (car-safe (car-safe block)))
        (push '(go cl--exit) block))
      (push (nreverse block) blocks))
    (let ((catch-tag (make-symbol "cl--tagbody-tag"))
          (cl--tagbody-alist cl--tagbody-alist))
      (push (cons 'cl--exit catch-tag) cl--tagbody-alist)
      (dolist (block blocks)
        (push (cons (car block) catch-tag) cl--tagbody-alist))
      (macroexpand-all
       `(let ((next-label ',first-label))
          (while
              (not (eq (setq next-label
                             (catch ',catch-tag
                               (cl-case next-label
                                 ,@blocks)))
                       'cl--exit))))
       `((go . ,(lambda (label)
                  (let ((catch-tag (cdr (assq label cl--tagbody-alist))))
                    (unless catch-tag
                      (error "Unknown cl-tagbody go label `%S'" label))
                    `(throw ',catch-tag ',label))))
         ,@macroexpand-all-environment)))))

(defun cl--prog (binder bindings body)
  (let (decls)
    (while (eq 'declare (car-safe (car body)))
      (push (pop body) decls))
    `(cl-block nil
       (,binder ,bindings
         ,@(nreverse decls)
         (cl-tagbody . ,body)))))
(defmacro cl-prog (bindings &rest body)
  "Run BODY like a `cl-tagbody' after setting up the BINDINGS."
  (cl--prog 'let bindings body))
(defmacro cl-prog* (bindings &rest body)
  "Run BODY like a `cl-tagbody' after setting up the BINDINGS."
  (cl--prog 'let* bindings body))

(defmacro cl-do-symbols (spec &rest body)
  "Loop over all symbols, or all symbols of OBARRAY."
  (declare (indent 1))
  `(cl-block nil
     (let (,(car spec))
       (mapatoms #'(lambda (,(car spec)) ,@body)
                 ,@(and (cadr spec) (list (cadr spec))))
       ,(nth 2 spec))))
(defmacro cl-do-all-symbols (spec &rest body)
  "Like `cl-do-symbols', but use the default obarray."
  (declare (indent 1))
  `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))

;; Outside the byte-compiler FORM is evaluated at expansion time and quoted.
(defmacro cl-load-time-value (form &optional _read-only)
  "Like `progn', but evaluates the body at load time."
  `',(eval form lexical-binding))

;; Declarations only matter to the byte-compiler; interpreted, this is nil.
(defmacro cl-declare (&rest _specs)
  "Declare SPECS about the current function while compiling."
  nil)

(defmacro cl-define-compiler-macro (func args &rest body)
  "Define a compiler-only macro."
  (declare (indent 2))
  (let ((p args) (res nil))
    (while (consp p) (push (pop p) res))
    (setq args (nconc (nreverse res) (and p (list '&rest p)))))
  (let ((fname (intern (concat (symbol-name func) "--cmacro"))))
    `(eval-and-compile
       (cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
                           (cons '_cl-whole-arg args))
         ,@body)
       (define-symbol-prop ',func 'compiler-macro #',fname))))

(defun cl-compiler-macroexpand (form)
  "Like `macroexpand', but for compiler macros."
  (while
      (let ((func (car-safe form)) (handler nil))
        (while (and (symbolp func)
                    (not (setq handler (get func 'compiler-macro)))
                    (fboundp func)
                    (or (not (autoloadp (symbol-function func)))
                        (autoload-do-load (symbol-function func) func)))
          (setq func (symbol-function func)))
        (and handler
             (not (eq form (setq form (apply handler form (cdr form))))))))
  form)

;; cl-macs.el (31.1): optimize away unused block-wrappers. `cl--block-throw'
;; marks its block as used while the wrapper's body is expanded; a block nothing
;; throws to expands to its body alone.
(defvar cl--active-block-names nil)

(cl-define-compiler-macro cl--block-wrapper (form)
  (pcase form
    (`(let ((,var . ,val)) (catch ,var . ,body))
     (let* ((cl-entry (cons var nil))
            (cl--active-block-names (cons cl-entry cl--active-block-names))
            (cl-body (macroexpand-all      ;Performs compiler-macro expansions.
                      (macroexp-progn body)
                      macroexpand-all-environment)))
       ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
       ;; to indicate that this return value is already fully expanded.
       (if (cdr cl-entry)
           `(let ((,var . ,val)) (catch ,var ,@(macroexp-unprogn cl-body)))
           cl-body)))
    ;; `form' was somehow mangled, god knows what happened, let's not touch it.
    (_ form)))

(cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
  (let ((cl-found (and (symbolp cl-tag) (assq cl-tag cl--active-block-names))))
    (if cl-found (setcdr cl-found t)))
  `(throw ,cl-tag ,cl-value))

;; Emacs also gives the function an inlining compiler macro built on
;; `cl--defsubst-expand'; that rewrite only changes how a call is compiled,
;; not what it returns, and is not ported.
(defmacro cl-defsubst (name args &rest body)
  "Define NAME as a function, like `cl-defun'."
  (declare (indent 2))
  `(progn nil (cl-defun ,name ,args ,@body)))

;; cl-extra.el's random-number generator: "ran3" from Numerical Recipes, an
;; additive congruential method over a 55-entry state vector.
(defun cl--random-time ()
  (car (time-convert nil t)))
(cl-defstruct (cl--random-state
               (:copier nil)
               (:predicate cl-random-state-p)
               (:constructor nil)
               (:constructor cl--make-random-state (vec)))
  (i -1) (j 30) vec)
(defvar cl--random-state (cl--make-random-state (cl--random-time)))
(defun cl-random (lim &optional state)
  "Return a pseudo-random nonnegative number less than LIM, an integer or float."
  (or state (setq state cl--random-state))
  (let ((vec (cl--random-state-vec state)))
    (if (integerp vec)
        (let ((i 0) (j (- 1357335 (abs (% vec 1357333)))) (k 1))
          (setf (cl--random-state-vec state)
                (setq vec (make-vector 55 nil)))
          (aset vec 0 j)
          (while (> (setq i (% (+ i 21) 55)) 0)
            (aset vec i (setq j (prog1 k (setq k (- j k))))))
          (while (< (setq i (1+ i)) 200) (cl-random 2 state))))
    (let* ((i (cl-callf (lambda (x) (% (1+ x) 55)) (cl--random-state-i state)))
           (j (cl-callf (lambda (x) (% (1+ x) 55)) (cl--random-state-j state)))
           (n (aset vec i (logand 8388607 (- (aref vec i) (aref vec j))))))
      (cond
       ((natnump lim)
        (if (<= lim 512) (% n lim)
          (if (> lim 8388607) (setq n (+ (ash n 9) (cl-random 512 state))))
          (let ((mask 1023))
            (while (< mask (1- lim)) (setq mask (1+ (+ mask mask))))
            (if (< (setq n (logand n mask)) lim) n (cl-random lim state)))))
       ((< 0 lim 1.0e+INF)
        (* (/ n '8388608e0) lim))
       (t
        (error "Limit %S not supported by cl-random" lim))))))
(defun cl-make-random-state (&optional state)
  "Return a copy of random-state STATE, or of the internal state if omitted."
  (unless state (setq state cl--random-state))
  (if (cl-random-state-p state)
      (copy-sequence state)
    (cl--make-random-state (if (integerp state) state (cl--random-time)))))

;; cl-lib.el's float parameters are nil until `cl-float-limits' measures them.
(defconst cl-most-positive-float nil)
(defconst cl-most-negative-float nil)
(defconst cl-least-positive-float nil)
(defconst cl-least-negative-float nil)
(defconst cl-least-positive-normalized-float nil)
(defconst cl-least-negative-normalized-float nil)
(defconst cl-float-epsilon nil)
(defconst cl-float-negative-epsilon nil)
(defun cl--finite-do (func a b)
  (condition-case _
      (let ((res (funcall func a b)))
        (and (numberp res) (/= res (/ res 2)) res))
    (arith-error nil)))
(defun cl-float-limits ()
  "Initialize the Common Lisp floating-point parameters."
  (or cl-most-positive-float (not (numberp '2e1))
      (let ((x '2e0) y z)
        (while (cl--finite-do '* x x) (setq x (* x x)))
        (while (cl--finite-do '* x (/ x 2)) (setq x (* x (/ x 2))))
        (while (cl--finite-do '+ x x) (setq x (+ x x)))
        (setq z x y (/ x 2))
        (while (and (cl--finite-do '+ x y) (/= (+ x y) x))
          (setq x (+ x y) y (/ y 2)))
        (setq cl-most-positive-float x
              cl-most-negative-float (- x))
        (setq x (/ x z) y (/ 16 z) x (* x y))
        (while (condition-case _ (and (= x (* (/ x 2) 2)) (> (/ y 2) 0))
                 (arith-error nil))
          (setq x (/ x 2) y (/ y 2)))
        (setq cl-least-positive-normalized-float y
              cl-least-negative-normalized-float (- y))
        (setq x (/ z) y x)
        (while (condition-case _ (> (/ x 2) 0) (arith-error nil))
          (setq x (/ x 2)))
        (setq cl-least-positive-float x
              cl-least-negative-float (- x))
        (setq x '1e0)
        (while (/= (+ '1e0 x) '1e0) (setq x (/ x 2)))
        (setq cl-float-epsilon (* x 2))
        (setq x '1e0)
        (while (/= (- '1e0 x) '1e0) (setq x (/ x 2)))
        (setq cl-float-negative-epsilon (* x 2))))
  nil)
(define-obsolete-function-alias 'cl-floatp-safe 'floatp "24.4")

;; subr.el: KEY is present even when its value is nil.
(let ((missing (make-symbol "missing")))
  (defun hash-table-contains-p (key table)
    "Return non-nil if TABLE has an element with KEY."
    (not (eq (gethash key table missing) missing))))

;; cl-extra.el; `terpri''s ENSURE does the bolp test.
(defun cl-fresh-line (&optional stream)
  "Output a newline unless already at the beginning of a line."
  (terpri stream 'ensure))
;; doc.c `documentation' / `documentation-property' and simple.el's
;; `function-documentation' (Emacs 31.1). There is no etc/DOC file, so a
;; primitive's docstring is nil.
(defun documentation-property (symbol prop &optional raw)
  (let ((tem (get symbol prop)))
    (if (and (null tem) (eq prop 'variable-documentation)
             (not (eq symbol (indirect-variable symbol))))
        (documentation-property (indirect-variable symbol) prop raw)
      (when (eql tem 0) (setq tem nil))
      (unless (stringp tem) (setq tem (eval tem nil)))
      (if (and (null raw) (stringp tem)) (substitute-command-keys tem) tem))))
(defun function-documentation (function)
  (cond
   ((closurep function)
    (when (> (length function) 4)
      (let ((doc (aref function 4)))
        (when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc))))
   ((or (stringp function) (vectorp function)) "Keyboard macro.")
   ((eq (car-safe function) 'keymap)
    "Prefix command (definition is a keymap associating keystrokes with commands).")
   ((memq (car-safe function) '(lambda autoload))
    (let ((doc (car (cdr (cdr function)))))
      (when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc)))
   ((symbolp function)
    (let ((f (indirect-function function)))
      (if f (function-documentation f)
        (signal 'void-function (list function)))))
   ((eq (car-safe function) 'macro) (function-documentation (cdr function)))
   ;; elisprs holds a defmacro's `(macro . FN)' as FN's closure flagged as a
   ;; macro: `car-safe' does not open it and `closurep' rejects it, but its
   ;; docstring slot is FN's.
   ((and (not (symbolp function)) (macrop function))
    (when (> (length function) 4)
      (let ((doc (aref function 4)))
        (when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc))))
   ((subrp function) nil)
   (t (signal 'invalid-function (list function)))))
(defun documentation (function &optional raw)
  (if (and (symbolp function) (get function 'function-documentation))
      (documentation-property function 'function-documentation raw)
    (let ((fun (indirect-function function)))
      (unless fun (signal 'void-function (list function)))
      (when (eq (car-safe fun) 'macro) (setq fun (cdr fun)))
      (let ((doc (function-documentation fun)))
        (if (eql doc 0) (setq doc nil))
        (if raw doc (substitute-command-keys doc))))))
;; The per-buffer variables of buffer.c (`DEFVAR_PER_BUFFER') and the C
;; variables Emacs makes automatically buffer-local at startup, as GNU Emacs
;; 31.1 `emacs -Q --batch' has them: every one is bound, and setting one in a
;; buffer gives that buffer its own value instead of changing every buffer's.
;; Defaults are the measured `default-value's; `mode-line-format' holds
;; bindings.el's construct (whose parts are not defined: nothing displays it).
;; Left out: `lexical-binding' (rebound by `load'); `enable-multibyte-characters'
;; is one of the always-local slots below, and only `set-buffer-multibyte' sets it.
(dolist (var '(case-fold-search case-symbols-as-words deactivate-mark
               multibyte-syntax-as-symbol parse-sexp-ignore-comments
               parse-sexp-lookup-properties show-trailing-whitespace tab-width))
  (make-variable-buffer-local var))
(defvar-local abbrev-mode nil)
(defvar-local auto-composition-function 'auto-compose-chars)
(defvar-local auto-composition-mode t)
(defvar-local auto-fill-function nil)
(defvar-local bidi-display-reordering t)
(defvar-local bidi-paragraph-separate-re nil)
(defvar-local bidi-paragraph-start-re nil)
(defvar-local buffer-auto-save-file-format t)
(defvar-local buffer-auto-save-file-name nil)
(defvar-local buffer-backed-up nil)
(defvar-local buffer-display-count 0)
(defvar-local buffer-display-table nil)
(defvar-local buffer-display-time nil)
(defvar-local buffer-file-coding-system 'utf-8-unix)
(defvar-local buffer-file-format nil)
(defvar-local buffer-file-name nil)
(defvar-local buffer-file-truename nil)
(defvar-local buffer-invisibility-spec t)
(defvar-local buffer-saved-size 0)
(defvar-local cache-long-scans t)
(defvar-local ctl-arrow t)
(defvar-local cursor-in-non-selected-windows t)
(defvar-local cursor-type t)
(defvar-local display-fill-column-indicator nil)
(defvar-local display-fill-column-indicator-character nil)
(defvar-local display-fill-column-indicator-column t)
(defvar-local display-line-numbers nil)
(defvar-local display-line-numbers-offset 0)
(defvar-local display-line-numbers-widen nil)
(defvar-local display-line-numbers-width nil)
(defvar-local expose-hidden-buffer nil)
(defvar-local fill-column 70)
(defvar-local fontification-functions nil)
(defvar-local fringe-cursor-alist nil)
(defvar-local fringe-indicator-alist nil)
(defvar-local fringes-outside-margins nil)
(defvar-local header-line-format nil)
(defvar-local horizontal-scroll-bar t)
(defvar-local indicate-buffer-boundaries nil)
(defvar-local indicate-empty-lines nil)
(defvar-local left-fringe-width nil)
(defvar-local left-margin 0)
(defvar-local left-margin-width 0)
(defvar-local line-prefix nil)
(defvar-local line-spacing nil)
(defvar-local make-window-start-visible nil)
(defvar-local mode-line-format
  '("%e" mode-line-front-space mode-line-mule-info mode-line-client
    mode-line-modified mode-line-remote mode-line-window-dedicated
    mode-line-frame-identification mode-line-buffer-identification "   "
    mode-line-position (project-mode-line project-mode-line-format)
    (vc-mode vc-mode) "  " mode-line-modes mode-line-misc-info
    mode-line-end-spaces))
(defvar-local mark-active nil)
(defvar-local minor-mode-overriding-map-alist nil)
(defvar-local overwrite-mode nil)
(defvar-local point-before-scroll nil)
(defvar-local post-command-hook nil)
(defvar-local pre-command-hook nil)
(defvar-local right-fringe-width nil)
(defvar-local right-margin-width 0)
(defvar-local scroll-bar-height nil)
(defvar-local scroll-bar-width nil)
(defvar-local scroll-down-aggressively nil)
(defvar-local scroll-up-aggressively nil)
(defvar-local selective-display nil)
(defvar-local selective-display-ellipses t)
(defvar-local tab-line-format nil)
(defvar-local text-conversion-style nil)
(defvar-local text-property-default-nonsticky '((composition . t) (syntax-table . t) (display . t)))
(defvar-local treesit-language-remap-alist nil)
(defvar-local vertical-scroll-bar t)
(defvar-local word-wrap nil)
(defvar-local wrap-prefix nil)
;; The always-local slots: `buffer_local_flags' is -1 for these in buffer.c
;; `init_buffer_once', so every buffer has its own value from birth
;; (`local-variable-p' is t in a fresh buffer) and `kill-local-variable' keeps
;; it. The second element is what a new buffer starts with: `reset_buffer' /
;; `reset_buffer_local_variables' store constants, `default-directory' is the
;; creating buffer's, and `buffer-undo-list' is t only in a buffer whose name
;; starts with a space (`Fget_buffer_create').
(dolist (slot '((buffer-file-name nil) (buffer-file-truename nil)
                (default-directory :inherit) (buffer-backed-up nil)
                (buffer-saved-size 0) (buffer-auto-save-file-name nil)
                (buffer-read-only nil) (major-mode fundamental-mode)
                (local-minor-modes nil) (mode-name "Fundamental")
                (buffer-undo-list :undo-list) (mark-active nil)
                (point-before-scroll nil) (buffer-invisibility-spec t)
                (buffer-file-format nil) (buffer-auto-save-file-format t)
                (buffer-display-count 0) (buffer-display-time nil)
                (enable-multibyte-characters t)))
  (--make-always-local-- (car slot) (cadr slot)))
;; The startup buffers now hold the working directory; the default, which only
;; `default-value' sees, is nil as in Emacs.
(setq-default default-directory nil)
;; lisp-mode.el (preloaded): the docstring positions and indentation of the
;; definers and special forms, which have no `declare' of their own.
(put 'autoload 'doc-string-elt 3)
(put 'defmethod 'doc-string-elt 3)
(put 'defvar   'doc-string-elt 3)
(put 'defconst 'doc-string-elt 3)
(put 'defalias 'doc-string-elt 3)
(put 'defvaralias 'doc-string-elt 3)
(put 'define-category 'doc-string-elt 2)
(put 'defconstant 'doc-string-elt 3)
(put 'define-compiler-macro 'doc-string-elt 3)
(put 'define-setf-expander 'doc-string-elt 3)
(put 'defparameter 'doc-string-elt 3)
(put 'defstruct 'doc-string-elt 2)
(put 'deftype 'doc-string-elt 3)
(put 'autoload 'lisp-indent-function 'defun) ;Elisp
(put 'progn 'lisp-indent-function 0)
(put 'defvar 'lisp-indent-function 'defun)
(put 'defalias 'lisp-indent-function 'defun)
(put 'defvaralias 'lisp-indent-function 'defun)
(put 'defconst 'lisp-indent-function 'defun)
(put 'define-category 'lisp-indent-function 'defun)
(put 'define-charset-internal 'lisp-indent-function 'defun)
(put 'define-fringe-bitmap 'lisp-indent-function 'defun)
(put 'prog1 'lisp-indent-function 1)
(put 'save-excursion 'lisp-indent-function 0)      ;Elisp
(put 'save-restriction 'lisp-indent-function 0)    ;Elisp
(put 'save-current-buffer 'lisp-indent-function 0) ;Elisp
(put 'let 'lisp-indent-function 1)
(put 'let* 'lisp-indent-function 1)
(put 'while 'lisp-indent-function 1)
(put 'if 'lisp-indent-function 2)
(put 'catch 'lisp-indent-function 1)
(put 'condition-case 'lisp-indent-function 2)
(put 'handler-case 'lisp-indent-function 1) ;CL
(put 'unwind-protect 'lisp-indent-function 1)
"#;

/// Faithful port of emacs-lisp/nadvice.el (Emacs 30.2) — the modern light-weight
/// advice primitives. `advice-add`/`advice-remove`/`add-function`/
/// `remove-function`/`define-advice`/`advice-member-p` plus every combinator
/// (`:around` `:before` `:after` `:override` `:filter-args` `:filter-return`
/// `:before-while` `:before-until` `:after-while` `:after-until`). An advice is an
/// `advice` oclosure holding (car cdr how props); `advice--make` threads them into
/// the symbol-function cell honoring `depth`. This is *source-symbol* advice —
/// entirely distinct from the glob-AOP intercept layer (src/intercepts.rs).
///
/// Kept in its own segment because nadvice.el's `cl-print-object` method embeds
/// the literal `"#f(advice …)"`, whose `"#` would terminate PRELUDE's `r#"…"#`.
///
/// elisprs divergences (NAMED — the advice API/combinators match Emacs exactly;
/// only Emacs-help cosmetics are omitted):
///  * Docstring builders (`advice--make-docstring`, `nadvice--make-docstring`,
///    the `function-documentation` puts) are omitted — they exist only to enrich
///    `describe-function` output.
///  * Interactive-spec propagation (`advice--interactive-form*`,
///    `oclosure-interactive-form`) and the `cl-print-object` printer are omitted
///    (cosmetic; advised functions still run identically).
///  * `advice--called-interactively-skip` (+ its hook) is omitted — it only
///    adjusts `called-interactively-p` frame counting.
///  * Buffer-local advice places (`advice--buffer-local`/`advice--forward`) are
///    omitted; `advice--normalize-place` still supports symbol / `(var V)` /
///    raw gv-place forms (what `advice-add` and typical configs use).
pub const NADVICE: &str = r##"
(oclosure-define (advice
                  (:predicate advice--p)
                  (:copier advice--cons (cdr))
                  (:copier advice--copy (car cdr how props)))
  car cdr how props)

;; advice--how-alist maps each HOW keyword to a prototype `advice' oclosure whose
;; body combines the added FUNCTION (`car') with the previous definition (`cdr').
(eval-when-compile
  (defmacro advice--make-how-alist (&rest args)
    `(list
      ,@(mapcar
         (lambda (arg)
           (pcase-let ((`(,how . ,body) arg))
             `(list ,how
                    (oclosure-lambda (advice (how ,how)) (&rest r)
                      ,@body))))
         args))))

(defvar advice--how-alist
  (advice--make-how-alist
   (:around (apply car cdr r))
   (:before (apply car r) (apply cdr r))
   (:after (prog1 (apply cdr r) (apply car r)))
   (:override (apply car r))
   (:after-until (or (apply cdr r) (apply car r)))
   (:after-while (and (apply cdr r) (apply car r)))
   (:before-until (or (apply car r) (apply cdr r)))
   (:before-while (and (apply car r) (apply cdr r)))
   (:filter-args (apply cdr (funcall car r)))
   (:filter-return (funcall car (apply cdr r))))
  "List of descriptions of how to add a function.
Each element has the form (HOW OCL) where HOW is a keyword and OCL is a
\"prototype\" function of type `advice'.")

(defun advice--cd*r (f)
  (while (advice--p f)
    (setq f (advice--cdr f)))
  f)

(defun advice--make (how function main props)
  "Build a function value that adds FUNCTION to MAIN at HOW.
HOW is a symbol to select an entry in `advice--how-alist'."
  (let ((fd (or (cdr (assq 'depth props)) 0))
        (md (if (advice--p main)
                (or (cdr (assq 'depth (advice--props main))) 0))))
    (if (and md (> fd md))
        ;; `function' should go deeper.
        (let ((rest (advice--make how function (advice--cdr main) props)))
          (advice--cons main rest))
      (let ((proto (assq how advice--how-alist)))
        (unless proto (error "Unknown add-function location `%S'" how))
        (advice--copy (cadr proto)
                      function main how props)))))

(defun advice--member-p (function use-name definition)
  (let ((found nil))
    (while (and (not found) (advice--p definition))
      (if (if (eq use-name :use-both)
	      (or (equal function
			 (cdr (assq 'name (advice--props definition))))
		  (equal function (advice--car definition)))
	    (equal function (if use-name
				(cdr (assq 'name (advice--props definition)))
			      (advice--car definition))))
          (setq found definition)
        (setq definition (advice--cdr definition))))
    found))

(defun advice--tweak (flist tweaker)
  (if (not (advice--p flist))
      (funcall tweaker nil flist nil)
    (let ((first (advice--car flist))
          (rest (advice--cdr flist))
          (props (advice--props flist)))
      (let ((val (funcall tweaker first rest props)))
        (if val (car val)
          (let ((nrest (advice--tweak rest tweaker)))
            (if (eq rest nrest) flist
              (advice--cons flist nrest))))))))

(defun advice--remove-function (flist function)
  (advice--tweak flist
                 (lambda (first rest props)
                   (cond ((not first) rest)
                         ((or (equal function first)
                              (equal function (cdr (assq 'name props))))
                          (list (advice--remove-function rest function)))))))

(eval-and-compile
  (defun advice--normalize-place (place)
    (cond ((eq 'local (car-safe place))
           (error "Buffer-local advice places are unsupported"))
          ((eq 'var (car-safe place))   (nth 1 place))
          ((symbolp place)              `(default-value ',place))
          (t place))))

(defmacro add-function (how place function &optional props)
  "Add a piece of advice on the function stored at PLACE.
FUNCTION describes the code to add.  HOW describes how to add it (see
`advice--how-alist').  PROPS is an alist; `name' and `depth' are special."
  (declare
   (debug (form [&or symbolp ("local" form) ("var" sexp) gv-place]
                form &optional form)))
  `(advice--add-function ,how (gv-ref ,(advice--normalize-place place))
                         ,function ,props))

(defun advice--add-function (how ref function props)
  (let* ((name (cdr (assq 'name props)))
         (a (advice--member-p (or name function) (if name t) (gv-deref ref))))
    (when a
      ;; The advice is already present.  Remove the old one, first.
      (setf (gv-deref ref)
            (advice--remove-function (gv-deref ref)
                                     (or name (advice--car a)))))
    (setf (gv-deref ref)
          (advice--make how function (gv-deref ref) props))))

(defmacro remove-function (place function)
  "Remove the FUNCTION piece of advice from PLACE.
If FUNCTION was not added to PLACE, do nothing.  FUNCTION can also be the
`name' of the piece of advice."
  (declare (debug ([&or symbolp ("local" form) ("var" sexp) gv-place]
                   form)))
  (gv-letplace (getter setter) (advice--normalize-place place)
    (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
      `(unless (eq ,new ,getter) ,(funcall setter new)))))

(defun advice-function-mapc (f function-def)
  "Apply F to every advice function in FUNCTION-DEF.
F is called with two arguments: the added function and its props alist."
  (while (advice--p function-def)
    (funcall f (advice--car function-def) (advice--props function-def))
    (setq function-def (advice--cdr function-def))))

(defun advice-function-member-p (advice function-def)
  "Return non-nil if ADVICE is already in FUNCTION-DEF.
ADVICE can also be the `name' of the piece of advice."
  (advice--member-p advice :use-both function-def))

;;;; Specific application of add-function to `symbol-function' for advice.

(defun advice--subst-main (old new)
  (advice--tweak old
                 (lambda (first _rest _props) (if (not first) new))))

(defun advice--normalize (symbol def)
  (cond
   ((special-form-p def)
    (error "Advice impossible: %S is a special form" symbol))
   ((and (symbolp def) (macrop def))
    (let ((newval `(macro . ,(lambda (&rest r) (macroexpand `(,def . ,r))))))
      (put symbol 'advice--saved-rewrite (cons def (cdr newval)))
      newval))
   ;; `f' might be a pure (hence read-only) cons!
   ((and (eq 'macro (car-safe def))
	 (not (ignore-errors (setcdr def (cdr def)) t)))
    (cons 'macro (cdr def)))
   (t def)))

(defsubst advice--strip-macro (x)
  (if (eq 'macro (car-safe x)) (cdr x) x))

(defun advice--symbol-function (symbol)
  ;; Conceptually the symbol-function is split into the plain definition plus the
  ;; list of advice; this returns the advice part (or the pending advice stashed
  ;; on `advice--pending' while the definition is nil/an autoload).
  (or (get symbol 'advice--pending)
      (advice--strip-macro (symbol-function symbol))))

(defun advice--defalias-fset (fsetfun symbol newdef)
  (unless fsetfun (setq fsetfun #'fset))
  ;; `newdef' shouldn't include advice wrappers, since that's what *we* manage.
  (cond
   ((advice--p newdef) (setq newdef (advice--cd*r newdef)))
   ((and (eq 'macro (car-safe newdef))
         (advice--p (cdr newdef)))
    (setq newdef `(macro . ,(advice--cd*r (cdr newdef))))))
  (when (get symbol 'advice--saved-rewrite)
    (put symbol 'advice--saved-rewrite nil))
  (setq newdef (advice--normalize symbol newdef))
  (let ((oldadv (advice--symbol-function symbol)))
    (if (and newdef (not (autoloadp newdef)))
        (let* ((snewdef (advice--strip-macro newdef))
               (snewadv (advice--subst-main oldadv snewdef)))
          (put symbol 'advice--pending nil)
          (funcall fsetfun symbol
                   (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))
      (unless (eq oldadv (get symbol 'advice--pending))
        (put symbol 'advice--pending (advice--subst-main oldadv nil)))
      (funcall fsetfun symbol newdef))))

(defun advice-add (symbol how function &optional props)
  "Like `add-function' but for the function named SYMBOL.
Handles the cases where SYMBOL is defined as a macro, alias, command, ..."
  (let* ((f (symbol-function symbol))
	 (nf (advice--normalize symbol f)))
    (unless (eq f nf) (fset symbol nf))
    (add-function how (cond
                       ((eq (car-safe nf) 'macro) (cdr nf))
                       ((or (not nf) (autoloadp nf))
                        (get symbol 'advice--pending))
                       (t (symbol-function symbol)))
                  function props)
    (add-function :around (get symbol 'defalias-fset-function)
                  #'advice--defalias-fset))
  nil)

(defun advice-remove (symbol function)
  "Like `remove-function' but for the function named SYMBOL.
Works when SYMBOL is a macro or an autoload and preserves `fboundp'.
FUNCTION can also be the `name' of the piece of advice."
  (let ((f (symbol-function symbol)))
    (remove-function (cond ;This is `advice--symbol-function' but as a "place".
                      ((get symbol 'advice--pending)
                       (get symbol 'advice--pending))
                      ((eq (car-safe f) 'macro) (cdr f))
                      (t (symbol-function symbol)))
                     function)
    (unless (advice--p (advice--symbol-function symbol))
      (remove-function (get symbol 'defalias-fset-function)
                       #'advice--defalias-fset)
      (let ((asr (get symbol 'advice--saved-rewrite)))
        (and asr (eq (cdr-safe (symbol-function symbol))
                     (cdr asr))
             (fset symbol (car (get symbol 'advice--saved-rewrite)))))))
  nil)

(defmacro define-advice (symbol args &rest body)
  "Define an advice and add it to function named SYMBOL.
See `advice-add' and `add-function'.  If NAME is non-nil, the advice is
named `SYMBOL@NAME' and installed with the name NAME; else it is anonymous.

\(fn SYMBOL (HOW LAMBDA-LIST &optional NAME DEPTH) &rest BODY)"
  (declare (indent 2) (doc-string 3) (debug (sexp sexp def-body)))
  (or (listp args) (signal 'wrong-type-argument (list 'listp args)))
  (or (<= 2 (length args) 4)
      (signal 'wrong-number-of-arguments (list 2 4 (length args))))
  (let* ((how           (nth 0 args))
         (lambda-list   (nth 1 args))
         (name          (nth 2 args))
         (depth         (nth 3 args))
         (props         (append
                         (and depth `((depth . ,depth)))
                         (and name `((name . ,name)))))
         (advice (cond ((null name) `(lambda ,lambda-list ,@body))
                       ((or (stringp name) (symbolp name))
                        (intern (format "%s@%s" symbol name)))
                       (t (error "Unrecognized name spec `%S'" name)))))
    `(prog1 ,@(and (symbolp advice) `((defun ,advice ,lambda-list ,@body)))
       (advice-add ',symbol ,how #',advice ,@(and props `(',props))))))

(defun advice-mapc (fun symbol)
  "Apply FUN to every advice function in SYMBOL.
FUN is called with two arguments: the added function and its props alist."
  (advice-function-mapc fun (advice--symbol-function symbol)))

(defun advice-member-p (advice symbol)
  "Return non-nil if ADVICE has been added to SYMBOL.
ADVICE can also be the `name' of the piece of advice."
  (advice-function-member-p advice (advice--symbol-function symbol)))

(provide 'nadvice)
"##;