File: modes.c

package info (click to toggle)
vile 9.6m-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 8,196 kB
  • ctags: 8,459
  • sloc: ansic: 90,876; lex: 9,514; sh: 3,223; cpp: 3,137; perl: 2,928; makefile: 785; awk: 276
file content (4989 lines) | stat: -rw-r--r-- 112,412 bytes parent folder | download
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
/*
 *	modes.c
 *
 * Maintain and list the editor modes and value sets.
 *
 * Original code probably by Dan Lawrence or Dave Conroy for MicroEMACS.
 * Major extensions for vile by Paul Fox, 1991
 * Majormode extensions for vile by T.E.Dickey, 1997
 *
 * $Header: /usr/build/vile/vile/RCS/modes.c,v 1.362 2008/05/06 00:01:25 tom Exp $
 *
 */

#include <estruct.h>
#include <edef.h>
#include <blist.h>
#include <chgdfunc.h>
#include <nefsms.h>

#define	ONE_COL	(80/3)

#define isLocalVal(valptr)          ((valptr)->vp == &((valptr)->v))
#define makeLocalVal(valptr)        ((valptr)->vp = &((valptr)->v))

#define MAJOR_SUFFIX	"mode"
#define NO_PREFIX	"no"
#define noPrefix(mode)	(!strncmp(mode, NO_PREFIX, 2))

/*--------------------------------------------------------------------------*/

#if OPT_UPBUFF
static void relist_settings(void);
#else
#define relist_settings()	/* nothing */
#endif

#if OPT_ENUM_MODES
static int fsm_idx;
static FSM_BLIST *valname_to_choices(const struct VALNAMES *names);
#endif

/*--------------------------------------------------------------------------*/

#if OPT_EVAL || OPT_MAJORMODE
static size_t size_my_varmodes;
static char **my_varmodes;	/* list for modename-completion */
#endif

#if OPT_MAJORMODE
typedef struct {
    char *shortname;		/* copy of MAJORMODE.shortname */
    char *longname;		/* copy of MAJORMODE.longname */
    MAJORMODE *data;		/* pointer to actual data */
    int init;			/* predefined during initialization */
    int flag;			/* true when majormode is active/usable */
    struct VALNAMES qual[MAX_M_VALUES + 1];	/* majormode qualifier names */
    struct VALNAMES used[MAX_B_VALUES + 1];	/* submode names */
    struct VALNAMES subq[MAX_Q_VALUES + 1];	/* submode qualifier names */
} MAJORMODE_LIST;

static MAJORMODE_LIST *my_majormodes;
static MAJORMODE_LIST no_majormodes[1];
static BLIST majormode_blist = init_blist(no_majormodes);

static int *majormodes_order;	/* index, for precedence */
static M_VALUES global_m_values;	/* dummy, for convenience */
static struct VAL *major_g_vals;	/* on/off values of major modes */
static struct VAL *major_l_vals;	/* dummy, for convenience */
static struct VALNAMES *major_valnames;

static int did_attach_mmode;

static const char **my_mode_list = 0;	/* copy of 'all_modes[]' */

#define is_bool_type(type) ((type) == VALTYPE_BOOL || (type) == VALTYPE_MAJOR)

static MAJORMODE_LIST *lookup_mm_list(const char *name);
static char *majorname(char *dst, const char *majr, int flag);
static const char *ModeName(const char *name);
static int attach_mmode(BUFFER *bp, const char *name);
static int detach_mmode(BUFFER *bp, const char *name);
static int enable_mmode(const char *name, int flag);
static struct VAL *get_sm_vals(MAJORMODE * ptr);
static void init_my_mode_list(void);

#if OPT_UPBUFF
static void relist_majormodes(void);
#endif

#else

#define ModeName(s) s
#define init_my_mode_list()	/* nothing */
#define is_bool_type(type) ((type) == VALTYPE_BOOL)
#define my_mode_list all_modes
#define relist_majormodes()	/* nothing */

#endif /* OPT_MAJORMODE */

#define is_str_type(type) ((type) == VALTYPE_REGEX || (type) == VALTYPE_STRING)

static BLIST blist_my_mode_list = init_blist(all_modes);

/*--------------------------------------------------------------------------*/

#if OPT_ENUM_MODES || !SMALLER
int
choice_to_code(FSM_BLIST * data, const char *name, size_t len)
{
    const FSM_CHOICES *choices = data->choices;
    char temp[NSTRING];
    int code = ENUM_ILLEGAL;
    int i;

    if (choices != 0 && name != 0 && len != 0) {
	if (len > NSTRING - 1)
	    len = NSTRING - 1;

	memcpy(temp, name, len);
	temp[len] = EOS;
	(void) mklower(temp);

	if ((i = blist_pmatch(&(data->blist), temp, len)) >= 0) {
	    code = choices[i].choice_code;
	}
    }
    return code;
}

const char *
choice_to_name(FSM_BLIST * data, int code)
{
    const FSM_CHOICES *choices = data->choices;
    const char *name = 0;
    int i;

    if (choices == 0) {
	name = "";
    } else {
	for (i = 0; choices[i].choice_name != 0; i++) {
	    if (choices[i].choice_code == code) {
		name = choices[i].choice_name;
		break;
	    }
	}
    }
    return name;
}
#endif /* OPT_ENUM_MODES || !SMALLER */

#if !SMALLER
/*
 * Add the values from one or more keywords.  If any error is found, return that
 * code instead.
 */
int
combine_choices(FSM_BLIST * choices, const char *string)
{
    char temp[NSTRING];
    const char *s;
    int code;
    int result = 0;

    while (*string) {
	vl_strncpy(temp, string, sizeof(temp));
	if ((s = strchr(string, '+')) != 0) {
	    temp[s - string] = EOS;
	    string = s + 1;
	} else {
	    string += strlen(string);
	}
	if ((code = choice_to_code(choices, temp, strlen(temp))) >= 0) {
	    result += code;
	} else {
	    result = code;
	    break;
	}
    }
    return result;
}
#endif

/*--------------------------------------------------------------------------*/

/*
 * Update window-flags applying to the current buffer when we modify a window
 * property, or something that requires repainting a window.
 */
void
set_bufflags(int glob_vals, USHORT flags)
{
    if (glob_vals) {
	set_winflags(glob_vals, flags);
    } else {
	WINDOW *wp;
	for_each_visible_window(wp) {
	    if (wp->w_bufp == curbp)
		wp->w_flag |= flags;
	}
    }
}

/*
 * Update window-flags when we modify a window property, or something that
 * requires repainting all (or the current if local) windows.
 */
void
set_winflags(int glob_vals, USHORT flags)
{
    if (glob_vals) {
	WINDOW *wp;
	for_each_visible_window(wp) {
	    if ((wp->w_bufp == NULL)
		|| !b_is_scratch(wp->w_bufp)
		|| !(flags & WFMODE))
		wp->w_flag |= flags;
	}
    } else {
	curwp->w_flag |= flags;
    }
}

static int
same_val(const struct VALNAMES *names, struct VAL *tst, struct VAL *ref)
{
    if (ref == 0)		/* can't test, not really true */
	return -TRUE;

    switch (names->type) {
#if OPT_MAJORMODE
    case VALTYPE_MAJOR:
	/*FALLTHRU */
#endif
    case VALTYPE_BOOL:
    case VALTYPE_ENUM:
    case VALTYPE_INT:
	return (tst->vp->i == ref->vp->i);
    case VALTYPE_STRING:
	return (tst->vp->p != 0)
	    && (ref->vp->p != 0)
	    && !strcmp(tst->vp->p, ref->vp->p);
    case VALTYPE_REGEX:
	return (tst->vp->r != 0)
	    && (ref->vp->r != 0)
	    && (tst->vp->r->pat != 0)
	    && (ref->vp->r->pat != 0)
	    && !strcmp(tst->vp->r->pat, ref->vp->r->pat);
    default:
	mlforce("BUG: bad type %s %d", ModeName(names->name), names->type);
    }

    return FALSE;
}

/*
 * Returns the value if it is a string, null otherwise.
 */
static const char *
string_val(const struct VALNAMES *names, struct VAL *values)
{
    const char *s = 0;

    switch (names->type) {
#if OPT_ENUM_MODES		/* will show the enum name too */
    case VALTYPE_ENUM:
	s = choice_to_name(valname_to_choices(names), values->vp->i);
	break;
#endif
    case VALTYPE_STRING:
	s = values->vp->p;
	break;
    case VALTYPE_REGEX:
	if (values->vp->r)
	    s = values->vp->r->pat;
	break;
    }

    return isEmpty(s) ? 0 : s;
}

/*
 * Returns the formatted length of a string value.
 */
static size_t
size_val(const struct VALNAMES *names, struct VAL *values)
{
    return strlen(ModeName(names->name))
	+ 3
	+ strlen(NonNull(string_val(names, values)));
}

/*
 * Returns a mode-value formatted as a string
 */
const char *
string_mode_val(VALARGS * args)
{
    const struct VALNAMES *names = args->names;
    struct VAL *values = args->local;
    union V *actual = values->vp ? values->vp : &(values->v);
    static TBUFF *result;

    if (values != 0) {
	switch (names->type) {
#if OPT_MAJORMODE
	case VALTYPE_MAJOR:
#endif
	case VALTYPE_BOOL:
	    return actual->i ? "TRUE" : "FALSE";
	case VALTYPE_ENUM:
#if OPT_ENUM_MODES
	    {
		static TBUFF *temp = 0;		/* const workaround */
		(void) tb_scopy(&temp,
				choice_to_name(valname_to_choices(names),
					       actual->i));
		return tb_values(temp);
	    }
#endif /* else, fall-thru to use int-code */
	case VALTYPE_INT:
	    return render_int(&result, actual->i);
	case VALTYPE_STRING:
	    return NonNull(actual->p);
	case VALTYPE_REGEX:
	    if (actual->r == 0)
		break;
	    return NonNull(actual->r->pat);
	}
    }
    return error_val;
}

/* listvalueset:  print each value in the array according to type, along with
 * its name, until a NULL name is encountered.  If not local, only print if the value in the
 * two arrays differs, or the second array is nil.  If local, print only the
 * values in the first array that are local.
 */
static int
listvalueset(const char *which,
	     int nflag,
	     int local,
	     const struct VALNAMES *names,
	     struct VAL *values,
	     struct VAL *globvalues)
{
    int show[MAX_G_VALUES + MAX_B_VALUES + MAX_W_VALUES];
    int any = 0;
    int passes = 1;
    int ncols = term.cols / ONE_COL;
    int padded;
    int perline;
    int percol;
    int total;
    int j, pass;

    if (ncols > MAXCOLS)
	ncols = MAXCOLS;

    /*
     * First, make a list of values we want to show.
     * Store:
     *      0 - don't show
     *      1 - show in first pass
     *      2 - show in second pass (too long)
     */
    for (j = 0; names[j].name != 0; j++) {
	int ok;
	show[j] = 0;
	if (local) {
	    ok = is_local_val(values, j);
	} else {
	    ok = (same_val(names + j, values + j, globvalues ? globvalues +
			   j : 0) != TRUE);
	}
	if (ok) {
	    switch (names[j].type) {
	    case VALTYPE_ENUM:
	    case VALTYPE_STRING:
	    case VALTYPE_REGEX:
		if (string_val(names + j, values + j) == 0) {
		    ok = FALSE;
		    break;
		}
		if (size_val(names + j, values + j) >= ONE_COL) {
		    show[j] += 1;
		    passes = 2;
		}
		/* fall-thru */
	    default:
		show[j] += 1;
	    }
	}
	if (ok && !any++) {
	    if (nflag)
		bputc('\n');
	    bprintf("%s:\n", which);
	}
    }
    total = j;

    if (any) {
	if (!passes)
	    passes = 1;
    } else
	return nflag;

    /*
     * Now, go back and display the values
     */
    for (pass = 1; pass <= passes; pass++) {
	int line, col, k;
	int offsets[MAXCOLS + 1];

	offsets[0] = 0;
	if (pass == 1) {
	    for (j = percol = 0; j < total; j++) {
		if (show[j] == pass)
		    percol++;
	    }
	    for (j = 1; j < ncols; j++) {
		offsets[j]
		    = (percol + ncols - j) / ncols
		    + offsets[j - 1];
	    }
	    perline = ncols;
	} else {		/* these are too wide for ONE_COL */
	    offsets[1] = total;
	    perline = 1;
	}
	offsets[ncols] = total;

	line = 0;
	col = 0;
	any = 0;
	for_ever {
	    k = line + offsets[col];
	    for (j = 0; j < total; j++) {
		if (show[j] == pass) {
		    if (k-- <= 0)
			break;
		}
	    }
	    if (k >= 0)		/* no more cells to display */
		break;

	    if (col == 0)
		bputc(' ');
	    padded = DOT.o + ((col + 1) < perline ? ONE_COL : 1);
	    if (is_bool_type(names[j].type)) {
		bprintf("%s%s",
			values[j].vp->i ? "  " : NO_PREFIX,
			ModeName(names[j].name));
	    } else {
		VALARGS args;	/* FIXME */
		args.names = names + j;
		args.local = values + j;
		args.global = 0;
		bprintf("  %s=%s",
			ModeName(names[j].name),
			string_mode_val(&args));
	    }
	    bpadc(' ', padded - DOT.o);
	    any++;
	    if (++col >= perline) {
		col = 0;
		bputc('\n');
		if (++line >= offsets[1])
		    break;
	    } else if (line + offsets[col] >= offsets[col + 1])
		break;
	}
	if (any && (pass != passes))
	    bputc('\n');
	if (col != 0)
	    bputc('\n');
    }
    return TRUE;
}

#ifdef lint
static /*ARGSUSED */ WINDOW *
ptr2WINDOW(void *p)
{
    return 0;
}
#else
#define	ptr2WINDOW(p)	(WINDOW *)p
#endif

/* list the current modes into the current buffer */
/* ARGSUSED */
static void
makemodelist(int local, void *ptr)
{
    static const char gg[] = "Universal";
    static const char bb[] = "Buffer";
    static const char ww[] = "Window";
    int nflag, nflg2;

#if OPT_ENUM_MODES
    int save_fsm_idx = fsm_idx;
#endif
    WINDOW *localwp = ptr2WINDOW(ptr);	/* alignment okay */
    BUFFER *localbp = localwp->w_bufp;
    struct VAL *local_b_vals = localbp->b_values.bv;
    struct VAL *local_w_vals = localwp->w_values.wv;
    struct VAL *globl_b_vals = global_b_values.bv;

#if OPT_UPBUFF
    if (relisting_b_vals != 0)
	local_b_vals = relisting_b_vals;
    if (relisting_w_vals != 0)
	local_w_vals = relisting_w_vals;
#endif

#if OPT_MAJORMODE
    if (local && (localbp->majr != 0)) {
	bprintf("--- \"%s\" settings, if different than \"%s\" majormode ",
		localbp->b_bname,
		localbp->majr->shortname);
	globl_b_vals = get_sm_vals(localbp->majr);
    } else
#endif
	bprintf("--- \"%s\" settings, if different than globals ",
		localbp->b_bname);
    bpadc('-', term.cols - DOT.o);
    bputc('\n');

    nflag = listvalueset(bb, FALSE, FALSE, b_valnames, local_b_vals, globl_b_vals);
    nflg2 = listvalueset(ww, nflag, FALSE, w_valnames, local_w_vals, global_w_values.wv);
    if (!(nflag || nflg2))
	bputc('\n');
    bputc('\n');

    bprintf("--- %s settings ", local ? "Local" : "Global");
    bpadc('-', term.cols - DOT.o);
    bputc('\n');

    if (local) {
	nflag = listvalueset(bb, nflag, local, b_valnames, local_b_vals,
			     (struct VAL *) 0);
	(void) listvalueset(ww, nflag, local, w_valnames, local_w_vals,
			    (struct VAL *) 0);
    } else {
	nflag = listvalueset(gg, nflag, local, g_valnames,
			     global_g_values.gv, (struct VAL *) 0);
	nflag = listvalueset(bb, nflag, local, b_valnames, globl_b_vals,
			     (struct VAL *) 0);
	(void) listvalueset(ww, nflag, local, w_valnames,
			    global_w_values.wv, (struct VAL *) 0);
    }
#if OPT_ENUM_MODES
    fsm_idx = save_fsm_idx;
#endif
}

/*
 * Set tab size
 */
int
settab(int f, int n)
{
    WINDOW *wp;
#if OPT_MAJORMODE
    int val = VAL_TAB;
    const char *whichtabs = "T";
#else
    int val;
    const char *whichtabs;
    if (is_c_mode(curbp)) {
	val = VAL_C_TAB;
	whichtabs = "C-t";
    } else {
	val = VAL_TAB;
	whichtabs = "T";
    }
#endif
    if (f && n >= 1) {
	make_local_b_val(curbp, val);
	set_b_val(curbp, val, n);
	for_each_visible_window(wp) {
	    if (wp->w_bufp == curbp)
		wp->w_flag |= WFHARD;
	}
    } else if (f) {
	mlwarn("[Illegal tabstop value]");
	return FALSE;
    }
    if (!global_b_val(MDTERSE) || !f)
	mlwrite("[%sabs are %d columns apart, using %s value.]", whichtabs,
		tabstop_val(curbp),
		is_local_b_val(curbp, val) ? "local" : "global");
    return TRUE;
}

/*
 * Set fill column to n.
 */
int
setfillcol(int f, int n)
{
    if (f) {
	make_local_b_val(curbp, VAL_FILL);
	set_b_val(curbp, VAL_FILL, n);
    }
    if (!global_b_val(MDTERSE) || !f)
	mlwrite("[Fill column is %d, and is %s]",
		getfillcol(curbp),
		is_local_b_val(curbp, VAL_FILL) ? "local" : "global");
    return (TRUE);
}

/*
 * Returns the effective fill-column
 */
int
getfillcol(BUFFER *bp)
{
    int result = b_val(bp, VAL_FILL);
    if (result == 0) {
	result = term.cols - b_val(bp, VAL_WRAPMARGIN);
    } else if (result < 0) {
	result = term.cols + result;
    }
    return (result);
}

/*
 * Release storage of a REGEXVAL struct
 */
REGEXVAL *
free_regexval(REGEXVAL * rp)
{
    if (rp != 0) {
	beginDisplay();
	FreeAndNull(rp->pat);
	FreeAndNull(rp->reg);
	free((char *) rp);
	endofDisplay();
    }
    return 0;
}

/*
 * Allocate/set a new REGEXVAL struct
 */
REGEXVAL *
new_regexval(const char *pattern, int magic)
{
    REGEXVAL *rp = 0;

    if (pattern != 0) {
	beginDisplay();
	if ((rp = typecalloc(REGEXVAL)) != 0) {
	    if ((rp->pat = strmalloc(pattern)) == 0
		|| (rp->reg = regcomp(rp->pat, strlen(rp->pat), magic)) == 0)
		rp = free_regexval(rp);
	}
	endofDisplay();
    }

    return rp;
}

/*
 * Release storage of a VAL struct
 */
void
free_val(const struct VALNAMES *names, struct VAL *values)
{
    switch (names->type) {
    case VALTYPE_STRING:
	beginDisplay();
	FreeAndNull(values->v.p);
	endofDisplay();
	break;
    case VALTYPE_REGEX:
	values->v.r = free_regexval(values->v.r);
	break;
    default:			/* nothing to free */
	break;
    }
}

/*
 * Copy a VAL-struct, preserving the sense of local/global.
 */
static int
copy_val(struct VAL *dst, struct VAL *src)
{
    int local = isLocalVal(src);

    *dst = *src;
    if (local)
	makeLocalVal(dst);
    return local;
}

void
copy_mvals(int maximum,
	   struct VAL *dst,
	   struct VAL *src)
{
    int n;
    for (n = 0; n < maximum; n++)
	(void) copy_val(&dst[n], &src[n]);
}

/*
 * This is a special routine designed to save the values of local modes and to
 * restore them.  The 'recompute_buffer()' procedure assumes that global modes
 * do not change during the recomputation process (so there is no point in
 * trying to convert any of those values to local ones).
 */
#if OPT_UPBUFF
void
save_vals(int maximum,
	  struct VAL *gbl,
	  struct VAL *dst,
	  struct VAL *src)
{
    int n;
    for (n = 0; n < maximum; n++)
	if (copy_val(&dst[n], &src[n]))
	    make_global_val(src, gbl, n);
}
#endif

/*
 * free storage used by local mode-values, called only when we are freeing
 * all other storage associated with a buffer or window.
 */
void
free_local_vals(const struct VALNAMES *names,
		struct VAL *gbl,
		struct VAL *val)
{
    int j;

    for (j = 0; names[j].name != 0; j++) {
	if (is_local_val(val, j)) {
	    make_global_val(val, gbl, j);
	    free_val(names + j, val + j);
	}
    }
}

/*
 * Convert a string to boolean, checking for errors
 */
static int
string_to_bool(const char *base, int *np)
{
    if (is_truem(base))
	*np = TRUE;
    else if (is_falsem(base))
	*np = FALSE;
    else {
	mlforce("[Not a boolean: '%s']", base);
	return FALSE;
    }
    return TRUE;
}

/*
 * Convert a string to number, checking for errors
 */
int
string_to_number(const char *from, int *np)
{
    long n;
    char *p;

    /* accept decimal, octal, or hex */
    n = strtol(from, &p, 0);
    if (p == from || *p != EOS) {
	mlforce("[Not a number: '%s']", from);
	return FALSE;
    }
    *np = (int) n;
    return TRUE;
}

/*
 * Validate a 'glob' mode-value.  It is either a boolean, or it must be a
 * pipe-expression with exactly one "%s" embedded (no other % characters,
 * unless escaped).  That way, we can use the string to format the pipe
 * command.
 */
#if defined(GMD_GLOB) || defined(GVAL_GLOB)
static int
legal_glob_mode(const char *base)
{
#ifdef GVAL_GLOB		/* string */
    if (isShellOrPipe(base)) {
	const char *s = base;
	int count = 0;
	while (*s != EOS) {
	    if (*s == '%') {
		if (*++s != '%') {
		    if (*s == 's')
			count++;
		    else
			count = 2;
		}
	    }
	    if (*s != EOS)
		s++;
	}
	if (count == 1)
	    return TRUE;
    }
#endif
    if (is_truem(base)
	|| is_falsem(base))
	return TRUE;

    mlforce("[Illegal value for glob: '%s']", base);
    return FALSE;
}
#endif

/*
 * FSM stands for fixed string mode, so called because the strings which the
 * user is permitted to enter are non-arbitrary (fixed).
 *
 * It is meant to handle the following sorts of things:
 *
 *	:set popup-choices off
 *	:set popup-choices immediate
 *	:set popup-choices delayed
 *
 *	:set error quiet
 *	:set error beep
 *	:set error flash
 */
#if OPT_ENUM_MODES

#if VILE_NEVER
FSM_CHOICES fsm_error[] =
{
    {"beep", 1},
    {"flash", 2},
    {"quiet", 0},
    END_CHOICES
};
#endif

#if OPT_COLOR_CHOICES
static const char s_fcolor[] = "fcolor";
static const char s_bcolor[] = "bcolor";
static const char s_ccolor[] = "ccolor";
#endif

#if OPT_COLOR_SCHEMES
static const char s_default[] = "default";
static const char s_color_scheme[] = "color-scheme";
static const char s_palette[] = "palette";
static const char s_video_attrs[] = "video-attrs";
static const
FSM_CHOICES fsm_no_choices[] =
{
    {s_default, 0},
    END_CHOICES			/* ends table for name-completion */
};
static FSM_BLIST fsm_no_blist =
{
    fsm_no_choices,
    init_blist(fsm_no_choices)
};
#endif /* OPT_COLOR_SCHEMES */

static const FSM_TABLE fsm_tbl[] =
{
    {"*bool", &fsm_bool_blist},
#if OPT_COLOR_SCHEMES
    {s_color_scheme, &fsm_no_blist},
#endif
#if OPT_COLOR_CHOICES
    {s_fcolor, &fsm_color_blist},
    {s_bcolor, &fsm_color_blist},
    {s_ccolor, &fsm_color_blist},
#endif
#if OPT_CURTOKENS_CHOICES
    {"cursor-tokens", &fsm_curtokens_blist},
#endif
#if OPT_POPUP_CHOICES
    {"popup-choices", &fsm_popup_blist},
#endif
#if VILE_NEVER
    {"error", &fsm_error},
#endif
#if OPT_BACKUP_CHOICES
    {"backup-style", &fsm_backup_blist},
#endif
#if OPT_COLOR
    {s_video_attrs, &fsm_videoattrs_blist},
#endif
#if OPT_FORBUFFERS_CHOICES
    {"for-buffers", &fsm_forbuffers_blist},
#endif
#if OPT_HILITE_CHOICES
    {"mcolor", &fsm_hilite_blist},
    {"visual-matches", &fsm_hilite_blist},
    {"mini-hilite", &fsm_hilite_blist},
#endif
#if OPT_MULTIBYTE
    {"byteorder-mark", &fsm_byteorder_mark_blist},
    {"file-encoding", &fsm_file_encoding_blist},
#endif
#if OPT_VTFLASHSEQ_CHOICES
    {"vtflash", &fsm_vtflashseq_blist},
#endif
#if SYS_VMS
    {"record-format", &fsm_recordformat_blist},
    {"record-attrs", &fsm_recordattrs_blist},
#endif
#if OPT_READERPOLICY_CHOICES
    {"reader-policy", &fsm_readerpolicy_blist},
#endif
#if OPT_RECORDSEP_CHOICES
    {"recordseparator", &fsm_recordsep_blist},
#endif
#if OPT_SHOWFORMAT_CHOICES
    {"showformat", &fsm_showformat_blist},
#endif
#if OPT_MMQUALIFIERS_CHOICES
    {"qualifiers", &fsm_mmqualifiers_blist},
#endif
};

static size_t
fsm_size(const FSM_CHOICES * list)
{
    size_t result = 0;
    while ((list++)->choice_name != 0)
	result++;
    return result;
}

FSM_BLIST *
name_to_choices(const char *name)
{
    int i;
    FSM_BLIST *result = 0;

    fsm_idx = -1;
    for (i = 1; i < (int) TABLESIZE(fsm_tbl); i++) {
	if (strcmp(fsm_tbl[i].mode_name, name) == 0) {
	    fsm_idx = i;
	    result = fsm_tbl[i].lists;
	    break;
	}
    }
    return result;
}

static FSM_BLIST *
valname_to_choices(const struct VALNAMES *names)
{
    return name_to_choices(names->name);
}

static int
is_fsm(const struct VALNAMES *names)
{
    size_t i;

    if (names->type == VALTYPE_ENUM
	|| names->type == VALTYPE_STRING) {
	for (i = 1; i < TABLESIZE(fsm_tbl); i++) {
	    if (strcmp(fsm_tbl[i].mode_name, names->name) == 0) {
		fsm_idx = (int) i;
		return TRUE;
	    }
	}
    } else if (is_bool_type(names->type)) {
	fsm_idx = 0;
	return TRUE;
    }
    fsm_idx = -1;
    return FALSE;
}

/*
 * Silently check if the string forms a number, to work with checks for FSM's
 * that allow numbers instead of names.
 */
static int
legal_number(const char *val)
{
    int failed;
    (void) vl_atol(val, 0, &failed);
    return (failed == 0);
}

/*
 * Test if we're processing an enum-valued mode.  If so, lookup the mode value.
 * We'll allow a numeric index also (e.g., for colors).  Note that we're
 * returning the table-value in that case, so we'll have to ensure that we
 * don't corrupt the table.
 */
static const char *
legal_fsm(const char *val)
{
    if (fsm_idx >= 0) {
	int i;
	int idx = fsm_idx;
	FSM_BLIST *p = fsm_tbl[idx].lists;
	const char *s;
	int failed = FALSE;

	if (isDigit(*val) && legal_number(val)) {
	    if (string_to_number(val, &i)
		&& (s = choice_to_name(p, i)) != 0) {
		val = s;
	    } else {
		failed = TRUE;
	    }
	} else {
	    if (choice_to_code(p, val, strlen(val)) == ENUM_ILLEGAL) {
		failed = TRUE;
	    }
	}
	if (failed) {
	    mlforce("[Illegal value for %s: '%s']",
		    fsm_tbl[idx].mode_name,
		    val);
	    val = 0;
	}
    }
    return val;
}

int
fsm_complete(DONE_ARGS)
{
    int result = FALSE;

    if (buf != 0) {
	if (isDigit(*buf)) {	/* allow numbers for colors */
	    if (c != NAMEC && c != TESTC) {
		/* put it back (cf: kbd_complete) */
		unkeystroke(c);
		result = isSpace(c);
	    }
	}
	if (!result) {
	    result = kbd_complete(PASS_DONE_ARGS,
				  (const char *) (fsm_tbl[fsm_idx].lists->choices),
				  sizeof(FSM_CHOICES));
	}
    }
    return result;
}
#endif /* OPT_ENUM_MODES */

static int
ok_local_mode(void)
{
#if OPT_MODELINE
    /*
     * When processing modeline, disallow major changes.
     */
    if (in_modeline) {
	TRACE(("ignored (within modeline)\n"));
	return FALSE;
    }
#endif
    return TRUE;
}

/*
 * Lookup the mode named with 'cp[]' and adjust its value.
 */
int
adjvalueset(const char *cp,	/* name of the mode we are changing */
	    int defining,	/* for majormodes, suppress side_effect */
	    int setting,	/* true if setting, false if unsetting */
	    int global,
	    VALARGS * args)
{				/* symbol-table entry for the mode */
    const struct VALNAMES *names = args->names;
    struct VAL *values = args->local;
    struct VAL *globls = args->global;

    char prompt[NLINE];
    char respbuf[NFILEN];
    int no;
    const char *rp = NULL;
    int status;

    if (isEmpty(cp))
	return FALSE;

    no = noPrefix(cp);
    if (no && !is_bool_type(names->type))
	return FALSE;		/* this shouldn't happen */

    if ((names->side_effect == chgd_major) && !ok_local_mode()) {
	return FALSE;
    }

    /*
     * Check if we're allowed to change this mode in the current context.
     */
    if (!defining
	&& (names->side_effect != 0)
	&& !(*(names->side_effect)) (curbp, args, (values == globls), TRUE)) {
	return FALSE;
    }

    /* get a value if we need one */
    if ((end_string() == '=')
	|| (!is_bool_type(names->type) && setting)) {
	int regex = (names->type == VALTYPE_REGEX);
	KBD_OPTIONS opts = regex ? 0 : KBD_NORMAL;
	int eolchar = is_str_type(names->type) ? '\n' : ' ';
	int (*complete) (DONE_ARGS) = no_completion;

	respbuf[0] = EOS;
	(void) lsprintf(prompt, "New %s %s: ",
			names->name ? names->name : cp,
			regex ? "pattern" : "value");

#if OPT_ENUM_MODES
	if (is_fsm(names)) {
	    complete = fsm_complete;
	    opts |= KBD_LOWERC;
	}
#endif

	status = kbd_string(prompt, respbuf, sizeof(respbuf), eolchar,
			    opts, complete);
	if (status != TRUE)
	    return status;

	/*
	 * Allow an empty response to a string-value if we're running in a
	 * macro rather than interactively.
	 */
	if (!strlen(rp = respbuf)
	    && !clexec) {
	    switch (names->type) {
	    case VALTYPE_REGEX:	/* FALLTHRU */
	    case VALTYPE_STRING:
		break;
	    default:
		return FALSE;
	    }
	}
    } else if (!setting) {
	rp = is_str_type(names->type) ? "" : "0";
    }
#if OPT_HISTORY
    else
	hst_glue(' ');
#endif
    status = set_mode_value(curbp, cp, defining, setting, global, args, rp);
    TRACE(("...adjvalueset(%s)=%d\n", cp, status));

    return status;
}

int
set_mode_value(BUFFER *bp,
	       const char *cp,
	       int defining,
	       int setting,
	       int global,
	       VALARGS * args,
	       const char *rp)
{
    const struct VALNAMES *names = args->names;
    struct VAL *values = args->local;
    struct VAL *globls = args->global;
    REGEXVAL *r;

    struct VAL oldvalue;
    int no = noPrefix(cp);
    int nval, status;
    int unsetting = !setting && !global;
    int changed = FALSE;

    /*
     * Check if we're allowed to change this mode in the current context.
     */
    if (!defining
	&& (names->side_effect != 0)
	&& !(*(names->side_effect)) (bp, args, (values == globls), TRUE)) {
	return FALSE;
    }

    if (rp == NULL) {
	rp = no ? cp + 2 : cp;
    } else {
	if (no && !is_bool_type(names->type))
	    return FALSE;	/* this shouldn't happen */

#if defined(GMD_GLOB) || defined(GVAL_GLOB)
	if (!strcmp(names->name, "glob")
	    && !legal_glob_mode(rp))
	    return FALSE;
#endif
#if OPT_ENUM_MODES
	(void) is_fsm(names);	/* evaluated for its side effects */
	if ((rp = legal_fsm(rp)) == 0)
	    return FALSE;
#endif
	/* Test after fsm, to allow translation */
	if (is_bool_type(names->type)) {
	    if (!string_to_bool(rp, &setting))
		return FALSE;
	}
    }

    /* save, to simplify no-change testing */
    (void) copy_val(&oldvalue, values);

    if (unsetting) {
	make_global_val(values, globls, 0);
#if OPT_MAJORMODE
	switch (names->type) {
	case VALTYPE_MAJOR:
	    if (values == globls)
		changed = enable_mmode(names->shortname, FALSE);
	    else
		changed = detach_mmode(bp, names->shortname);
	    break;
	}
#endif
    } else {
	makeLocalVal(values);	/* make sure we point to result! */

	/* we matched a name -- set the value */
	switch (names->type) {
#if OPT_MAJORMODE
	case VALTYPE_MAJOR:
	    values->vp->i = no ? !setting : setting;
	    if (values == globls) {
		changed = enable_mmode(names->shortname, values->vp->i);
	    } else {
		changed = no
		    ? detach_mmode(bp, names->shortname)
		    : attach_mmode(bp, names->shortname);
		if (changed)
		    did_attach_mmode = TRUE;
	    }
	    break;
#endif
	case VALTYPE_BOOL:
	    values->vp->i = no ? !setting : setting;
	    break;

	case VALTYPE_ENUM:
#if OPT_ENUM_MODES
	    {
		FSM_BLIST *fp = valname_to_choices(names);

		if (legal_number(rp)) {
		    if (!string_to_number(rp, &nval))
			return FALSE;
		    if (choice_to_name(fp, nval) == 0)
			nval = ENUM_ILLEGAL;
		} else {
		    nval = choice_to_code(fp, rp, strlen(rp));
		}
		if (nval == ENUM_ILLEGAL) {
		    mlforce("[Not a legal enum-index: %s]",
			    rp);
		    return FALSE;
		}
	    }
	    values->vp->i = nval;
	    break;
#endif /* OPT_ENUM_MODES */

	case VALTYPE_INT:
	    if (!string_to_number(rp, &nval))
		return FALSE;
	    values->vp->i = nval;
	    break;

	case VALTYPE_STRING:
	    values->vp->p = strmalloc(rp);
	    break;

	case VALTYPE_REGEX:
	    if ((r = new_regexval(rp, TRUE)) == 0) {
		values->vp->r = new_regexval("", TRUE);
		return FALSE;
	    }
	    values->vp->r = r;
	    break;

	default:
	    mlforce("BUG: bad type %s %d", names->name, names->type);
	    return FALSE;
	}
    }

    /*
     * Set window flags (to force the redisplay as needed), and apply
     * side-effects.
     */
    status = TRUE;
    if (!same_val(names, values, &oldvalue)) {
	changed = TRUE;
    }

    if (!defining
	&& changed
	&& (names->side_effect != 0)
	&& !(*(names->side_effect)) (bp, args, (values == globls), FALSE)) {
	if (!same_val(names, values, &oldvalue)) {
	    free_val(names, values);
	}
	(void) copy_val(values, &oldvalue);
	mlforce("[Cannot set this value]");
	status = FALSE;
    } else if (values == globls) {
	free_val(names, &oldvalue);
    } else if (isLocalVal(&oldvalue)) {
	free_val(names, &oldvalue);
    }

    return status;
}

/* ARGSUSED */
int
listmodes(int f, int n GCC_UNUSED)
{
    WINDOW *wp = curwp;
    int s;

    TRACE((T_CALLED "listmodes(f=%d)\n", f));

    s = liststuff(SETTINGS_BufName, FALSE, makemodelist, f, (void *) wp);
    /* back to the buffer whose modes we just listed */
    if (swbuffer(wp->w_bufp))
	curwp = wp;
    returnCode(s);
}

/*
 * The 'mode_complete()' and 'mode_eol()' functions are invoked from
 * 'kbd_reply()' to setup the mode-name completion and query displays.
 */
static int
mode_complete(DONE_ARGS)
{
    init_my_mode_list();

    return kbd_complete(PASS_DONE_ARGS,
			(const char *) &my_mode_list[0], sizeof(my_mode_list[0]));
}

int
/*ARGSUSED*/
mode_eol(EOL_ARGS)
{
    (void) buffer;
    (void) cpos;

    return (c == ' ' || c == eolchar);
}

int
lookup_valnames(const char *rp, const struct VALNAMES *table)
{
    int j;

    if (rp != 0) {
	for (j = 0; table[j].name != 0; j++) {
	    if (!strcmp(rp, table[j].name)
		|| !strcmp(rp, table[j].shortname)) {
		return j;
	    }
	}
    }
    return -1;
}

static const char *
strip_no(const char *mode)
{
    return noPrefix(mode) ? (mode + 2) : mode;
}

#if OPT_MAJORMODE
/*
 * Find a submode value for the current majormode.
 */
int
find_submode(BUFFER *bp, const char *mode, int global, VALARGS * args)
{
    const char *rp = strip_no(mode);
    int j;

    /* major submodes (buffers) */
    if (my_majormodes != 0) {
	int k = 0;
	size_t n = strlen(rp);

	for (j = 0; my_majormodes[j].shortname; j++) {
	    MAJORMODE_LIST *p = my_majormodes + j;
	    struct VAL *my_vals = get_sm_vals(p->data);
	    size_t len = strlen(p->shortname);

	    if (n >= len
		&& !strncmp(rp, p->shortname, len)
		&& (k = lookup_valnames(rp + len + (rp[len] == '-'),
					b_valnames)) >= 0
		&& is_local_val(my_vals, k)) {
		TRACE(("...found submode %s\n", b_valnames[k].name));
		if (global == FALSE) {
		    if (valid_buffer(bp)
			&& (bp->majr == 0
			    || strcmp(bp->majr->shortname, p->shortname))) {
			TRACE(("...not applicable\n"));
			return FALSE;
		    }
		    args->names = b_valnames + k;
		    args->global = my_vals + k;
		    args->local = (valid_buffer(bp)
				   ? bp->b_values.bv + k
				   : (struct VAL *) 0);
		} else {
		    args->names = b_valnames + k;
		    args->global = my_vals + k;
		    args->local = args->global;
		}
		return TRUE;
	    }
	}
    }
    return FALSE;
}
#endif

/*
 * Check if the given mode exists for the given class.  If so, fill in its
 * data and return true.  Otherwise return false.  The 'args' data is filled
 * in unless there is no such mode class.
 */
int
find_mode_class(BUFFER *bp,
		const char *mode,
		int global,
		VALARGS * args,
		MODECLASS mode_class)
{
    const char *rp = strip_no(mode);
    int j;

    memset(args, 0, sizeof(*args));
    switch (mode_class) {
    default:
    case UNI_MODE:		/* universal modes */
	args->names = g_valnames;
	args->global = global_g_values.gv;
	args->local = ((global !=FALSE)
		       ? args->global
		       : (struct VAL *)0);
	break;
    case BUF_MODE:		/* buffer modes */
	args->names = b_valnames;
	args->global = global_b_values.bv;
	args->local = ((global == TRUE)
		       ? args->global
		       : (valid_buffer(bp)
			  ? bp->b_values.bv
			  : (struct VAL *)0));
	break;
    case WIN_MODE:		/* window modes */
	args->names = w_valnames;
	args->global = global_w_values.wv;
	args->local = ((global == TRUE)
		       ? args->global
		       : ((curwp != 0)
			  ? curwp->w_values.wv
			  : (struct VAL *)0));
	break;
#if OPT_MAJORMODE
    case MAJ_MODE:		/* major modes */
	args->names = major_valnames;
	args->global = major_g_vals;
	args->local = ((global == TRUE)
		       ? args->global
		       : (valid_buffer(bp)
			  ? major_l_vals
			  : (struct VAL *)0));
	break;
    case SUB_MODE:		/* major submodes (qualifiers) */
	if (my_majormodes != 0) {
	    size_t n = strlen(rp);

	    for (j = 0; my_majormodes[j].shortname; j++) {
		MAJORMODE_LIST *p = my_majormodes + j;
		size_t len = strlen(p->shortname);

		if (n >= len
		    && !strncmp(rp, p->shortname, len)
		    && (lookup_valnames(rp, p->qual)) >= 0) {
		    args->names = p->qual;
		    args->global = p->data->mm.mv;
		    args->local = ((global !=FALSE)
				   ? args->global
				   : (struct VAL *)0);
		    break;
		}
	    }
	}
	break;
#endif
    }
    if (args->names != 0
	&& args->local != 0) {
	if ((j = lookup_valnames(rp, args->names)) >= 0) {
	    args->names += j;
	    args->local += j;
	    args->global +=j;
	    TRACE(("...found class %d %s\n", mode_class, rp));
#if OPT_MAJORMODE
	    if (mode_class == MAJ_MODE) {
		const char *it = ((bp->majr != 0)
				  ? bp->majr->shortname
				  : "?");
		make_global_val(args->local, args->global, 0);
		if (global) {
		    MAJORMODE_LIST *ptr = lookup_mm_list(it);
		    args->local[0].v.i = (ptr != 0 && ptr->flag);
		} else {
		    char temp[NSTRING];
		    majorname(temp, it, TRUE);
		    make_local_val(args->local, 0);
		    args->local[0].v.i = !strcmp(temp, rp);
		}
	    }
#endif
	    return TRUE;
	}
    }
    return FALSE;
}

/*
 * Search the list of modes across all classes to find the first match, and
 * fill in the corresponding data, returning true.  If no match is found,
 * return false.
 */
int
find_mode(BUFFER *bp, const char *mode, int global, VALARGS * args)
{
    int mode_class;

    TRACE2(("find_mode(%s) %s\n", mode, global ? "global" : "local"));

    for (mode_class = 0; mode_class < END_MODE; mode_class++) {
	if (find_mode_class(bp, mode, global, args, (MODECLASS) mode_class))
	      return TRUE;
    }
#if OPT_MAJORMODE
    if (find_submode(bp, mode, global, args)) {
	return TRUE;
    }
#endif
    TRACE2(("...not found\n"));
    return FALSE;
}

/*
 * Process a single mode-setting
 */
static int
do_a_mode(int kind, int global)
{
    int rc = FALSE;
    VALARGS args;
    int s;
    static TBUFF *cbuf;		/* buffer to receive mode name into */

    /* prompt the user and get an answer */
    /* *INDENT-OFF* */
    tb_scopy(&cbuf, "");
    if ((s = kbd_reply((global
			? "Global value: "
			: "Local value: "),
		       &cbuf,
		       mode_eol, '=', KBD_NORMAL, mode_complete)) != TRUE) {
	rc = ((s == FALSE) ? SORTOFTRUE : s);
#if OPT_MODELINE
	if (clexec && (in_modeline >= 2) && (s == ABORT)) {
	    TRACE(("Recovering from unsupported vi-mode:%s\n",
		   tb_values(cbuf)));
	    if (end_string() == '=') {
		char respbuf[NSTRING];
		kbd_string("", respbuf, sizeof(respbuf), ' ',
			    KBD_NORMAL, no_completion);
	    }
	    TRACE(("...done recovering...\n"));
	    rc = TRUE;
	}
#endif
    } else if (tb_length(cbuf) == 0) {
	rc = FALSE;
    } else if (!strcmp(tb_values(cbuf), "all")) {
	if (ok_local_mode()) {
	    hst_glue(' ');
	    rc = listmodes(FALSE, 1);
	}
    } else if ((s = find_mode(curbp, tb_values(cbuf), global, &args)) != TRUE) {
#if OPT_EVAL
	if (global) {
	    rc = set_state_variable(tb_values(cbuf), NULL);
	} else if ((s = find_mode(curbp, tb_values(cbuf), TRUE, &args)) != TRUE) {
	    rc = set_state_variable(tb_values(cbuf), NULL);
	} else {
	    mlforce("[Not a local mode: \"%s\"]", tb_values(cbuf));
	}
#else
	mlforce("[Not a legal set option: \"%s\"]", tb_values(cbuf));
#endif
    } else if ((s = adjvalueset(tb_values(cbuf), FALSE, kind, global, &args)) != 0) {
	if (s == TRUE) {
	    mlerase();	/* erase the junk */
	}
	rc = s;
    } else {
	rc = FALSE;
    }
    /* *INDENT-ON* */

    return rc;
}

/*
 * Process the list of mode-settings.
 * If 'kind' is true, set otherwise delete.
 */
static int
adjustmode(int kind, int global)
{
    int s;
    int anything = 0;

    if (kind && global &&isreturn(end_string()))
	return listmodes(TRUE, 1);

    while (((s = do_a_mode(kind, global)) == TRUE) && (end_string() == ' '))
	  anything++;
    if ((s == SORTOFTRUE) && anything)	/* fix for trailing whitespace */
	return TRUE;

    /* if the settings are up, redisplay them */
    relist_settings();
    relist_majormodes();

    return s;
}

/*
 * Buffer-animation for [Settings]
 */
#if OPT_UPBUFF
static int
show_Settings(BUFFER *bp)
{
    b_clr_obsolete(bp);
    return listmodes(FALSE, 1);
}

static void
relist_settings(void)
{
    update_scratch(SETTINGS_BufName, show_Settings);
}
#endif /* OPT_UPBUFF */

/* prompt and set an editor mode */
/* ARGSUSED */
int
setlocmode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return adjustmode(TRUE, FALSE);
}

/* prompt and delete an editor mode */
/* ARGSUSED */
int
dellocmode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return adjustmode(FALSE, FALSE);
}

/* prompt and set a global editor mode */
/* ARGSUSED */
int
setglobmode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return adjustmode(TRUE, TRUE);
}

/* prompt and delete a global editor mode */
/* ARGSUSED */
int
delglobmode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return adjustmode(FALSE, TRUE);
}

/*
 * The following functions are invoked to carry out side effects of changing
 * modes.
 */
/*ARGSUSED*/
int
chgd_autobuf(BUFFER *bp GCC_UNUSED,
	     VALARGS * args GCC_UNUSED,
	     int glob_vals,
	     int testing GCC_UNUSED)
{
    if (glob_vals)
	sortlistbuffers();
    return TRUE;
}

/*ARGSUSED*/
int
chgd_buffer(BUFFER *bp GCC_UNUSED,
	    VALARGS * args GCC_UNUSED,
	    int glob_vals,
	    int testing GCC_UNUSED)
{
    if (!glob_vals) {		/* i.e., ":setl" */
	if (bp == 0)
	    return FALSE;
	b_clr_counted(bp);
	(void) bsizes(bp);
    }
    return TRUE;
}

int
chgd_charset(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	charinit();
    }
    return chgd_window(bp, args, glob_vals, testing);
}

#if OPT_COLOR
int
chgd_color(BUFFER *bp GCC_UNUSED, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	if (&args->local->vp->i == &gfcolor)
	    term.setfore(gfcolor);
	else if (&args->local->vp->i == &gbcolor)
	    term.setback(gbcolor);
	else if (&args->local->vp->i == &gccolor)
	    term.setccol(gccolor);
	set_winflags(glob_vals, WFHARD | WFCOLR);
	need_update = TRUE;
    }
    return TRUE;
}

#if OPT_ENUM_MODES || OPT_COLOR_SCHEMES
static void
set_fsm_choice(const char *name, const FSM_CHOICES * choices)
{
    size_t n;

    TRACE((T_CALLED "set_fsm_choices(%s)\n", name));
#if OPT_TRACE
    for (n = 0; choices[n].choice_name != 0; n++)
	TRACE(("   [%d] %s = %d (%#x)\n", (int) n,
	       choices[n].choice_name,
	       choices[n].choice_code,
	       choices[n].choice_code));
#endif
    for (n = 0; n < TABLESIZE(fsm_tbl); n++) {
	if (!strcmp(name, fsm_tbl[n].mode_name)) {
	    blist_reset(&(fsm_tbl[n].lists->blist),
			fsm_tbl[n].lists->choices = choices);
	    break;
	}
    }
    returnVoid();
}
#endif /* OPT_ENUM_MODES || OPT_COLOR_SCHEMES */

static int
is_white(int n)
{
    if (ncolors <= 8)
	return ((n & 7) == 7);
    return (n == NCOLORS - 1);
}

static int
reset_color(int n)
{
    int oldvalue = global_g_val(n);
    if (oldvalue > ncolors && !is_white(oldvalue)) {
	set_global_g_val(n, oldvalue % ncolors);
	TRACE(("reset_color(%scolor) from %d to %d\n",
	       (n == GVAL_FCOLOR) ? "f" : "b",
	       oldvalue,
	       global_g_val(n)));
	return TRUE;
    }
    return FALSE;
}

#if OPT_ENUM_MODES
static FSM_CHOICES *my_colors;
static FSM_CHOICES *my_hilite;

static int
choosable_color(const char *name, int n)
{
    if (ncolors > 2 && n < NCOLORS) {
	if (ncolors <= 8	/* filter out misleading names */
	    && (!strncmp(name, "bright", 6)
		|| !strncmp(name, "light", 5)
		|| !strcmp(name, "gray")
		|| !strcmp(name, "brown")))
	    return FALSE;
	return TRUE;
    }
    return (n == C_BLACK) || (n == NCOLORS - 1);
}
#endif

/*
 * Set the number of colors to a subset of that which is configured.  The main
 * use for this is to switch between 16-colors and 8-colors, though it should
 * work for setting any value up to the NCOLORS value.
 */
int
set_colors(int n)
{
    static int initialized;
#if OPT_ENUM_MODES
    const FSM_CHOICES *the_colors, *the_hilite;
    size_t s, d;
    int code;
#endif

    TRACE((T_CALLED "set_colors(%d)\n", n));

    if (n > NCOLORS || n < 2)
	returnCode(FALSE);
    if (!initialized)
	initialized = n;
    if (n > initialized)
	returnCode(FALSE);
    ncolors = n;

    if (reset_color(GVAL_FCOLOR)
	|| reset_color(GVAL_BCOLOR)) {
	set_winflags(TRUE, WFHARD | WFCOLR);
	need_update = TRUE;
	relist_settings();
    }
#if OPT_ENUM_MODES
    if (ncolors == NCOLORS) {
	the_colors = fsm_color_choices;
	the_hilite = fsm_hilite_choices;
    } else {

	beginDisplay();
	my_colors = typecallocn(FSM_CHOICES, fsm_size(fsm_color_choices));
	my_hilite = typecallocn(FSM_CHOICES, fsm_size(fsm_hilite_choices));
	endofDisplay();

	if (my_colors == 0
	    || my_hilite == 0) {
	    FreeIfNeeded(my_colors);
	    return FALSE;
	}

	the_colors = my_colors;
	the_hilite = my_hilite;
	for (s = d = 0; fsm_color_choices[s].choice_name != 0; s++) {
	    my_colors[d] = fsm_color_choices[s];
	    if (choosable_color(my_colors[d].choice_name, my_colors[d].choice_code)) {
		if (ncolors <= 8)
		    my_colors[d].choice_code %= 8;
		d++;
	    }
	}
	my_colors[d].choice_name = 0;

	for (s = d = 0; fsm_hilite_choices[s].choice_name != 0; s++) {
	    my_hilite[d] = fsm_hilite_choices[s];
	    code = my_hilite[d].choice_code;
	    if (code >= 0 && (code & VASPCOL) != 0) {
		if (ncolors > 2
		    && choosable_color(my_hilite[d].choice_name, VCOLORNUM(code))) {
		    my_hilite[d].choice_code = (VASPCOL | code);
		    d++;
		}
	    } else if (ncolors > 2 || (code & VACOLOR) == 0) {
		d++;
	    }
	}
	my_hilite[d].choice_name = 0;
    }
    set_fsm_choice(s_fcolor, the_colors);
    set_fsm_choice(s_bcolor, the_colors);
    set_fsm_choice(s_ccolor, the_colors);
    set_fsm_choice("visual-matches", the_hilite);
    set_fsm_choice("mini-hilite", the_hilite);
    relist_descolor();
#endif /* OPT_ENUM_MODES */
    returnCode(TRUE);
}
#endif /* OPT_COLOR */

#if OPT_SHOW_COLORS

#if OPT_COLOR_CHOICES
static const char *
lookup_color_code(int code)
{
    const char *rc = 0;
    int j;
    const FSM_CHOICES *the_colors = name_to_choices(s_fcolor)->choices;

    for (j = 0; the_colors[j].choice_name != 0; j++) {
	if (code == the_colors[j].choice_code) {
	    rc = the_colors[j].choice_name;
	    break;
	}
    }
    return rc;
}
#endif

int
is_color_code(int n)
{
    int rc;
#if OPT_COLOR_CHOICES
    rc = (lookup_color_code(n) != 0);
#else
    rc = (c >= C_BLACK && n < ncolors);
#endif
    return rc;
}

const char *
get_color_name(int n)
{
    static char temp[80];
    const char *rc = 0;

#if OPT_COLOR_CHOICES
    if ((rc = lookup_color_code(n)) == 0)
#endif
    {
	lsprintf(temp, "color #%d", n);
	rc = temp;
    }
    return rc;
}
#endif

	/* Report mode that cannot be changed */
/*ARGSUSED*/
int
chgd_disabled(BUFFER *bp GCC_UNUSED,
	      VALARGS * args,
	      int glob_vals GCC_UNUSED,
	      int testing GCC_UNUSED)
{
    mlforce("[Cannot change \"%s\" ]", args->names->name);
    return FALSE;
}

	/* Change "fences" mode */
/*ARGSUSED*/
int
chgd_fences(BUFFER *bp GCC_UNUSED, VALARGS * args, int glob_vals GCC_UNUSED, int testing)
{
    if (!testing) {
	/* was even number of fence pairs specified? */
	char *value = args->local->vp->p;
	size_t len = strlen(value);

	if (len & 1) {
	    value[len - 1] = EOS;
	    mlwrite("[Fence-pairs not in pairs:  truncating to \"%s\"",
		    value);
	    return FALSE;
	}
    }
    return TRUE;
}

	/* Change a "major" mode (one that we cannot use in majormodes) */
int
chgd_major(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    /* prevent major changes for scratch-buffers */
    if (testing) {
	if (!glob_vals) {
	    if (b_is_scratch(bp))
		return chgd_disabled(bp, args, glob_vals, testing);
	}
    } else {
	set_bufflags(glob_vals, WFMODE);
    }
    return TRUE;
}

	/* Change the "undoable" mode (this is also a major change) */
int
chgd_undoable(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (chgd_major(bp, args, glob_vals, testing)) {
	if (!testing
	    && !(args->local->v.i))
	    freeundostacks(bp, TRUE);
	return TRUE;
    }
    return FALSE;
}

	/* Change a mode that affects the window(s) on the buffer */
int
chgd_win_mode(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (testing) {
	if (!chgd_major(bp, args, glob_vals, testing))
	    return FALSE;
	return chgd_window(bp, args, glob_vals, testing);
    }

    set_winflags(glob_vals, WFHARD | WFMODE);
    return TRUE;
}

	/* Change the DOS-mode on the buffer */
int
chgd_dos_mode(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    int rc = TRUE;

    if (testing) {
	rc = chgd_win_mode(bp, args, glob_vals, testing);
    } else {
	if (!glob_vals) {
	    if (args->local->vp->i) {
		rc = set_rs_crlf(FALSE, 1);
	    } else {
		rc = set_rs_lf(FALSE, 1);
	    }
	}
	set_winflags(glob_vals, WFHARD | WFMODE);
    }
    return rc;
}

void
set_record_sep(BUFFER *bp, RECORD_SEP code)
{
    const char *recordsep = "\n";

    if (code == RS_AUTO)
	code = RS_DEFAULT;

    switch (code) {
    case RS_AUTO:
	/* see above */
	break;
    case RS_LF:
	/* see above */
	break;
    case RS_CRLF:
	recordsep = "\r\n";
	break;
    case RS_CR:
	recordsep = "\r";
	break;
    }
    (bp)->b_recordsep_str = recordsep;
    (bp)->b_recordsep_len = (int) strlen(get_record_sep(bp));

    make_local_b_val(bp, MDDOS);
    make_local_b_val(bp, VAL_RECORD_SEP);
    set_b_val(bp, MDDOS, (code == RS_CRLF));
    set_b_val(bp, VAL_RECORD_SEP, code);
    b_clr_counted(bp);
    (void) bsizes(bp);
    relist_settings();
    updatelistbuffers();
    set_winflags(TRUE, WFMODE);
}

	/* Change the record separator */
int
chgd_rs(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	if (bp == 0)
	    return FALSE;
	if (args->local->vp->i == RS_AUTO)
	    args->local->vp->i = RS_DEFAULT;
	set_record_sep(bp, (RECORD_SEP) args->local->vp->i);
    }

    set_winflags(TRUE, WFMODE);
    return chgd_win_mode(bp, args, glob_vals, testing);
}

	/* Change something on the mode/status line */
/*ARGSUSED*/
int
chgd_status(BUFFER *bp GCC_UNUSED, VALARGS * args GCC_UNUSED, int glob_vals, int testing)
{
    if (!testing) {
	set_winflags(glob_vals, WFSTAT);
    }
    return TRUE;
}

#if OPT_CURTOKENS
static int
have_b_val_rexp(BUFFER *bp, int mode)
{
    return (bp != 0
	    && bp->b_values.bv[mode].vp != 0
	    && bp->b_values.bv[mode].vp->r != 0
	    && bp->b_values.bv[mode].vp->r->pat != 0);
}

static int
update_regexval(struct VAL *val, const char *pattern, int magic)
{
    int result = TRUE;
    union V *vp = val->vp;

    vp->r = free_regexval(vp->r);
    vp->r = new_regexval(pattern, magic);
    if (vp->r == 0) {
	vp->r = new_regexval("", TRUE);
	result = FALSE;
    }
    return result;
}

/*
 * Maintain the $buf-fname-expr variable, which is the combination of the
 * bufname-expr and pathname-expr modes.
 *
 * Yes, we could add another mode - but since the value is readonly and
 * derived, it does not really fit as a mode.  It is stored in BUFFER as a
 * struct VAL so we can treat the value as a local/global mode.
 */
void
set_buf_fname_expr(BUFFER *bp)
{
    TBUFF *combined = 0;

    if ((bp == 0 || b_val(bp, VAL_CURSOR_TOKENS) != CT_CCLASS)
	&& have_b_val_rexp(bp, VAL_BUFNAME_EXPR)
	&& have_b_val_rexp(bp, VAL_PATHNAME_EXPR)
	&& tb_sappend(&combined, "\\(")
	&& tb_sappend(&combined, b_val_rexp(bp, VAL_BUFNAME_EXPR)->pat)
	&& tb_sappend(&combined, "\\|")
	&& tb_sappend(&combined, b_val_rexp(bp, VAL_PATHNAME_EXPR)->pat)
	&& tb_sappend(&combined, "\\)")
	&& tb_append(&combined, EOS)) {
	char *pattern = tb_values(combined);
	struct VAL *global_expr = &buf_fname_expr;
	struct VAL *local_expr;
	int local = FALSE;

	TRACE(("set_buf_fname_expr(%s)\n", pattern));
	if (bp != 0) {
	    local_expr = &(bp->buf_fname_expr);

	    if (is_local_b_val(bp, VAL_BUFNAME_EXPR)
		|| is_local_b_val(bp, VAL_PATHNAME_EXPR)) {
		local = TRUE;
		local_expr->vp = &(local_expr->v);
		update_regexval(local_expr, pattern, TRUE);
	    } else {
		local_expr->vp = &(global_expr->v);
	    }
	}
	if (!local) {
	    global_expr->vp = &(global_expr->v);
	    update_regexval(global_expr, pattern, TRUE);
	}
    }
    tb_free(&combined);
}

REGEXVAL *
get_buf_fname_expr(BUFFER *bp)
{
    REGEXVAL *result = 0;
    if (bp->buf_fname_expr.vp != 0)
	result = bp->buf_fname_expr.vp->r;
    else
	result = buf_fname_expr.vp->r;
    return result;
}

int
chgd_curtokens(BUFFER *bp,
	       VALARGS * args GCC_UNUSED,
	       int glob_vals GCC_UNUSED,
	       int testing)
{
    if (!testing)
	set_buf_fname_expr(bp);
    return TRUE;
}
#endif

#if OPT_TITLE
	/* Changed swap-title */
int
chgd_swaptitle(BUFFER *bp GCC_UNUSED,
	       VALARGS * args GCC_UNUSED,
	       int glob_vals GCC_UNUSED,
	       int testing)
{
    if (!testing)
	set_editor_title();
    return TRUE;
}
#endif

#if OPT_FINDPATH
/*
 * user changed find-cfg mode
 *
 * Strictly speaking, there is no reason to require that a chgd() function
 * track changes to find-cfg mode.  However, this routine does allow the
 * editor to flag incorrect syntax before a shell command is initiated.
 */
int
chgd_find_cfg(BUFFER *bp GCC_UNUSED,
	      VALARGS * args,
	      int glob_vals GCC_UNUSED,
	      int testing)
{
    int rc = TRUE;
    FINDCFG unused;

    if (!testing)
	rc = parse_findcfg_mode(&unused, args->global->vp->p);
    return (rc);
}
#endif

	/* Change a mode that affects the windows on the buffer */
/*ARGSUSED*/
int
chgd_window(BUFFER *bp GCC_UNUSED, VALARGS * args GCC_UNUSED, int glob_vals, int testing)
{
    if (!testing) {
	set_winflags(glob_vals, WFHARD);
    }
    return TRUE;
}

	/* if unique-buffers is turned on, make sure all buffers that
	   can have a valid fuid */
/*ARGSUSED*/
int
chgd_uniqbuf(BUFFER *bp GCC_UNUSED,
	     VALARGS * args GCC_UNUSED,
	     int glob_vals GCC_UNUSED,
	     int testing)
{
    if (!testing) {
	if (global_g_val(GMDUNIQ_BUFS)) {
	    FUID fuid;
	    BUFFER *bp2;

	    for_each_buffer(bp2) {
		if (bp2->b_fname != 0
		    && !isInternalName(bp2->b_fname)
		    && fileuid_get(bp2->b_fname, &fuid)) {
		    fileuid_set(bp2, &fuid);
		}
	    }
	}
    }
    return TRUE;
}

	/* Change the working mode */
#if OPT_WORKING
/*ARGSUSED*/
int
chgd_working(BUFFER *bp GCC_UNUSED,
	     VALARGS * args GCC_UNUSED,
	     int glob_vals,
	     int testing GCC_UNUSED)
{
    if (glob_vals)
	imworking(0);
    return TRUE;
}
#endif

	/* Change the xterm-mouse mode */
/*ARGSUSED*/
int
chgd_xterm(BUFFER *bp GCC_UNUSED,
	   VALARGS * args GCC_UNUSED,
	   int glob_vals GCC_UNUSED,
	   int testing GCC_UNUSED)
{
#if OPT_XTERM
    if (glob_vals && !testing) {
	int new_state = global_g_val(GMDXTERM_MOUSE);
	set_global_g_val(GMDXTERM_MOUSE, !new_state);
	term.kclose();
	set_global_g_val(GMDXTERM_MOUSE, new_state);
	term.kopen();
	vile_refresh(FALSE, 0);
    }
#endif
    return TRUE;
}

	/* Change the xterm-fkeys mode */
/*ARGSUSED*/
int
chgd_xtermkeys(BUFFER *bp GCC_UNUSED,
	       VALARGS * args GCC_UNUSED,
	       int glob_vals GCC_UNUSED,
	       int testing GCC_UNUSED)
{
#if DISP_TERMCAP || DISP_CURSES
    if (glob_vals && !testing) {
	tcap_init_fkeys();
    }
#endif
    return TRUE;
}

	/* Change the mouse mode */
#ifdef GMDMOUSE
/*ARGSUSED*/
int
chgd_mouse(BUFFER *bp, VALARGS * args GCC_UNUSED, int glob_vals, int testing GCC_UNUSED)
{
    if (glob_vals) {
	int new_state = global_g_val(GMDMOUSE);
	set_global_g_val(GMDMOUSE, TRUE);
	if (!new_state)
	    term.kclose();
	else
	    term.kopen();
	set_global_g_val(GMDMOUSE, new_state);
    }
    return TRUE;
}
#endif

	/* Change a mode that affects the search-string highlighting */
/*ARGSUSED*/
int
chgd_hilite(BUFFER *bp, VALARGS * args GCC_UNUSED, int glob_vals GCC_UNUSED, int testing)
{
    if (!testing) {
#if OPT_HILITEMATCH
	if (bp->b_highlight & HILITE_ON)
	    bp->b_highlight |= HILITE_DIRTY;
	if (bp == curbp)	/* FIXME: attrib_matches only does curbp */
	    attrib_matches();
#endif
#if OPT_COLOR
	set_winflags(glob_vals, WFHARD | WFCOLR);
	need_update = TRUE;
#endif
    }
    return TRUE;
}

#if SYS_WINNT
int
chgd_rcntfiles(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	int nfiles = args->global->v.i;

	if (nfiles < 0 || nfiles > MAX_RECENT_FILES)
	    return (FALSE);
    }
    return (TRUE);
}

int
chgd_rcntfldrs(BUFFER *bp, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	int nfolders = args->global->v.i;

	if (nfolders < 0 || nfolders > MAX_RECENT_FLDRS)
	    return (FALSE);
    }
    return (TRUE);
}
#endif /* SYS_WINNT */

/*--------------------------------------------------------------------------*/

#if OPT_EVAL || OPT_MAJORMODE
/*
 * Test for mode-names that we'll not show in the variable name-completion.
 */
int
is_varmode(const char *name)
{
    return (!noPrefix(name)
	    && strcmp(name, "all"));
}

/*
 * Returns the current number of items in the list of modes
 */
static int
count_modes(void)
{
    init_my_mode_list();
    return blist_count(&blist_my_mode_list);
}

/*
 * Returns true if the given pointer is in all_modes[].  We use this to check
 * whether a name is in the original const array or not, so we can free it.
 */
static int
in_all_modes(const char *name)
{
    unsigned n;
    for (n = 0; all_modes[n] != 0; n++) {
	if (all_modes[n] == name)
	    return TRUE;
    }
    return FALSE;
}

static void
fill_my_varmodes(void)
{
    const char *const *s;
    const char **d;

    if (my_varmodes != 0 && my_mode_list != 0) {
	for (s = my_mode_list,
	     d = (const char **) my_varmodes; (*d = *s) != 0; s++) {
	    if (is_varmode(*d)) {
		d++;
	    }
	}
    }
}

static size_t
need_my_varmodes(size_t actual)
{
    return (actual | 31);
}

static void
free_my_varmodes(void)
{
    FreeAndNull(my_varmodes);
}

/*
 * The my_varmodes[] data is an index into my_mode_list.
 */
static void
check_my_varmodes(size_t actual)
{
    if (my_varmodes != 0) {
	size_t need = need_my_varmodes(actual);
	if (need > size_my_varmodes) {
	    free_my_varmodes();
	}
    }
}

/*
 * Return a list of only the modes that can be set with ":setv", ignoring
 * artifacts such as "all".
 */
const char *const *
list_of_modes(void)
{
    if (my_varmodes == 0) {
	size_t n;

	beginDisplay();
	n = need_my_varmodes(count_modes()) + 1;
	my_varmodes = typeallocn(char *, n);
	size_my_varmodes = n;
	endofDisplay();

	fill_my_varmodes();
    }
    return (const char **) my_varmodes;
}
#endif /* OPT_EVAL || OPT_MAJORMODE */

/*--------------------------------------------------------------------------*/

#if OPT_MAJORMODE
static int
is_identifier(const char *name)
{
    if (name != 0) {
	int first = TRUE;

	while (*name != EOS) {
	    if (first) {
		if (!isAlpha(*name))
		    return FALSE;
		first = FALSE;
	    } else if (!isident(*name))
		return FALSE;
	    name++;
	}
	return TRUE;
    }
    return FALSE;
}

static int
ok_submode(const char *name)
{
    /* like is_varmode, but allow "no" prefix */
    return strcmp(name, "all") != 0 ? TRUE : FALSE;
}

/* format the name of a majormode's qualifier */
static char *
per_major(char *dst, const char *majr, size_t code, int brief)
{
    if (brief) {
	if (!strcmp(m_valnames[code].shortname, "X")) {
	    *dst = EOS;
	} else {
	    (void) lsprintf(dst, "%s%s", majr, m_valnames[code].shortname);
	}
    } else {
	(void) lsprintf(dst, "%s-%s", majr, m_valnames[code].name);
    }
    return dst;
}

/* format the name of a majormode's submode */
static char *
per_submode(char *dst, const char *majr, int code, int brief)
{
    if (brief) {
	if (!strcmp(b_valnames[code].shortname, "X")) {
	    *dst = EOS;
	    return 0;
	}
	(void) lsprintf(dst, "%s%s", majr, b_valnames[code].shortname);
    } else {
	(void) lsprintf(dst, "%s-%s", majr, b_valnames[code].name);
    }
    return dst;
}

static char *TheMajor;

static const char *
ModeName(const char *name)
{
    if (TheMajor != 0) {
	static char *dst;

	beginDisplay();
	if (dst != 0)
	    free(dst);
	dst = typeallocn(char, strlen(TheMajor) + strlen(name) + 3);
	endofDisplay();

	if (dst != 0) {
	    (void) lsprintf(dst, "%s-%s", TheMajor, name);
	    return dst;
	}
    }
    return name;
}

/* format the name of a majormode */
static char *
majorname(char *dst, const char *majr, int flag)
{
    (void) lsprintf(dst, "%s%s" MAJOR_SUFFIX, flag ? "" : NO_PREFIX, majr);
    return dst;
}

/*
 * Returns the current number of items in the list of modes
 */
static unsigned
count_majormodes(void)
{
    unsigned n = 0;

    if (my_majormodes != 0) {
	n = blist_count(&majormode_blist);
    }
    return n;
}

static int
get_mm_number(int n, int m)
{
    int result = 0;

    if (my_majormodes[n].data != 0) {
	struct VAL *mv = my_majormodes[n].data->mm.mv;

	if (mv[m].vp->i != 0) {
	    TRACE(("get_mm_number(%s) %d\n",
		   my_majormodes[n].shortname,
		   mv[m].vp->i));
	    result = mv[m].vp->i;
	}
    }
    return result;
}

/*
 * Returns the regular expression for the given indices, checking that the
 * pattern is non-null.
 */
static regexp *
get_mm_rexp(int n, int m)
{
    regexp *result = 0;

    if (my_majormodes[n].data != 0) {
	struct VAL *mv = my_majormodes[n].data->mm.mv;

	if (mv[m].vp != 0
	    && mv[m].vp->r != 0
	    && mv[m].vp->r->pat != 0
	    && mv[m].vp->r->pat[0] != 0
	    && mv[m].vp->r->reg != 0) {
	    TRACE(("get_mm_rexp(%s) %s\n",
		   my_majormodes[n].shortname,
		   mv[m].vp->r->pat));
	    result = mv[m].vp->r->reg;
	}
    }
    return result;
}

static char *
get_mm_string(int n, int m)
{
    char *result = 0;

    if (my_majormodes[n].data != 0) {
	struct VAL *mv = my_majormodes[n].data->mm.mv;

	if (mv[m].vp->p != 0) {
	    TRACE(("get_mm_string(%s) %s\n",
		   my_majormodes[n].shortname,
		   mv[m].vp->p));
	    result = mv[m].vp->p;
	}
    }
    return result;
}

static int
find_majormode_order(int mm)
{
    int found = -1;
    int n;

    if (majormodes_order != 0) {
	for (n = 0; majormodes_order[n] >= 0; n++) {
	    if (majormodes_order[n] == mm) {
		found = n;
		break;
	    }
	}
    }
    return found;
}

#if OPT_TRACE
static void
show_majormode_order(char *tag)
{
    static TBUFF *order;

    int n;
    if (majormodes_order != 0) {
	tb_scopy(&order, "order ");
	tb_sappend0(&order, tag);
	for (n = 0; majormodes_order[n] >= 0; n++) {
	    tb_sappend0(&order, " ");
	    tb_sappend0(&order, my_majormodes[majormodes_order[n]].shortname);
	}
	TRACE(("%s\n", tb_values(order)));
    }
}
#else
#define show_majormode_order(tag)	/* nothing */
#endif

static int
put_majormode_before(unsigned j, const char *s)
{
    const char *t;
    const char *told = "~";	/* FIXME: majormode names are 7-bit ASCII */
    int k;
    int kk;
    int found = -1;

    if (majormodes_order != 0) {
	TRACE(("put_majormode_before(%d:%s, %s)\n",
	       j,
	       my_majormodes[majormodes_order[j]].shortname,
	       s));

	for (k = 0; (kk = majormodes_order[k]) >= 0; k++) {
	    t = my_majormodes[kk].shortname;
	    if (strcmp(t, s) <= 0
		&& (found < 0 || strcmp(told, t) < 0)) {
		found = k;
		told = t;
	    }
	}
	if (found >= 0 && found < (int) j) {
	    show_majormode_order("before");
	    kk = majormodes_order[j];
	    while (found < (int) j) {
		majormodes_order[j] =
		    majormodes_order[j - 1];
		j--;
	    }
	    majormodes_order[j] = kk;
	    show_majormode_order("after:");
	} else if (found < 0) {
	    TPRINTF(("cannot put %s before %s (not found)\n",
		     my_majormodes[majormodes_order[j]].shortname,
		     s));
	    TRACE(("...did not find %s\n", s));
	}
	TRACE(("->%d\n", j));
    }
    return j;
}

static int
put_majormode_after(unsigned j, char *s)
{
    const char *t;
    const char *told = "";
    int k;
    int kk;
    int found = -1;

    if (majormodes_order != 0) {
	TRACE(("put_majormode_after(%d:%s, %s)\n",
	       j,
	       my_majormodes[majormodes_order[j]].shortname,
	       s));

	for (k = (int) count_majormodes() - 1;
	     k >= 0 && (kk = majormodes_order[k]) >= 0;
	     k--) {
	    t = my_majormodes[kk].shortname;
	    if (strcmp(t, s) >= 0
		&& (found < 0 || strcmp(told, t) > 0)) {
		found = k;
		told = t;
	    }
	}
	if (found >= 0 && found > (int) j) {
	    show_majormode_order("before");
	    kk = majormodes_order[j];
	    while (found > (int) j) {
		majormodes_order[j] =
		    majormodes_order[j + 1];
		j++;
	    }
	    majormodes_order[found] = kk;
	    show_majormode_order("after:");
	} else if (found < 0) {
	    TPRINTF(("cannot put %s after %s (not found)\n",
		     my_majormodes[majormodes_order[j]].shortname,
		     s));
	    TRACE(("...did not find %s\n", s));
	}
	TRACE(("->%d\n", j));
    }
    return j;
}

/*
 * Make an ordered index into my_majormodes[], accounting for "before" and
 * "after" qualifiers.
 */
static void
compute_majormodes_order(void)
{
    char *s;
    size_t need = count_majormodes();
    size_t want;
    unsigned j;
    int jj;
    static size_t have;

    TRACE((T_CALLED "compute_majormodes_order(%d)\n", (int) need));
    if (need) {
	want = (need + 1) * 2;

	beginDisplay();
	if (have >= want) {
	    /* EMPTY */ ;
	} else if (have) {
	    have = want;
	    majormodes_order = typereallocn(int, majormodes_order, have);
	} else {
	    have = want;
	    majormodes_order = typecallocn(int, have);
	}
	endofDisplay();

	if (majormodes_order != 0) {
	    /* set the default order */
	    for (j = 0; j < need; j++) {
		majormodes_order[j] = j;
	    }
	    majormodes_order[need] = -1;

	    /* handle special cases */
	    for (j = 0; j < need; j++) {
		jj = majormodes_order[j];
		if ((s = get_mm_string(jj, MVAL_BEFORE)) != 0
		    && *s != EOS) {
		    jj = put_majormode_before(j, s);
		    TRACE(("JUMP %d to %d\n", j, jj));
		    if (jj < (int) j)
			j = jj;
		}
	    }
	    for (j = 0; j < need; j++) {
		jj = majormodes_order[j];
		if ((s = get_mm_string(jj, MVAL_AFTER)) != 0
		    && *s != EOS) {
		    jj = put_majormode_after(j, s);
		    TRACE(("JUMP %d to %d\n", j, jj));
		    if (jj < (int) j)
			j = jj;
		}
	    }
	    show_majormode_order("final:");
	}
    }
    returnVoid();
}

/*
 * Search my_mode_list[] for the given name, using 'count' for the array size.
 * We don't use bsearch because we need to handle insertions into the list.
 * If we find it, and will_insert is true, return -1, otherwise the index.
 * If we do not find it, return the closest index if will_insert is true,
 * otherwise -1.
 */
static int
search_mode_list(const char *name, int count, int will_insert)
{
    int prev = -1;
    int next = 0;
    int lo = 0;
    int hi = count;
    int cmp;
    const char *test;

    if (my_mode_list != 0) {
	while (lo < hi) {
	    next = (lo + hi + 0) / 2;
	    if (next == prev) {	/* didn't find it - stop iterating */
		if (will_insert) {
		    next = (strcmp(name, my_mode_list[lo]) > 0
			    ? hi : lo);
		} else {
		    next = -1;
		}
		break;
	    }
	    prev = next;
	    test = ((next < count)
		    ? my_mode_list[next]
		    : (strcmp("\177", "\377") < 0
		       ? "\377"
		       : "\177"));
	    if ((cmp = strcmp(name, test)) == 0) {
		if (will_insert)
		    next = -1;
		break;
	    } else if (cmp > 0) {
		lo = next;
	    } else {
		hi = next;
	    }
	}
    } else {
	next = -1;
    }
    return next;
}

static int
found_per_submode(const char *majr, int code)
{
    char temp[NSTRING];

    init_my_mode_list();

    (void) per_submode(temp, majr, code, TRUE);
    return search_mode_list(temp, (int) count_modes(), FALSE) >= 0;
}

/*
 * Insert 'name' into 'my_mode_list[]', which has 'count' entries.
 */
static size_t
insert_per_major(size_t count, const char *name)
{
    if (name != 0 && *name != EOS && my_mode_list != 0) {
	size_t j, k;
	int found;

	TRACE(("insert_per_major %lu %s\n", (ULONG) count, name));
	if ((found = search_mode_list(name, (int) count, TRUE)) >= 0) {
	    char *newname = strmalloc(name);

	    if (newname != 0) {
		j = found;
		for (k = ++count; k != j; k--)
		    my_mode_list[k] = my_mode_list[k - 1];
		my_mode_list[j] = newname;
		blist_my_mode_list.itemCount++;
	    } else {
		no_memory("insert_per_major");
	    }
	}
    }
    return count;
}

/*
 * Remove 'name' from 'my_mode_list[]', which has 'count' entries.
 */
static size_t
remove_per_major(size_t count, const char *name)
{
    if (name != 0 && my_mode_list != 0) {
	int redo = FALSE;
	int found;
	size_t j, k;

	if ((found = search_mode_list(name, (int) count, FALSE)) >= 0) {
	    j = found;
	    if (my_mode_list != all_modes
		&& !in_all_modes(my_mode_list[j])) {
		beginDisplay();
		redo = is_varmode(my_mode_list[j]);
		free(TYPECAST(char, my_mode_list[j]));
		endofDisplay();
	    }
	    count--;
	    for (k = j; k <= count; k++)
		my_mode_list[k] = my_mode_list[k + 1];
	    blist_my_mode_list.itemCount--;

	    if (redo)
		fill_my_varmodes();
	}
    }
    return count;
}

/*
 * Lookup a majormode's data area, given its short name, e.g., "c" vs "cmode".
 * We store the majormodes in an array to simplify name completion, though this
 * complicates definition and removal.
 */
static MAJORMODE *
lookup_mm_data(const char *name)
{
    MAJORMODE *rc = 0;
    MAJORMODE_LIST *p = lookup_mm_list(name);

    if (p != 0)
	rc = p->data;

    return rc;
}

/*
 * Lookup a majormode's data area, given its short name, e.g., "c" vs "cmode".
 * We store the majormodes in an array to simplify name completion, though this
 * complicates definition and removal.
 */
static MAJORMODE_LIST *
lookup_mm_list(const char *name)
{
    MAJORMODE_LIST *rc = 0;

    if (my_majormodes != 0) {
	int n = blist_match(&majormode_blist, name);
	if (n >= 0)
	    rc = my_majormodes + n;
    }
    return rc;
}

/* Check if a majormode is predefined.  There are some things we don't want to
 * do to them (such as remove them).
 */
static int
predef_majormode(const char *name)
{
    int rc = FALSE;
    MAJORMODE_LIST *p = lookup_mm_list(name);

    if (p != 0)
	rc = p->init;

    return rc;
}

static int
check_majormode_name(const char *name, int defining)
{
    int status = TRUE;
    if (defining && lookup_mm_data(name) != 0) {
	TRACE(("Mode '%s' already exists\n", name));
	status = SORTOFTRUE;
    } else if (!defining && lookup_mm_data(name) == 0) {
	TRACE(("Mode '%s' does not exist\n", name));
	status = SORTOFTRUE;
    }
    return status;
}

/* name-completion for "longname" */
int
major_complete(DONE_ARGS)
{
    return kbd_complete(PASS_DONE_ARGS,
			(const char *) &my_majormodes[0].longname,
			sizeof(my_majormodes[0]));
}

/* name-completion for "shortname" */
static int
short_major_complete(DONE_ARGS)
{
    return kbd_complete(PASS_DONE_ARGS,
			(const char *) &my_majormodes[0].shortname,
			sizeof(my_majormodes[0]));
}

static int
prompt_majormode(char **result, int defining)
{
    static TBUFF *cbuf;		/* buffer to receive mode name into */
    char *s;
    char *value;
    int status;

    /* prompt the user and get an answer */
    tb_scopy(&cbuf, "");
    if ((status = kbd_reply("majormode: ",
			    &cbuf,
			    eol_history, ' ',
			    KBD_NORMAL,		/* FIXME: KBD_MAYBEC if !defining */
			    (defining || clexec)
			    ? no_completion
			    : short_major_complete)) == TRUE) {
	value = tb_values(cbuf);
	/* check for legal name (alphanumeric) */
	if ((status = is_identifier(value)) != TRUE) {
	    mlwarn("[Not an identifier: %s]", value);
	    return status;
	}
	if ((s = strstr(value, MAJOR_SUFFIX)) != 0
	    && !strcmp(s, MAJOR_SUFFIX)) {
	    if (s == value) {
		mlwarn("[Not a legal majormode identifier: %s]", value);
		return ABORT;
	    }
	    *s = 0;
	}
	if ((status = is_varmode(value)) == TRUE) {
	    *result = value;
	    status = check_majormode_name(*result, defining);
	    if (status != TRUE && status != SORTOFTRUE)
		mlwarn("[No such majormode: %s]", *result);
	    return status;
	}
    }
    if (status != FALSE)
	mlwarn("[Illegal name: %s]", tb_values(cbuf));
    return status;
}

static int
submode_complete(DONE_ARGS)
{
    return kbd_complete(PASS_DONE_ARGS, (const char *) &all_submodes[0],
			sizeof(all_submodes[0]));
}

/*
 * Set the submode values to a known state
 */
static void
init_sm_vals(struct VAL *dst)
{
    int k;
    for (k = 0; k < NUM_B_VALUES; k++) {
	make_global_val(dst, global_b_values.bv, k);
    }
}

/*
 * Free data allocated in get_sm_vals().
 */
static void
free_sm_vals(MAJORMODE * ptr)
{
    MINORMODE *p;

    while (ptr->sm != 0) {
	p = ptr->sm;
	ptr->sm = p->sm_next;
	free_local_vals(b_valnames, global_b_values.bv, p->sm_vals.bv);

	beginDisplay();
	free(p->sm_name);
	free(p);
	endofDisplay();
    }
}

/*
 * Help initialization of submode groups by copying mode values from the
 * base, e.g., ignorecase for majormodes that need this in their fence patterns.
 *
 * We do not copy the regular expressions since those are what submode groups
 * are designed for, and do not want to have leftover patterns from the
 * base contaminating the fence-fi, fence-else, etc.
 */
static void
copy_sm_vals(struct VAL *dst, struct VAL *src, int type)
{
    int n;

    if (src != 0) {
	int last = NUM_B_VALUES;
	for (n = 0; n < last; n++) {
	    if (b_valnames[n].type == type
		&& is_local_val(src, n)) {
		dst[n] = src[n];
		make_local_val(dst, n);
	    }
	}
    }
}

/*
 * Using the currently specified 'group' qualifier, lookup the corresponding
 * MINORMODE structure and return a pointer to the B_VALUES VALS data.  If
 * no structure is found, create one.
 *
 * We maintain the list of MINORMODE structures in the order they are defined.
 * This has the desirable side-effect of returning immediately for the default
 * "" group.
 */
static struct VAL *
get_sm_vals(MAJORMODE * ptr)
{
    struct VAL *result = 0;
    MINORMODE *p, *q;
    char *name = ptr->mq.qv[QVAL_GROUP].vp->p;

    for (p = ptr->sm, q = 0; p != 0; q = p, p = p->sm_next) {
	if (!strcmp(name, p->sm_name)) {
	    break;
	}
    }

    if (p == 0) {

	beginDisplay();
	if ((p = typecalloc(MINORMODE)) != 0) {
	    if ((p->sm_name = strmalloc(name)) == 0) {
		free(p);
		p = 0;
	    }
	}
	endofDisplay();

	if (p != 0) {
	    init_sm_vals(&(p->sm_vals.bv[0]));
	    if (ptr->sm != 0) {
		copy_sm_vals(&(p->sm_vals.bv[0]),
			     &(ptr->sm->sm_vals.bv[0]),
			     VALTYPE_BOOL);
		copy_sm_vals(&(p->sm_vals.bv[0]),
			     &(ptr->sm->sm_vals.bv[0]),
			     VALTYPE_INT);
		copy_sm_vals(&(p->sm_vals.bv[0]),
			     &(ptr->sm->sm_vals.bv[0]),
			     VALTYPE_ENUM);
	    }
	    if (q != 0)
		q->sm_next = p;
	    else
		ptr->sm = p;
	}
    }
    if (p != 0) {
	TRACE2(("...get_sm_vals(%s:%s)\n", ptr->shortname, p->sm_name));
	result = &(p->sm_vals.bv[0]);
    }
    return result;
}

/*
 * Returns the name of the n'th submode group
 */
const char *
get_submode_name(BUFFER *bp, int n)
{
    const char *result = "";
    MAJORMODE *data;

    if (n == 0) {
	result = "";
    } else if ((data = bp->majr) != 0) {
	MINORMODE *sm = data->sm;
	while (n-- > 0) {
	    if ((sm = sm->sm_next) == 0) {
		break;
	    } else if (n == 0) {
		result = sm->sm_name;
		break;
	    }
	}
    }
    return (result);
}

/*
 * Fetch a pointer to the n'th group of submode values.  The 0th group consists
 * of the normal buffer values.  Other values are defined in the majormode.
 *
 * FIXME: shouldn't I have a local submode value for the data which is defined
 * in a group?
 */
struct VAL *
get_submode_vals(BUFFER *bp, int n)
{
    struct VAL *result = 0;
    MAJORMODE *data;

    if (n == 0) {
	result = bp->b_values.bv;
    } else if ((data = bp->majr) != 0) {
	MINORMODE *sm = data->sm;
	while (n-- > 0) {
	    if ((sm = sm->sm_next) == 0) {
		break;
	    } else if (n == 0) {
		result = sm->sm_vals.bv;
		break;
	    }
	}
    }
    return (result);
}

struct VAL *
get_submode_valx(BUFFER *bp, int n, int *m)
{
    struct VAL *result = 0;
    int next = *m + 1;

    if (next != n) {
	if ((result = get_submode_vals(bp, next)) == 0) {
	    next = 0;
	    if (next != n) {
		result = get_submode_vals(bp, next);
	    }
	}

    }
    *m = next;
    return (result);
}

/*
 * Look in the submode's list of qualifiers, e.g., for "group" or "name".
 */
static int
ok_subqual(MAJORMODE * ptr, char *name)
{
    VALARGS args;
    int j;

    if ((j = lookup_valnames(name, q_valnames)) >= 0) {
	args.names = q_valnames;
	args.local = ptr->mq.qv;
	args.global = global_m_values.mv;
    } else {
	return FALSE;
    }

    args.names += j;
    args.global +=j;
    args.local += j;

    return adjvalueset(name, TRUE, TRUE, FALSE, &args);
}

static int
prompt_submode(MAJORMODE * ptr, char **result, int defining)
{
    static TBUFF *cbuf;		/* buffer to receive mode name into */
    const char *rp;
    int status;

    /* prompt the user and get an answer */
    tb_scopy(&cbuf, "");
    *result = 0;
    while ((status = kbd_reply("submode: ",
			       &cbuf,
			       eol_history, '=',
			       KBD_NORMAL,
			       submode_complete)) == TRUE) {
	if ((status = ok_subqual(ptr, tb_values(cbuf))) == TRUE) {
	    continue;
	} else if ((status = ok_submode(tb_values(cbuf))) == TRUE) {
	    *result = tb_values(cbuf);
	    rp = strip_no(*result);
	    status = check_majormode_name(rp, defining);
	}
	break;
    }
    if (status != TRUE
	&& status != SORTOFTRUE)
	mlwarn("[Illegal submode name: %s]", tb_values(cbuf));
    return status;
}

/*
 * Attach a buffer to the given majormode.  Adjust all of the non-local buffer
 * modes to point to the majormode's values where those in turn are local.
 */
static int
attach_mmode(BUFFER *bp, const char *name)
{
    int n;
    VALARGS args;

    if (valid_buffer(bp)) {
	if (bp->majr != 0
	    && strcmp(bp->majr->shortname, name) != 0)
	    (void) detach_mmode(bp, bp->majr->shortname);

	TRACE(("attach_mmode '%s' to '%s'\n", name, bp->b_bname));
	if ((bp->majr = lookup_mm_data(name)) != 0) {
	    struct VAL *mm = get_sm_vals(bp->majr);

	    /* adjust buffer modes */
	    for (n = 0; n < NUM_B_VALUES; n++) {
		if (!is_local_b_val(bp, n)
		    && is_local_val(mm, n)) {
		    make_global_val(bp->b_values.bv, mm, n);
		    if (b_valnames[n].side_effect != 0) {
			args.names = &(b_valnames[n]);
			args.local = &(bp->b_values.bv[n]);
			args.global = &mm[n];
			b_valnames[n].side_effect(bp,
						  &args,
						  TRUE,
						  FALSE);
		    }
		} else if (n == MDDOS
			   && is_local_val(mm, n)
			   && !b_val(bp, n)) {
		    /*
		     * This is a special case - we need a
		     * way to force vile to go back and
		     * strip the ^M's from the end of each
		     * line when reading a .bat file on
		     * a Unix system.
		     */
		    set_rs_crlf(0, 1);
		}
	    }
	    return TRUE;
	}
	return (bp->majr != 0);
    }

    return FALSE;
}

/*
 * Detach a buffer from the given majormode.  Modify the buffer's minor modes
 * to point to global modes where they've been pointed to the majormode's data.
 */
static int
detach_mmode(BUFFER *bp, const char *name)
{
    size_t n;
    MAJORMODE *mp;

    if (valid_buffer(bp)
	&& (mp = bp->majr) != 0
	&& !strcmp(mp->shortname, name)) {
	TRACE(("detach_mmode '%s', given '%s'\n", name, mp->shortname));
	/* readjust the buffer's modes */
	for (n = 0; n < NUM_B_VALUES; n++) {
	    if (!is_local_b_val(bp, n)
		&& is_local_val(get_sm_vals(mp), n)) {
		make_global_b_val(bp, n);
	    }
	}
	relist_settings();
	bp->majr = 0;
	return TRUE;
    }

    return FALSE;
}

static int
enable_mmode(const char *name, int flag)
{
    MAJORMODE_LIST *ptr = lookup_mm_list(name);
    if (ptr != 0
	&& ptr->flag != flag) {
	ptr->flag = flag;
	return TRUE;
    }
    return FALSE;
}

static int
free_majormode(const char *name)
{
    int result = FALSE;
    MAJORMODE *ptr = lookup_mm_data(name);
    size_t j, k;
    int n;
    char temp[NSTRING];
    BUFFER *bp;

    if (ptr != 0) {
	int init = TRUE;
	for (j = 0; my_majormodes[j].shortname != 0; j++) {
	    if (my_majormodes[j].data == ptr) {
		init = my_majormodes[j].init;
		for_each_buffer(bp) {
		    if (detach_mmode(bp, my_majormodes[j].shortname)) {
			set_winflags(TRUE, WFHARD | WFMODE);
		    }
		}
		free_local_vals(m_valnames, major_g_vals, ptr->mm.mv);
		free_local_vals(b_valnames, global_b_values.bv, get_sm_vals(ptr));

		beginDisplay();
		for (k = 0; k < MAX_M_VALUES; k++) {
		    free_val(m_valnames + k, my_majormodes[j].data->mm.mv + k);
		    free(TYPECAST(char, my_majormodes[j].qual[k].name));
		    free(TYPECAST(char, my_majormodes[j].qual[k].shortname));
		}
		for (k = 0; k < MAX_Q_VALUES; k++) {
		    free_val(q_valnames + k, my_majormodes[j].data->mq.qv + k);
		    free(TYPECAST(char, my_majormodes[j].subq[k].name));
		    free(TYPECAST(char, my_majormodes[j].subq[k].shortname));
		}
		free_sm_vals(ptr);
		free(ptr->shortname);
		free(ptr->longname);
		free(ptr);
		endofDisplay();

		do {
		    my_majormodes[j] = my_majormodes[j + 1];
		} while (my_majormodes[j++].shortname != 0);
		break;
	    }
	}
	if (my_mode_list != all_modes && !init) {
	    j = count_modes();
	    j = remove_per_major(j, majorname(temp, name, FALSE));
	    j = remove_per_major(j, majorname(temp, name, TRUE));
	    for (n = 0; n < MAX_M_VALUES; n++) {
		j = remove_per_major(j,
				     per_major(temp, name, n, TRUE));
		j = remove_per_major(j,
				     per_major(temp, name, n, FALSE));
	    }
	}
	if (major_valnames != 0) {
	    for (n = 0; major_valnames[n].name != 0; n++) {
		if (!strcmp(name, major_valnames[n].shortname)) {
		    beginDisplay();
		    free(TYPECAST(char, major_valnames[n].name));
		    free(TYPECAST(char, major_valnames[n].shortname));
		    endofDisplay();
		    while (major_valnames[n].name != 0) {
			major_valnames[n] = major_valnames[n + 1];
			n++;
		    }
		    break;
		}
	    }
	}
	blist_reset(&majormode_blist, my_majormodes);
	compute_majormodes_order();
	result = TRUE;
    }
    return result;
}

static void
init_my_mode_list(void)
{
    if (my_mode_list == 0) {
	my_mode_list = TYPECAST(const char *, all_modes);
	blist_reset(&blist_my_mode_list, my_mode_list);
    }
}

static size_t
extend_mode_list(size_t increment)
{
    size_t j, k;

    beginDisplay();

    j = count_modes();
    k = increment + j + 1;

    TRACE(("extend_mode_list from %d by %d\n", (int) j, (int) increment));

    if (my_mode_list == all_modes) {
	my_mode_list = typeallocn(const char *, k);
	memcpy(TYPECAST(char *, my_mode_list), all_modes, (j + 1) * sizeof(*my_mode_list));
    } else {
	my_mode_list = typereallocn(const char *, TYPECAST(char *,
							   my_mode_list), k);
    }
    blist_my_mode_list.theList = my_mode_list;
    check_my_varmodes(k);
    endofDisplay();

    return j;
}

static struct VAL *
extend_VAL_array(struct VAL *ptr, size_t item, size_t len)
{
    size_t j, k;

    TRACE(("extend_VAL_array %p item %ld of %ld\n", ptr, (long) item, (long) len));

    if (ptr == 0) {
	beginDisplay();
	ptr = typeallocn(struct VAL, len + 1);
	endofDisplay();
    } else {
	beginDisplay();
	ptr = typereallocn(struct VAL, ptr, len + 1);
	endofDisplay();

	if (ptr != 0) {
	    for (j = k = 0; j < len; j++) {
		k = (j >= item) ? j + 1 : j;
		ptr[k] = ptr[j];
		make_local_val(ptr, k);
	    }
	}
    }
    if (ptr != 0) {
	make_local_val(ptr, item);
	make_local_val(ptr, len);
	ptr[item].v.i = FALSE;
    }
    return ptr;
}

static void
set_qualifier(const struct VALNAMES *names,
	      struct VAL *values,
	      const char *s,
	      int n)
{
    free_val(names, values);
    switch (names->type) {
    case VALTYPE_BOOL:
    case VALTYPE_ENUM:
    case VALTYPE_INT:
	values->v.i = n;
	break;
    case VALTYPE_STRING:
	values->v.p = strmalloc(s);
	break;
    case VALTYPE_REGEX:
	values->v.r = new_regexval(s, TRUE);
	break;
    }
    make_local_val(values, 0);
}

static void
reset_qualifier(const struct VALNAMES *names, struct VAL *values)
{
    set_qualifier(names, values, "", 0);
}

/*
 * Reset/initialize all of the qualifiers.  We will use any that become set as
 * parameters for the current submode operation.
 */
static void
reset_sm_qualifiers(MAJORMODE * ptr)
{
    int k;
    for (k = 0; k < MAX_Q_VALUES; k++)
	reset_qualifier(q_valnames + k, ptr->mq.qv + k);
}

/*
 * Buffer-animation for [Major Modes]
 */
#if OPT_UPBUFF
static int
show_majormodes(BUFFER *bp)
{
    b_clr_obsolete(bp);
    return list_majormodes(FALSE, 1);
}

static void
relist_majormodes(void)
{
    update_scratch(MAJORMODES_BufName, show_majormodes);
}
#endif /* OPT_UPBUFF */

static int
show_active_majormodes(int nflag)
{
    int n;
    for (n = 0; major_valnames[n].name != 0; n++) {
	make_local_val(major_g_vals, n);
	major_g_vals[n].vp->i = my_majormodes[n].flag;
    }
    return listvalueset("Majormodes", nflag, FALSE, major_valnames,
			major_g_vals, (struct VAL *) 0);
}

/* list the current modes into the current buffer */
/* ARGSUSED */
static void
makemajorlist(int local, void *ptr GCC_UNUSED)
{
    int j;
    int nflag;
    MAJORMODE *data;
    MINORMODE *vals;

    if (my_majormodes != 0) {
	unsigned count = (unsigned) count_majormodes();
	if (show_active_majormodes(0))
	    bputc('\n');
	for (j = 0; my_majormodes[j].shortname != 0; j++) {
	    if (local)
		TheMajor = my_majormodes[j].shortname;
	    data = my_majormodes[j].data;

	    bprintf("--- \"%s\" majormode settings ",
		    my_majormodes[j].shortname);
	    bpadc('-', term.cols - 12 - DOT.o);
	    bprintf("(%d:%u)",
		    find_majormode_order(j) + 1,
		    count);
	    bpadc('-', term.cols - DOT.o);
	    bputc('\n');

	    nflag = listvalueset("Qualifier", FALSE, TRUE,
				 m_valnames,
				 data->mm.mv,
				 data->mm.mv);
	    for (vals = data->sm; vals != 0; vals = vals->sm_next) {
		char *group = vals->sm_name;
		char *name;

		beginDisplay();
		name = typeallocn(char, 80 + strlen(group));
		endofDisplay();

		if (name != 0) {
		    if (*group)
			lsprintf(name, "Buffer (\"%s\" group)", group);
		    else
			strcpy(name, "Buffer");
		    nflag = listvalueset(name, nflag, TRUE,
					 b_valnames,
					 vals->sm_vals.bv,
					 global_b_values.bv);
		    beginDisplay();
		    free(name);
		    endofDisplay();
		}
	    }
	    if (my_majormodes[j + 1].data)
		bputc('\n');
	}
    }
    TheMajor = 0;
}

/* ARGSUSED */
int
list_majormodes(int f, int n GCC_UNUSED)
{
    WINDOW *wp = curwp;
    int s;

    TRACE((T_CALLED "list_majormodes(f=%d)\n", f));

    s = liststuff(MAJORMODES_BufName, FALSE, makemajorlist, f, (void *) wp);
    /* back to the buffer whose modes we just listed */
    if (swbuffer(wp->w_bufp))
	curwp = wp;

    returnCode(s);
}

int
alloc_mode(const char *shortname, int predef)
{
    size_t j = 0, k;
    int n;
    int status = TRUE;
    char longname[NSTRING];
    char temp[NSTRING];
    static struct VAL *new_vals;

    TRACE((T_CALLED "alloc_mode(%s,%d)\n", shortname, predef));
    if (major_valnames == 0) {
	beginDisplay();
	major_valnames = typecallocn(struct VALNAMES, 2);
	endofDisplay();
	j = 0;
	k = 1;
    } else {
	k = count_majormodes();
	beginDisplay();
	major_valnames = typereallocn(struct VALNAMES, major_valnames, k + 2);
	endofDisplay();
	if (major_valnames != 0) {
	    for (j = k++; j != 0; j--) {
		major_valnames[j] = major_valnames[j - 1];
		if (strcmp(major_valnames[j - 1].shortname, shortname) < 0) {
		    break;
		}
	    }
	}
    }

    if (major_valnames == 0)
	returnCode(FALSE);

    (void) majorname(longname, shortname, TRUE);
    major_valnames[j].name = strmalloc(longname);
    major_valnames[j].shortname = strmalloc(shortname);
    major_valnames[j].type = VALTYPE_MAJOR;
    major_valnames[j].side_effect = chgd_win_mode;

    if (major_valnames[j].name == 0
	|| major_valnames[j].shortname == 0) {
	do {
	    major_valnames[j] = major_valnames[j + 1];
	    ++j;
	} while (major_valnames[j].name != 0);
	returnCode(FALSE);
    }

    memset(major_valnames + k, 0, sizeof(*major_valnames));

    /* build arrays needed for 'find_mode()' bookkeeping */
    if ((new_vals = extend_VAL_array(major_g_vals, j, k)) == 0)
	returnCode(FALSE);
    major_g_vals = new_vals;

    if ((new_vals = extend_VAL_array(major_l_vals, j, k)) == 0)
	returnCode(FALSE);
    major_l_vals = new_vals;

    if (my_majormodes == 0) {
	beginDisplay();
	my_majormodes = typecallocn(MAJORMODE_LIST, 2);
	endofDisplay();
	j = 0;
	k = 1;
    } else {
	k = count_majormodes();
	beginDisplay();
	my_majormodes = typereallocn(MAJORMODE_LIST, my_majormodes, k + 2);
	endofDisplay();
	for (j = k++; j != 0; j--) {
	    my_majormodes[j] = my_majormodes[j - 1];
	    if (strcmp(my_majormodes[j - 1].shortname, shortname) < 0) {
		break;
	    }
	}
    }
    blist_reset(&majormode_blist, my_majormodes);

    if (my_majormodes == 0)
	returnCode(FALSE);

    /* allocate the names for the major mode */
    beginDisplay();

    my_majormodes[j].shortname = strmalloc(shortname);
    my_majormodes[j].longname = strmalloc(longname);

    my_majormodes[j].init = predef;
    my_majormodes[j].flag = TRUE;

    if ((my_majormodes[j].data = typecalloc(MAJORMODE)) != 0) {
	my_majormodes[j].data->shortname = my_majormodes[j].shortname;
	my_majormodes[j].data->longname = my_majormodes[j].longname;

	memset(my_majormodes + k, 0, sizeof(*my_majormodes));
    }

    endofDisplay();

    if (my_majormodes[j].shortname == 0
	|| my_majormodes[j].longname == 0
	|| my_majormodes[j].data == 0) {
	beginDisplay();
	FreeIfNeeded(my_majormodes[j].data);
	FreeIfNeeded(my_majormodes[j].longname);
	endofDisplay();
	do {
	    my_majormodes[j] = my_majormodes[j + 1];
	    ++j;
	} while (my_majormodes[j].shortname != 0);
	returnCode(FALSE);
    }

    /* copy array to get types, then overwrite the name-pointers */
    memcpy(my_majormodes[j].subq, q_valnames, sizeof(q_valnames));
    for (k = 0; k < MAX_Q_VALUES; k++) {
	reset_qualifier(q_valnames + k, my_majormodes[j].data->mq.qv + k);

	my_majormodes[j].subq[k].name =
	    strmalloc(q_valnames[k].name);
	my_majormodes[j].subq[k].shortname =
	    strmalloc(q_valnames[k].shortname);

	if (my_majormodes[j].subq[k].name == 0
	    || my_majormodes[j].subq[k].shortname == 0) {
	    free_majormode(shortname);
	    returnCode(FALSE);
	}
    }

    init_sm_vals(get_sm_vals(my_majormodes[j].data));

    /* copy array to get types, then overwrite the name-pointers */
    memcpy(my_majormodes[j].qual, m_valnames, sizeof(m_valnames));
    for (k = 0; k < MAX_M_VALUES; k++) {
	reset_qualifier(m_valnames + k, my_majormodes[j].data->mm.mv + k);

	my_majormodes[j].qual[k].name =
	    strmalloc(per_major(temp, shortname, k, TRUE));
	my_majormodes[j].qual[k].shortname =
	    strmalloc(per_major(temp, shortname, k, FALSE));

	if (my_majormodes[j].qual[k].name == 0
	    || my_majormodes[j].qual[k].shortname == 0) {
	    free_majormode(shortname);
	    returnCode(FALSE);
	}
    }

    /*
     * Create the majormode-specific names.  If this is predefined, we
     * already had mktbls do this.
     */
    if (!predef) {
	j = extend_mode_list((MAX_M_VALUES + 2) * 2);
	j = insert_per_major(j, majorname(longname, shortname, FALSE));
	j = insert_per_major(j, majorname(longname, shortname, TRUE));
	for (n = 0; n < MAX_M_VALUES; n++) {
	    j = insert_per_major(j, per_major(temp, shortname, n, TRUE));
	    j = insert_per_major(j, per_major(temp, shortname, n, FALSE));
	}
    }

    compute_majormodes_order();
    returnCode(status);
}

/* ARGSUSED */
int
define_mode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    char *name;
    int status;

    if ((status = prompt_majormode(&name, TRUE)) == TRUE) {
	TRACE(("define majormode:%s\n", name));
	status = alloc_mode(name, FALSE);
	relist_settings();
	relist_majormodes();
    } else if (status == SORTOFTRUE) {
	status = TRUE;		/* don't complain if it's already true */
    }
    return status;
}

static int
do_a_submode(int defining)
{
    char *name;
    char *subname;
    int status;
    MAJORMODE *ptr;
    VALARGS args;
    int j;
    size_t k;
    int qualifier = FALSE;
    char temp[NSTRING];
    const char *rp;

    if ((status = prompt_majormode(&name, FALSE)) != TRUE)
	return status;

    ptr = lookup_mm_data(name);
    reset_sm_qualifiers(ptr);

    if ((status = prompt_submode(ptr, &subname, TRUE)) != TRUE) {
	reset_sm_qualifiers(ptr);
	return status;
    }

    rp = strip_no(subname);
    if ((j = lookup_valnames(rp, m_valnames)) >= 0) {
	qualifier = TRUE;
	args.names = m_valnames;
	args.local = ptr->mm.mv;
	args.global = global_m_values.mv;
    } else if ((j = lookup_valnames(rp, b_valnames)) >= 0) {
	args.names = b_valnames;
	args.local = get_sm_vals(ptr);
	args.global = defining ? args.local : global_b_values.bv;
    } else {
	mlwarn("[BUG: no such submode: %s]", rp);
	reset_sm_qualifiers(ptr);
	return FALSE;
    }

    args.names += j;
    args.global +=j;
    args.local += j;

    /*
     * We store submodes in the majormode as local values.
     */
    status = adjvalueset(subname, TRUE, defining, FALSE, &args);

    /*
     * Check if we deleted one of the qualifiers, since there's no global
     * value to inherit back to, we'll have to ensure there's valid data.
     */
    if (status == TRUE
	&& qualifier
	&& !defining) {
	reset_qualifier(args.names, args.global);
    }

    if (status == TRUE
	&& !qualifier) {
	if (defining && found_per_submode(name, j)) {
	    TRACE(("submode names for %d present\n", j)) /*EMPTY */ ;
	} else if (defining) {
	    TRACE(("construct submode names for %d\n", j));
	    k = extend_mode_list(2);
	    k = insert_per_major(k,
				 per_submode(temp, name, j, TRUE));
	    (void) insert_per_major(k,
				    per_submode(temp, name, j, FALSE));
	} else {
	    TRACE(("destroy submode names for %d\n", j));
	    k = count_modes();
	    k = remove_per_major(k,
				 per_submode(temp, name, j, TRUE));
	    (void) remove_per_major(k,
				    per_submode(temp, name, j, FALSE));
	}
    }

    /* FIXME: remember to adjust all buffers that used this mode, in
     * case we make a minor mode part-of or removed from the major mode.
     */
    relist_settings();
    relist_majormodes();
    reset_sm_qualifiers(ptr);
    return status;
}

/* ARGSUSED */
int
define_submode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return do_a_submode(TRUE);
}

/* ARGSUSED */
int
remove_submode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return do_a_submode(FALSE);
}

/* ARGSUSED */
int
remove_mode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    char *name;
    int status;

    if ((status = prompt_majormode(&name, FALSE)) == TRUE) {
	if ((status = !predef_majormode(name)) == TRUE) {
	    TRACE(("remove majormode:%s\n", name));
	    free_majormode(name);
	    relist_settings();
	    relist_majormodes();
	} else {
	    mlwarn("[This is a predefined mode: %s]", name);
	}
    } else if (status == SORTOFTRUE) {
	status = TRUE;
    }
    return status;
}

#if !(OPT_CASELESS || OPT_VMS_PATH)
/*
 * For the given majormode (by index into my_majormodes[]), return the
 * corresponding buffer mode value.
 */
static int
get_sm_b_val(int n, int m)
{
    struct VAL *bv = get_sm_vals(my_majormodes[n].data);
    return (bv[m].vp->i);
}
#endif

/*
 * For the given majormode (by index into my_majormodes[]), return the
 * corresponding buffer mode value.
 */
static regexp *
get_sm_rexp(int n, int m)
{
    struct VAL *mv = get_sm_vals(my_majormodes[n].data);

    if (mv[m].vp != 0
	&& mv[m].vp->r != 0
	&& mv[m].vp->r->pat != 0
	&& mv[m].vp->r->pat[0] != 0
	&& mv[m].vp->r->reg != 0) {
	TRACE(("get_sm_rexp(%s) %s\n",
	       my_majormodes[n].shortname,
	       mv[m].vp->r->pat));
	return mv[m].vp->r->reg;
    }
    return 0;
}

/*
 * Use a regular expression (normally a suffix, such as ".c") to match the
 * buffer's filename.
 */
static int
test_by_suffix(int n, BUFFER *bp)
{
    int result = -1;

    if (my_majormodes[n].flag) {
	regexp *exp;
	int savecase = ignorecase;
	char *pathname = bp->b_fname;
	char *filename;
	char *suffix;
	TBUFF *savename = 0;
#if OPT_VMS_PATH
	TBUFF *stripname = 0;
#endif

#if OPT_CASELESS || OPT_VMS_PATH
	ignorecase = TRUE;
#else
	ignorecase = get_sm_b_val(n, MDIGNCASE);
#endif
#if OPT_VMS_PATH
	tb_scopy(&stripname, pathname);
	pathname = tb_values(stripname);
	strip_version(pathname);
#endif

	if (((exp = get_sm_rexp(n, VAL_STRIPSUFFIX)) != 0
	     || (exp = b_val_rexp(bp, VAL_STRIPSUFFIX)->reg) != 0)
	    && regexec(exp, pathname, (char *) 0, 0, -1)) {
	    if (tb_scopy(&savename, pathname) != 0) {
		strcpy(tb_values(savename) + (exp->startp[0] - pathname),
		       exp->endp[0]);
		pathname = tb_values(savename);
	    }
	}
	filename = pathleaf(pathname);
	suffix = strchr(filename, '.');
#if OPT_VMS_PATH
	if (suffix != 0 && suffix[1] == 0) {
	    *suffix = 0;
	    suffix = 0;
	}
#endif

	if ((exp = get_mm_rexp(n, MVAL_MODE_PATHNAME)) != 0
	    && regexec(exp, pathname, (char *) 0, 0, -1)) {
	    TRACE(("test_by_pathname(%s) %s\n",
		   pathname,
		   my_majormodes[n].shortname));
	    result = n;
	} else if ((exp = get_mm_rexp(n, MVAL_MODE_FILENAME)) != 0
		   && regexec(exp, filename, (char *) 0, 0, -1)) {
	    TRACE(("test_by_filename(%s) %s %s\n",
		   pathname,
		   filename,
		   my_majormodes[n].shortname));
	    result = n;
	} else if (!isShellOrPipe(pathname)
		   && suffix != 0
		   && (exp = get_mm_rexp(n, MVAL_MODE_SUFFIXES)) != 0
		   && regexec(exp, suffix, (char *) 0, 0, -1)) {
	    TRACE(("test_by_suffixes(%s) %s %s\n",
		   pathname,
		   suffix,
		   my_majormodes[n].shortname));
	    result = n;
	}
	ignorecase = savecase;
	tb_free(&savename);
#if OPT_VMS_PATH
	tb_free(&stripname);
#endif
    }
    return result;
}

static LINE *
get_preamble(BUFFER *bp)
{
    if (!is_empty_buf(bp)) {
	LINE *lp = lforw(buf_head(bp));
	if (lisreal(lp))
	    return lp;
    }
    return 0;
}

/*
 * Match the first line of the buffer against a regular expression.
 */
static int
test_by_preamble(int n, BUFFER *bp GCC_UNUSED, LINE *lp)
{
    int result = -1;

    if (lp != 0
	&& my_majormodes[n].flag) {
	regexp *exp = get_mm_rexp(n, MVAL_PREAMBLE);
	int savecase = ignorecase;
#if OPT_CASELESS || OPT_VMS_PATH
	ignorecase = TRUE;
#else
	ignorecase = get_sm_b_val(n, MDIGNCASE);
#endif
	if (exp != 0
	    && lregexec(exp, lp, 0, llength(lp))) {
	    TRACE(("test_by_preamble(%s) %s\n",
		   bp->b_fname,
		   my_majormodes[n].shortname));
	    result = n;
	}
	ignorecase = savecase;
    }
    return result;
}

static int
need_suffix_and_preamble(int n)
{
    if (get_mm_number(n, MVAL_QUALIFIERS) == MMQ_ALL
	&& (get_mm_rexp(n, MVAL_MODE_PATHNAME) != 0
	    || get_mm_rexp(n, MVAL_MODE_FILENAME) != 0
	    || get_mm_rexp(n, MVAL_MODE_SUFFIXES) != 0)
	&& get_mm_rexp(n, MVAL_PREAMBLE) != 0) {
	TRACE(("need both suffix/preamble for %s\n",
	       my_majormodes[n].shortname));
	return TRUE;
    }
    return FALSE;
}

void
infer_majormode(BUFFER *bp)
{
    static int level;

    TRACE((T_CALLED "infer_majormode(%s)\n", bp->b_bname));

    if (level++) {
	;
    } else if (my_majormodes != 0
	       && majormodes_order != 0
	       && !b_is_directory(bp)
	       && bp->b_fname != 0
	       && !(is_internalname(bp->b_fname)
		    && !eql_bname(bp, STDIN_BufName)
		    && !eql_bname(bp, OUTPUT_BufName))) {
	int n, m;
	int result = -1;
	LINE *lp = get_preamble(bp);

	did_attach_mmode = FALSE;
	if (bp == curbp		/* otherwise we cannot script it */
	    && run_a_hook(&majormodehook) == TRUE
	    && did_attach_mmode) {
	    ;
	} else {
	    for (m = 0; (n = majormodes_order[m]) >= 0; m++) {
		if (need_suffix_and_preamble(n)) {
		    if (test_by_suffix(n, bp) >= 0
			&& test_by_preamble(n, bp, lp) >= 0) {
			TPRINTF(("matched preamble and suffix of %s\n", bp->b_bname));
			result = n;
			break;
		    }
		} else if (test_by_suffix(n, bp) >= 0) {
		    TPRINTF(("matched suffix of %s\n", bp->b_bname));
		    result = n;
		    break;
		} else if (test_by_preamble(n, bp, lp) >= 0) {
		    result = n;
		    TPRINTF(("matched preamble of %s\n", bp->b_bname));
		    break;
		}
	    }
	    if (result >= 0) {
		TPRINTF(("...inferred majormode %s\n", my_majormodes[result].shortname));
		attach_mmode(bp, my_majormodes[result].shortname);
	    }
	}
    }
    --level;

    returnVoid();
}

void
set_submode_val(const char *name, int n, int value)
{
    MAJORMODE *p;

    TRACE((T_CALLED "set_submode_val(%s, %d, %d)\n", name, n, value));
    if ((p = lookup_mm_data(name)) != 0) {
	struct VAL *q = get_sm_vals(p);
	q[n].v.i = value;
	make_local_val(q, n);
    }
    returnVoid();
}

void
set_submode_txt(const char *name, int n, const char *value)
{
    MAJORMODE *p;

    TRACE((T_CALLED "set_submode_txt(%s, %d, %s)\n", name, n, value));
    if ((p = lookup_mm_data(name)) != 0) {
	struct VAL *q = get_sm_vals(p);
	q[n].v.p = strmalloc(value);
	make_local_val(q, n);
    }
    returnVoid();
}

void
set_majormode_rexp(const char *name, int n, const char *r)
{
    MAJORMODE *p;

    TRACE((T_CALLED "set_majormode_rexp(%s, %d, %s)\n", name, n, r));
    if ((p = lookup_mm_data(name)) != 0)
	set_qualifier(m_valnames + n, p->mm.mv + n, r, 0);
    returnVoid();
}

/*ARGSUSED*/
int
chgd_mm_order(BUFFER *bp GCC_UNUSED,
	      VALARGS * args GCC_UNUSED,
	      int glob_vals GCC_UNUSED,
	      int testing GCC_UNUSED)
{
    if (!testing) {
	compute_majormodes_order();
	relist_majormodes();
    }
    return TRUE;
}

/*ARGSUSED*/
int
chgd_filter(BUFFER *bp, VALARGS * args GCC_UNUSED, int glob_vals GCC_UNUSED, int testing)
{
    if (!testing) {
	struct VAL *values = args->local;
	BUFFER *bp2;

	if (values->vp->i == FALSE) {
	    if (glob_vals) {
		for_each_buffer(bp2) {
		    free_attribs(bp2);
		}
	    } else {
		free_attribs(bp);
	    }
	}
	set_winflags(glob_vals, WFHARD);
    }
    return TRUE;
}

/*ARGSUSED*/
int
reset_majormode(int f GCC_UNUSED, int n GCC_UNUSED)
{
    if (curbp->majr != 0)
	(void) detach_mmode(curbp, curbp->majr->shortname);
    infer_majormode(curbp);
    set_winflags(TRUE, WFMODE);
    return TRUE;
}

void
set_vilemode(BUFFER *bp)
{
    static const char *my_mode = "vile" MAJOR_SUFFIX;
    VALARGS args;

    if (find_mode(bp, my_mode, FALSE, &args) == TRUE
	&& !b_is_scratch(bp)) {
	(void) set_mode_value(bp, my_mode, FALSE, TRUE, FALSE, &args,
			      (char *) 0);
    }
}
#endif /* OPT_MAJORMODE */

/*--------------------------------------------------------------------------*/

#if OPT_COLOR_SCHEMES
typedef struct {
    char *name;
    UINT code;
    int fcol;			/* foreground color */
    int bcol;			/* background color */
    int ccol;			/* cursor color */
    int attr;			/* bold, reverse, underline, etc. */
    char *list;
} PALETTES;

static UINT current_scheme;
static UINT num_schemes;
static PALETTES *my_schemes;
static FSM_CHOICES *my_scheme_choices;

static int
set_scheme_color(FSM_BLIST * fp, int *d, char *s)
{
#if OPT_ENUM_MODES
    int nval;

    if (isDigit(*s)) {
	if (!string_to_number(s, &nval))
	    return FALSE;
	if (choice_to_name(fp, nval) == 0)
	    nval = ENUM_ILLEGAL;
    } else {
	nval = choice_to_code(fp, s, strlen(s));
    }
    *d = nval;
    return TRUE;
#else
    return string_to_number(s, d);
#endif
}

static void
set_scheme_string(char **d, char *s)
{
    beginDisplay();
    if (*d)
	free(*d);
    *d = s ? strmalloc(s) : 0;
    endofDisplay();
}

/*
 * Find a scheme
 */
static PALETTES *
find_scheme(const char *name)
{
    PALETTES *result = 0, *p;

    if ((p = my_schemes) != 0) {
	while (p->name != 0) {
	    if (!strcmp(p->name, name)) {
		result = p;
		break;
	    }
	    p++;
	}
    }
    return result;
}

static PALETTES *
find_scheme_by_code(UINT code)
{
    PALETTES *result = 0, *p;

    if ((p = my_schemes) != 0) {
	while (p->name != 0) {
	    if (p->code == code) {
		result = p;
		break;
	    }
	    p++;
	}
    }
    return result;
}

/*
 * Update the list of choices for color scheme
 */
static void
update_scheme_choices(void)
{
    int n;

    if (my_schemes != 0) {
	beginDisplay();
	if (my_scheme_choices != 0) {
	    my_scheme_choices = typereallocn(FSM_CHOICES, my_scheme_choices, num_schemes);
	} else {
	    my_scheme_choices = typeallocn(FSM_CHOICES, num_schemes);
	}
	endofDisplay();

	if (my_scheme_choices != 0) {
	    for (n = 0; n < (int) num_schemes; n++) {
		my_scheme_choices[n].choice_name = my_schemes[n].name;
		my_scheme_choices[n].choice_code = my_schemes[n].code;
	    }
	    set_fsm_choice(s_color_scheme, my_scheme_choices);
	}
    }
}

static int
same_string(const char *p, const char *q)
{
    if (p == 0)
	p = "";
    if (q == 0)
	q = "";
    return !strcmp(p, q);
}

/*
 * Set the current color scheme, given a pointer to its attributes
 */
static int
set_current_scheme(PALETTES * p)
{
    PALETTES *q = find_scheme_by_code(current_scheme);

    TRACE((T_CALLED "set_current_scheme()\n"));
    current_scheme = p->code;

    if (p != 0
	&& q != 0
	&& (p->fcol != q->fcol
	    || p->bcol != q->bcol
	    || p->ccol != q->ccol
	    || p->attr != q->attr
	    || !same_string(p->list, q->list))) {

	if (p->list != 0 && p->list[0] != 0)
	    set_palette(p->list);

	set_global_g_val(GVAL_FCOLOR, p->fcol);
	term.setfore(p->fcol);

	set_global_g_val(GVAL_BCOLOR, p->bcol);
	term.setback(p->bcol);

	set_global_g_val(GVAL_CCOLOR, p->ccol);
	term.setccol(p->ccol);

	set_global_g_val(GVAL_VIDEO, p->attr);

	returnCode(TRUE);
    }
    returnCode(FALSE);
}

/*
 * Remove a color scheme, except for the 'default' scheme.
 */
static int
free_scheme(char *name)
{
    PALETTES *p;

    if (strcmp(name, s_default)
	&& (p = find_scheme(name)) != 0) {
	UINT code = p->code;

	TRACE(("free_scheme(%s)\n", name));

	beginDisplay();
	free(p->name);
	if (p->list != 0)
	    free(p->list);
	endofDisplay();

	while (p->name != 0) {
	    p[0] = p[1];
	    p++;
	}
	num_schemes--;
	update_scheme_choices();

	if (code == current_scheme)
	    (void) set_current_scheme(find_scheme(s_default));

	return TRUE;
    }
    TRACE(("cannot free_scheme(%s)\n", name));
    return FALSE;
}

/*
 * Allocate a new scheme
 */
static PALETTES *
alloc_scheme(const char *name)
{
    static UINT code;
    PALETTES *result;

    if ((result = find_scheme(name)) == 0) {
	int len = ++num_schemes;

	beginDisplay();
	if (len == 1) {
	    len = ++num_schemes;
	    my_schemes = typecallocn(PALETTES, len);
	} else {
	    my_schemes = typereallocn(PALETTES, my_schemes, len);
	}
	endofDisplay();

	if (my_schemes == 0) {
	    no_memory("alloc_scheme");
	    return 0;
	}

	len--;			/* point to list-terminator */
	memset(&my_schemes[len], 0, sizeof(PALETTES));
	while (--len > 0) {
	    my_schemes[len] = my_schemes[len - 1];
	    if (my_schemes[len - 1].name != 0
		&& strcmp(my_schemes[len - 1].name, name) < 0)
		break;
	}
	if ((my_schemes[len].name = strmalloc(name)) != 0) {
	    my_schemes[len].code = code++;	/* unique identifier */
	    my_schemes[len].fcol = -1;
	    my_schemes[len].bcol = -1;
	    my_schemes[len].ccol = -1;
	    my_schemes[len].attr = 0;
	    my_schemes[len].list = 0;
	    result = &my_schemes[len];
	    update_scheme_choices();
	}
    }
    return result;
}

static int
scheme_complete(DONE_ARGS)
{
    return kbd_complete(PASS_DONE_ARGS, (const char *) &my_schemes[0],
			sizeof(my_schemes[0]));
}

static int
prompt_scheme_name(char **result, int defining)
{
    static TBUFF *cbuf;		/* buffer to receive mode name into */
    int status;

    /* prompt the user and get an answer */
    tb_scopy(&cbuf, "");
    if ((status = kbd_reply("name: ",
			    &cbuf,
			    eol_history, ' ',
			    KBD_NORMAL,		/* FIXME: KBD_MAYBEC if !defining */
			    (defining || clexec)
			    ? no_completion
			    : scheme_complete)) == TRUE) {
	/* check for legal name (alphanumeric) */
	if ((status = is_identifier(tb_values(cbuf))) != TRUE) {
	    mlwarn("[Not an identifier: %s]", tb_values(cbuf));
	    return status;
	}
	*result = tb_values(cbuf);
	return status;
    }
    return status;
}

/* FIXME: generate this with mktbls? */
/* this table must be sorted, since we do name-completion on it */
/* *INDENT-OFF* */
static const struct VALNAMES scheme_values[] =
{
    { s_bcolor,		s_bcolor,	VALTYPE_ENUM,	0 },
    { s_ccolor,		s_ccolor,	VALTYPE_ENUM,	0 },
    { s_fcolor,		s_fcolor,	VALTYPE_ENUM,	0 },
    { s_palette,	s_palette,	VALTYPE_STRING, 0 },
    { "use",		"use",		VALTYPE_ENUM,	0 },
    { s_video_attrs,	s_video_attrs,	VALTYPE_ENUM,	0 },
    { 0, 0, 0, 0 }
};
/* *INDENT-ON* */

static int
scheme_value_complete(DONE_ARGS)
{
    return kbd_complete(PASS_DONE_ARGS,
			(const char *) &scheme_values[0],
			sizeof(scheme_values[0]));
}

static int
prompt_scheme_value(PALETTES * p)
{
    static TBUFF *cbuf;		/* buffer to receive mode name into */
    PALETTES *q;
    int status;

    /* prompt the user and get an answer */
    tb_scopy(&cbuf, "");
    if ((status = kbd_reply("scheme value: ",
			    &cbuf,
			    eol_history, '=',
			    KBD_NORMAL,		/* FIXME: KBD_MAYBEC if !defining */
			    scheme_value_complete)) == TRUE) {
	char respbuf[NFILEN];
	char *name = tb_values(cbuf);
	int code = *name;
	int eolchar = (code == *s_palette) ? '\n' : ' ';
	int (*complete) (DONE_ARGS) = no_completion;
#if OPT_ENUM_MODES
	FSM_BLIST *fp = 0;
	const struct VALNAMES *names;
	for (code = 0; scheme_values[code].name; code++) {
	    if (!strcmp(name, scheme_values[code].name)) {
		names = &scheme_values[code];
		if (!strcmp("use", scheme_values[code].name))
		    complete = scheme_complete;
		else if (is_fsm(names))
		    complete = fsm_complete;
		fp = valname_to_choices(names);
		break;
	    }
	}
#else
	void *fp = 0;
#endif
	tb_sappend0(&cbuf, " value: ");
	*respbuf = EOS;
	status = kbd_string(name, respbuf, sizeof(respbuf), eolchar,
			    KBD_NORMAL, complete);
	if (status == TRUE) {
	    mktrimmed(respbuf);
	    if (*name == *s_video_attrs) {
		status = set_scheme_color(fp, &(p->attr), respbuf);
	    } else if (*name == *s_bcolor) {
		status = set_scheme_color(fp, &(p->bcol), respbuf);
	    } else if (*name == *s_ccolor) {
		status = set_scheme_color(fp, &(p->ccol), respbuf);
	    } else if (*name == *s_fcolor) {
		status = set_scheme_color(fp, &(p->fcol), respbuf);
	    } else if (*name == *s_palette) {
		set_scheme_string(&(p->list), respbuf);
		return status;
	    } else if (*name == 'u'
		       && (q = find_scheme(respbuf)) != 0) {
		char *newlist = 0;
		if (q->list == 0 || (newlist = strmalloc(q->list)) != 0) {
		    p->fcol = q->fcol;
		    p->bcol = q->bcol;
		    p->ccol = q->ccol;
		    p->attr = q->attr;
		    if (p->list)
			FreeAndNull(p->list);
		    p->list = newlist;
		} else {
		    return no_memory("prompt_scheme_value");
		}
	    }
	}
	if (status == TRUE)
	    return (end_string() == ' ') ? -1 : TRUE;
    }
    return status;
}

#if OPT_UPBUFF
/*ARGSUSED*/
static int
update_schemelist(BUFFER *bp GCC_UNUSED)
{
    return desschemes(FALSE, 1);
}
#endif /* OPT_UPBUFF */

/*
 * Define the default color scheme, based on the current settings of color
 * and $palette.
 */
void
init_scheme(void)
{
    PALETTES *p = alloc_scheme(s_default);
    char *list = tb_values(tb_curpalette);

    p->fcol = -1;
    p->bcol = -1;
    p->ccol = -1;
    if (list != 0)
	p->list = strmalloc(list);
}

/*
 * Define a color scheme, e.g.,
 *	define-color-scheme {name} [fcolor={value}|bcolor={value}|{value}]
 * where the {value}'s are all color names or constants 0..NCOLORS-1.
 */
/*ARGSUSED*/
int
define_scheme(int f GCC_UNUSED, int n GCC_UNUSED)
{
    char *name;
    int status;

    if ((status = prompt_scheme_name(&name, TRUE)) == TRUE) {
	PALETTES *p = alloc_scheme(name);
	while ((status = prompt_scheme_value(p)) < 0)
	    continue;
    }
    update_scratch(COLOR_SCHEMES_BufName, update_schemelist);
    return status;
}

/*
 * Remove a color scheme
 */
/*ARGSUSED*/
int
remove_scheme(int f GCC_UNUSED, int n GCC_UNUSED)
{
    char *name;
    int status;

    if (my_schemes == 0 || my_schemes->name == 0) {
	status = FALSE;
    } else if ((status = prompt_scheme_name(&name, FALSE)) == TRUE) {
	status = free_scheme(name);
    }
    update_scratch(COLOR_SCHEMES_BufName, update_schemelist);
    return status;
}

/*ARGSUSED*/
static void
makeschemelist(int dum1 GCC_UNUSED, void *ptr GCC_UNUSED)
{
    static const char fmt[] = "\n   %s=%s";
    PALETTES *p;
    int num = (num_schemes > 1) ? (num_schemes - 1) : 0;

    if (my_schemes != 0) {
	bprintf("There %s %d color scheme%s defined",
		(num != 1) ? "are" : "is", num, PLURAL(num));

	for (p = my_schemes; p != 0 && p->name != 0; p++) {
	    bprintf("\n\n%s", p->name);
	    bprintf(fmt, s_fcolor, get_color_name(p->fcol));
	    bprintf(fmt, s_bcolor, get_color_name(p->bcol));
	    bprintf(fmt, s_ccolor, get_color_name(p->ccol));
	    bprintf(fmt, s_video_attrs,
		    choice_to_name(&fsm_videoattrs_blist, p->attr));
	    if (p->list != 0)
		bprintf(fmt, s_palette, p->list);
	}
    }
}

/*ARGSUSED*/
int
desschemes(int f GCC_UNUSED, int n GCC_UNUSED)
{
    return liststuff(COLOR_SCHEMES_BufName, FALSE, makeschemelist,
		     0, (void *) 0);
}

int
chgd_scheme(BUFFER *bp GCC_UNUSED, VALARGS * args, int glob_vals, int testing)
{
    if (!testing) {
	PALETTES *p = find_scheme_by_code(args->local->vp->i);
	if (p == 0) {
	    return FALSE;
	} else if (set_current_scheme(p)) {
	    set_winflags(glob_vals, WFHARD | WFCOLR);
	    need_update = TRUE;
	}
    }
    return TRUE;
}
#endif /* OPT_COLOR_SCHEMES */

/*--------------------------------------------------------------------------*/
#if SYS_VMS
const char *
vms_record_format(int code)
{
    return choice_to_name(&fsm_recordformat_blist, code);
}

const char *
vms_record_attrs(int code)
{
    return choice_to_name(&fsm_recordattrs_blist, code);
}
#endif

/*--------------------------------------------------------------------------*/

int
vl_find_mode(const char *name)
{
    return blist_pmatch(&blist_my_mode_list, name, -1);
}

/*--------------------------------------------------------------------------*/

#if NO_LEAKS
void
mode_leaks(void)
{
    TRACE((T_CALLED "mode_leaks()\n"));

    beginDisplay();
#if OPT_COLOR_SCHEMES
    if (my_schemes != 0) {
	int last;
	for (last = 0; my_schemes[last].name != 0; last++) ;
	if (--last >= 0) {
	    while (my_schemes != 0 && my_schemes[last].name != 0) {
		if (!free_scheme(my_schemes[last].name)) {
		    if (last <= 0)
			break;
		    last = 0;
		} else if (last > 0) {
		    last--;
		}
	    }
	}
	if (my_schemes != 0) {	/* it's ok to free the default scheme */
	    FreeAndNull(my_schemes->list);
	    FreeAndNull(my_schemes->name);
	    free(my_schemes);
	}
	FreeAndNull(my_scheme_choices);
    }
#endif

#if OPT_ENUM_MODES && OPT_COLOR
    FreeAndNull(my_colors);
    FreeAndNull(my_hilite);
#endif

#if OPT_EVAL || OPT_MAJORMODE
    free_my_varmodes();
#endif

#if OPT_MAJORMODE
    while (my_majormodes != 0 && my_majormodes->shortname != 0) {
	char temp[NSTRING];
	free_majormode(strcpy(temp, my_majormodes->shortname));
    }
    FreeAndNull(my_majormodes);

    FreeAndNull(major_g_vals);
    FreeAndNull(major_l_vals);
    if (my_mode_list != all_modes
	&& my_mode_list != 0) {
	int j = count_modes();
	while (j > 0)
	    remove_per_major(j--, my_mode_list[0]);
	FreeAndNull(my_mode_list);
    }
    FreeAndNull(major_valnames);
    FreeAndNull(majormodes_order);
#endif
    endofDisplay();

    returnVoid();
}
#endif /* NO_LEAKS */