Source

vhdl / vhdl-mode.el

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
;;; vhdl-mode.el --- major mode for editing VHDL code

;; Copyright (C) 1992-1999, 2000 Free Software Foundation, Inc.

;; Authors:     Reto Zimmermann <reto@gnu.org>
;;              Rodney J. Whitby <software.vhdl-mode@rwhitby.net>
;; Maintainer:  Reto Zimmermann <reto@gnu.org>
;; Version:     3.31.20
;; RCS:         $Id$
;; Keywords:    languages vhdl
;; WWW:         http://opensource.ethz.ch/emacs/vhdl-mode.html


;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Commentary:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; This package provides an Emacs major mode for editing VHDL code.
;; It includes the following features:

;;   - Syntax highlighting
;;   - Indentation
;;   - Template insertion (electrification)
;;   - Insertion of file headers
;;   - Insertion of user-specified models
;;   - Port translation / test bench generation
;;   - Sensitivity list updating
;;   - File browser
;;   - Design hierarchy browser
;;   - Source file compilation (syntax analysis)
;;   - Makefile generation
;;   - Code hiding
;;   - Word/keyword completion
;;   - Block commenting
;;   - Code fixing/alignment/beautification
;;   - Postscript printing
;;   - VHDL'87/'93 and VHDL-AMS supported
;;   - Comprehensive menu
;;   - Fully customizable
;;   - Works under GNU Emacs (recommended) and XEmacs

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Documentation

;; See comment string of function `vhdl-mode' or type `C-c C-h' in Emacs.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Emacs Versions

;; supported: GNU Emacs 20.X, XEmacs 20.X/21.X
;; tested on: GNU Emacs 20.4, XEmacs 21.1 (marginally)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Installation

;; Prerequisites:  GNU Emacs 20.X, XEmacs 20.X/21.X.

;; Put `vhdl-mode.el' into the `site-lisp' directory of your Emacs installation
;; or into an arbitrary directory that is added to the load path by the
;; following line in your Emacs start-up file `.emacs':

;;   (setq load-path (cons (expand-file-name "<directory-name>") load-path))

;; If you already have the compiled `vhdl-mode.elc' file, put it in the same
;; directory.  Otherwise, byte-compile the source file:
;;   Emacs:  M-x byte-compile-file  ->  vhdl-mode.el
;;   Unix:   emacs -batch -q -no-site-file -f batch-byte-compile vhdl-mode.el

;; Add the following lines to the `site-start.el' file in the `site-lisp'
;; directory of your Emacs installation or to your Emacs start-up file `.emacs'
;; (not required in Emacs 20.X):

;;   (autoload 'vhdl-mode "vhdl-mode" "VHDL Mode" t)
;;   (setq auto-mode-alist (cons '("\\.vhdl?\\'" . vhdl-mode) auto-mode-alist))

;; More detailed installation instructions are included in the official
;; VHDL Mode distribution.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Acknowledgements

;; Electrification ideas by Bob Pack <rlpst@cislabs.pitt.edu>
;; and Steve Grout.

;; Fontification approach suggested by Ken Wood <ken@eda.com.au>.
;; Ideas about alignment from John Wiegley <johnw@gnu.org>.

;; Many thanks to all the users who sent me bug reports and enhancement
;; requests.
;; Thanks to Colin Marquardt for his serious beta testing, his innumerable
;; enhancement suggestions and the fruitful discussions.
;; Thanks to Dan Nicolaescu for reviewing the code and for his valuable hints.
;; Thanks to Ulf Klaperski for the indentation speedup hint.

;; Special thanks go to Wolfgang Fichtner and the crew from the Integrated
;; Systems Laboratory, Swiss Federal Institute of Technology Zurich, for
;; giving me the opportunity to develop this code.
;; This work has been funded in part by MICROSWISS, a Microelectronics Program
;; of the Swiss Government.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;; Code:

(defconst vhdl-version "3.31.20"
  "VHDL Mode version number.")

;; XEmacs handling
(defconst vhdl-xemacs (string-match "XEmacs" emacs-version)
  "Non-nil if XEmacs is used.")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; help function for user options
(defun vhdl-custom-set (variable value &rest functions)
  "Set variables as in `custom-set-default' and call FUNCTIONS afterwards."
  (if (fboundp 'custom-set-default)
      (custom-set-default variable value)
    (set-default variable value))
  (while functions
    (when (fboundp (car functions)) (funcall (car functions)))
    (setq functions (cdr functions))))

(defun vhdl-widget-directory-validate (widget)
  "Check that the value of WIDGET is a valid directory entry (i.e. ends with
'/' or is empty)."
  (let ((val (widget-value widget)))
    (unless (string-match "^\\(\\|.*/\\)$" val)
      (widget-put widget :error "Invalid directory entry: must end with '/'")
      widget)))

;; help string for user options
(defconst vhdl-name-doc-string "

FROM REGEXP is a regular expression matching the original name:
  \".*\"       matches the entire string
  \"\\(...\\)\"  matches a substring
TO STRING specifies the string to be inserted as new name:
  \"\\&\"  means substitute entire matched text
  \"\\N\"  means substitute what matched the Nth \"\\(...\\)\"
Examples:
  \".*\"           \"\\&\"    inserts original string
  \".*\"           \"\\&_i\"  attaches \"_i\" to original string
  \"\\(.*\\)_[io]$\" \"\\1\"    strips off \"_i\" or \"_o\" from original string
  \".*\"           \"foo\"   inserts constant string \"foo\"
  \".*\"           \"\"      inserts empty string")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User variables

(defgroup vhdl nil
  "Customizations for VHDL Mode."
  :prefix "vhdl-"
  :group 'languages
;  :version "20.4"  ; comment out for XEmacs
  )

(defgroup vhdl-mode nil
  "Customizations for modes."
  :group 'vhdl)

(defcustom vhdl-electric-mode t
  "*Non-nil enables electrification (automatic template generation).
If nil, template generators can still be invoked through key bindings and
menu.  Is indicated in the modeline by \"/e\" after the mode name and can be
toggled by `\\[vhdl-electric-mode]'."
  :type 'boolean
  :group 'vhdl-mode)

(defcustom vhdl-stutter-mode t
  "*Non-nil enables stuttering.
Is indicated in the modeline by \"/s\" after the mode name and can be toggled
by `\\[vhdl-stutter-mode]'."
  :type 'boolean
  :group 'vhdl-mode)

(defcustom vhdl-indent-tabs-mode nil
  "*Non-nil means indentation can insert tabs.
Overrides local variable `indent-tabs-mode'."
  :type 'boolean
  :group 'vhdl-mode)


(defgroup vhdl-compile nil
  "Customizations for compilation."
  :group 'vhdl)

(defcustom vhdl-compiler-alist
  '(
    ;; Cadence Leapfrog: cv -file test.vhd
    ;; duluth: *E,430 (test.vhd,13): identifier (POSITIV) is not declared
    ("Cadence Leapfrog" "cv" "-work \\1 -file" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "leapfrog"
     ("duluth: \\*E,[0-9]+ (\\(.+\\),\\([0-9]+\\)):" 1 2) ("" 0)
     ("\\1/entity" "\\2/\\1" "\\1/configuration"
      "\\1/package" "\\1/body" downcase))
    ;; Cadence Affirma NC vhdl: ncvhdl test.vhd
    ;; ncvhdl_p: *E,IDENTU (test.vhd,655|25): identifier
    ;; (PLL_400X_TOP) is not declared [10.3].
    ("Cadence NC" "ncvhdl" "-work \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "ncvhdl"
     ("ncvhdl_p: \\*E,\\w+ (\\(.+\\),\\([0-9]+\\)|[0-9]+):" 1 2) ("" 0)
     nil)
    ;; Ikos Voyager: analyze test.vhd
    ;; analyze sdrctl.vhd
    ;; E L4/C5:        this library unit is inaccessible
    ("Ikos" "analyze" "-l \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "ikos"
     ("E L\\([0-9]+\\)/C[0-9]+:" 0 1)
     ("^analyze +\\(.+ +\\)*\\(.+\\)$" 2)
     nil)
    ;; ModelSim, Model Technology: vcom test.vhd
    ;; ERROR: test.vhd(14): Unknown identifier: positiv
    ;; WARNING[2]: test.vhd(85): Possible infinite loop
    ("ModelSim" "vcom" "-93 -work \\1" "make" "-f \\1"
     nil "vlib \\1; vmap \\2 \\1" "./" "work/" "Makefile" "modelsim"
     ("\\(ERROR\\|WARNING\\)[^:]*: \\(.+\\)(\\([0-9]+\\)):" 2 3) ("" 0)
     ("\\1/_primary.dat" "\\2/\\1.dat" "\\1/_primary.dat"
      "\\1/_primary.dat" "\\1/body.dat" downcase))
    ;; ProVHDL, Synopsys LEDA: provhdl -w work -f test.vhd
    ;; file:line: message
    ("LEDA ProVHDL" "provhdl" "-w \\1 -f" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "provhdl"
     ("\\([^ \t\n]+\\):\\([0-9]+\\): " 1 2) ("" 0)
     ("ENTI/\\1.vif" "ARCH/\\1-\\2.vif" "CONF/\\1.vif"
      "PACK/\\1.vif" "BODY/BODY-\\1.vif" upcase))
    ;; QuickHDL, Mentor Graphics: qvhcom test.vhd
    ;; ERROR: test.vhd(24): near "dnd": expecting: END
    ;; WARNING[4]: test.vhd(30): A space is required between ...
    ("QuickHDL" "qvhcom" "-work \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "quickhdl"
     ("\\(ERROR\\|WARNING\\)[^:]*: \\(.+\\)(\\([0-9]+\\)):" 2 3) ("" 0)
     ("\\1/_primary.dat" "\\2/\\1.dat" "\\1/_primary.dat"
      "\\1/_primary.dat" "\\1/body.dat" downcase))
    ;; Savant: scram -publish-cc test.vhd
    ;; cla.vhdl:87: _set_passed_through_out_port(IIR_Boolean) not defined for
    ("Savant" "scram" "-publish-cc -design-library-name \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work._savant_lib/" "Makefile" "savant"
     ("\\([^ \t\n]+\\):\\([0-9]+\\): " 1 2) ("" 0)
     ("\\1_entity.vhdl" "\\2_secondary_units._savant_lib/\\2_\\1.vhdl"
      "\\1_config.vhdl" "\\1_package.vhdl"
      "\\1_secondary_units._savant_lib/\\1_package_body.vhdl" downcase))
    ;; Synopsys, VHDL Analyzer (sim): vhdlan -nc test.vhd
    ;; **Error: vhdlan,703 test.vhd(22): OTHERS is not legal in this context.
    ("Synopsys" "vhdlan" "-nc -work \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "synopsys"
     ("\\*\\*Error: vhdlan,[0-9]+ \\(.+\\)(\\([0-9]+\\)):" 1 2) ("" 0)
     ("\\1.sim" "\\2__\\1.sim" "\\1.sim" "\\1.sim" "\\1__.sim" upcase))
    ;; Synopsys, VHDL Analyzer (syn): vhdlan -nc -spc test.vhd
    ;; **Error: vhdlan,703 test.vhd(22): OTHERS is not legal in this context.
    ("Synopsys Design Compiler" "vhdlan" "-nc -spc -work \\1" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "synopsys_dc"
     ("\\*\\*Error: vhdlan,[0-9]+ \\(.+\\)(\\([0-9]+\\)):" 1 2) ("" 0)
     ("\\1.syn" "\\2__\\1.syn" "\\1.syn" "\\1.syn" "\\1__.syn" upcase))
    ;; Vantage: analyze -libfile vsslib.ini -src test.vhd
    ;;     Compiling "pcu.vhd" line 1...
    ;; **Error: LINE 499 *** No aggregate value is valid in this context.
    ("Vantage" "analyze" "-libfile vsslib.ini -src" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "vantage"
     ("\\*\\*Error: LINE \\([0-9]+\\) \\*\\*\\*" 0 1)
     ("^ *Compiling \"\\(.+\\)\" " 1)
     nil)
    ;; VeriBest: vc vhdl test.vhd
    ;; no file name printed out!
    ;;     32:   Z <=  A and BitA ;
    ;;                       ^^^^
    ;; [Error] Name BITA is unknown
    ("VeriBest" "vc" "vhdl" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "veribest"
     ("^ +\\([0-9]+\\): +[^ ]" 0 1) ("" 0)
     nil)
    ;; Viewlogic: analyze -libfile vsslib.ini -src test.vhd
    ;;     Compiling "pcu.vhd" line 1...
    ;; **Error: LINE 499 *** No aggregate value is valid in this context.
    ("Viewlogic" "analyze" "-libfile vsslib.ini -src" "make" "-f \\1"
     nil "mkdir \\1" "./" "work/" "Makefile" "viewlogic"
     ("\\*\\*Error: LINE \\([0-9]+\\) \\*\\*\\*" 0 1)
     ("^ *Compiling \"\\(.+\\)\" " 1)
     nil)
    )
  "*List of available VHDL compilers and their properties.
Each list entry specifies the following items for a compiler:
Compiler:
  Compiler name    : name used in option `vhdl-compiler' to choose compiler
  Compile command  : command used for source file compilation
  Compile options  : compile options (\"\\1\" inserts library name)
  Make command     : command used for compilation using a Makefile
  Make options     : make options (\"\\1\" inserts Makefile name)
  Generate Makefile: use built-in function or command to generate a Makefile
                     \(\"\\1\" inserts Makefile name, \"\\2\" inserts library name)
  Library command  : command to create library directory \(\"\\1\" inserts
                     library directory, \"\\2\" inserts library name)
  Compile directory: where compilation is run and the Makefile is placed
  Work directory   : directory of default library \"work\"
  Makefile name    : name of Makefile (default is \"Makefile\")
  ID string        : compiler identification string (see `vhdl-project-alist')
Error message:
  Regexp           : regular expression to match error messages
  File subexp index: index of subexpression that matches the file name
  Line subexp index: index of subexpression that matches the line number
File message:
  Regexp           : regular expression to match a file name message
  File subexp index: index of subexpression that matches the file name
Unit-to-file name mapping: mapping of library unit names to names of files
                     generated by the compiler (used for Makefile generation)
  To string        : string a name is mapped to (\"\\1\" inserts the unit name,
                     \"\\2\" inserts the entity name for architectures)
  Case adjustment  : adjust case of inserted unit names

Compile options allows insertion of the library name (see `vhdl-project-alist')
in order to set the compilers library option (e.g. \"vcom -work my_lib\").

For Makefile generation, the built-in function can be used (requires
specification of the unit-to-file name mapping).  Alternatively, an
external command can be specified.  Work directory allows specification of
an alternative \"work\" library path (e.g. \"WORK/\" instead of \"work/\",
used for Makefile generation).  To use another library name than \"work\",
customize `vhdl-project-alist'.  The library command is inserted in Makefiles
to automatically create the library directory if not existent.

Compile options, compile directory, library directory, and Makefile name are
overwritten by the project settings if a project is defined (see
`vhdl-project-alist').  Directory paths are relative to the source file
directory.

Some compilers do not include the file name in the error message, but print
out a file name message in advance.  In this case, set \"File Subexp Index\"
under \"Error Message\" to 0 and fill out the \"File Message\" entries.
If no file name at all is printed out, set both \"File Message\" entries to 0
\(a default file name message will be printed out instead, does not work in
XEmacs).

A compiler is selected for syntax analysis (`\\[vhdl-compile]') by
assigning its name to option `vhdl-compiler'.

Please send any missing or erroneous compiler properties to the maintainer for
updating.

NOTE: Reflect the new setting in the choice list of option `vhdl-compiler'
      by restarting Emacs."
  :type '(repeat
	  (list :tag "Compiler" :indent 2
		(string :tag "Compiler name      ")
		(string :tag "Compile command    ")
		(string :tag "Compile options    " "-work \\1")
		(string :tag "Make command       " "make")
		(string :tag "Make options       " "-f \\1")
		(choice :tag "Generate Makefile  "
			(const :tag "Built-in function" nil)
			(string :tag "Command" "vmake \\2 > \\1"))
		(string :tag "Library command    " "mkdir \\1")
		(directory :tag "Compile directory  "
			   :validate vhdl-widget-directory-validate "./")
		(directory :tag "Work directory     "
			   :validate vhdl-widget-directory-validate "work/")
		(file :tag "Makefile name      " "Makefile")
		(string :tag "ID string          ")
		(list :tag "Error message" :indent 4
		      (regexp  :tag "Regexp           ")
		      (integer :tag "File subexp index")
		      (integer :tag "Line subexp index"))
		(list :tag "File message" :indent 4
		      (regexp  :tag "Regexp           ")
		      (integer :tag "File subexp index"))
		(choice :tag "Unit-to-file name mapping"
			:format "%t: %[Value Menu%] %v\n"
			(const :tag "Not defined" nil)
			(list :tag "To string" :indent 4
			      (string :tag "Entity           " "\\1.vhd")
			      (string :tag "Architecture     " "\\2_\\1.vhd")
			      (string :tag "Configuration    " "\\1.vhd")
			      (string :tag "Package          " "\\1.vhd")
			      (string :tag "Package Body     " "\\1_body.vhd")
			      (choice :tag "Case adjustment  "
				      (const :tag "None" identity)
				      (const :tag "Upcase" upcase)
				      (const :tag "Downcase" downcase))))))
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-update-mode-menu))
  :group 'vhdl-compile)

(defcustom vhdl-compiler "ModelSim"
  "*Specifies the VHDL compiler to be used for syntax analysis.
Select a compiler name from the ones defined in option `vhdl-compiler-alist'."
  :type (let ((alist vhdl-compiler-alist) list)
	  (while alist
	    (setq list (cons (list 'const (caar alist)) list))
	    (setq alist (cdr alist)))
	  (append '(choice) (nreverse list)))
  :group 'vhdl-compile)

(defcustom vhdl-compile-use-local-error-regexp t
  "*Non-nil means use buffer-local `compilation-error-regexp-alist'.
In this case, only error message regexps for VHDL compilers are active if
compilation is started from a VHDL buffer.  Otherwise, the error message
regexps are appended to the predefined global regexps, and all regexps are
active all the time.  Note that by doing that, the predefined global regexps
might result in erroneous parsing of error messages for some VHDL compilers.

NOTE: Activate the new setting by restarting Emacs."
  :type 'boolean
  :group 'vhdl-compile)

(defcustom vhdl-makefile-generation-hook nil
  "*Functions to run at the end of Makefile generation.
Allows to insert user specific parts into a Makefile.

Example:
  \(lambda nil
    \(re-search-backward \"^# Rule for compiling entire design\")
    \(insert \"# My target\\n\\n.MY_TARGET :\\n\\n\\n\"))"
  :type 'hook
  :group 'vhdl-compile)


(defgroup vhdl-project nil
  "Customizations for projects."
  :group 'vhdl)

(defcustom vhdl-project-alist
  '(("Example 1" "Source files in two directories, custom library name, VHDL'87"
     "~/example1/" ("src/system/" "src/components/") ""
     (("ModelSim" "-87 \\2" "-f \\1 top_level" nil)
      ("Synopsys" "-vhdl87 \\2" "-f \\1 top_level" ((".*/datapath/.*" . "-optimize \\3") (".*_tb\\.vhd" . nil))))
     "lib/" "example3_lib" "lib/example3/" "Makefile_\\2" "")
    ("Example 2" "Individual source files, multiple compilers in different directories"
     "$EXAMPLE2/" ("vhdl/system.vhd" "vhdl/component_*.vhd") ""
     nil "\\1/" "work" "\\1/work/" "Makefile" "")
    ("Example 3" "Source files in a directory tree, multiple compilers in same directory"
     "/home/me/example3/" ("-r ./*/vhdl/") "/CVS/"
     nil "./" "work" "work-\\1/" "Makefile-\\1" "\
-------------------------------------------------------------------------------
-- This is a multi-line project description
-- that can be used as a project dependent part of the file header.
"))
  "*List of projects and their properties.
  Name             : name used in option `vhdl-project' to choose project
  Title            : title of project (single-line string)
  Default directory: default project directory (absolute path)
  Sources          : a) source files  : path + \"/\" + file name
                     b) directory     : path + \"/\"
                     c) directory tree: \"-r \" + path + \"/\"
  Exclude regexp   : matches file/directory names to be excluded as sources
  Compile options  : project-specific options for each compiler
    Compiler name  : name of compiler for which these options are valid
    Compile options: project-specific compiler options
                     (\"\\1\" inserts library name, \"\\2\" default options)
    Make options:    project-specific make options
                     (\"\\1\" inserts Makefile name, \"\\2\" default options)
    Exceptions     : file-specific exceptions
      File name regexp: matches file names for which exceptions are valid
      - Options       : file-specific compiler options string
                        (\"\\1\" inserts library name, \"\\2\" default options,
                        \"\\3\" project-specific options)
      - Do not compile: do not compile this file (in Makefile)
  Compile directory: where compilation is run and the Makefile is placed
                     \(\"\\1\" inserts compiler ID string)
  Library name     : name of library (default is \"work\")
  Library directory: path to library (\"\\1\" inserts compiler ID string)
  Makefile name    : name of Makefile
                     (\"\\1\" inserts compiler ID string, \"\\2\" library name)
  Description      : description of project (multi-line string)

Project title and description are used to insert into the file header (see
option `vhdl-file-header').

The default directory must have an absolute path (use `M-TAB' for completion).
All other paths can be absolute or relative to the default directory.  All
paths must end with '/'.

The design units found in the sources (files and directories) are shown in the
hierarchy browser.  Path and file name can contain wildcards `*' and `?' as
well as \"./\" and \"../\" (\"sh\" syntax).  Paths can also be absolute.
Environment variables (e.g. \"$EXAMPLE2\") are resolved.  If no sources are
specified, the default directory is taken as source directory.  Otherwise,
the default directory is only taken as source directory if there is a sources
entry with the empty string or \"./\".  Exclude regexp allows to filter out
specific file and directory names from the list of sources (e.g. CVS
directories).

Files are compiled in the compile directory.  Makefiles are also placed into
the compile directory.  Library directory specifies which directory the
compiler compiles into (used to generate the Makefile).

Since different compile/library directories and Makefiles may exist for
different compilers within one project, these paths and names allow the
insertion of a compiler-dependent ID string (defined in `vhdl-compiler-alist').
Compile options, compile directory, library directory, and Makefile name
overwrite the settings of the current compiler.

File-specific compiler options (highest priority) overwrite project-specific
options which overwrite default options (lowest priority).  Lower priority
options can be inserted in higher priority options.  This allows to reuse
default options (e.g. \"-file\") in project- or file-specific options (e.g.
\"-93 -file\").

NOTE: Reflect the new setting in the choice list of option `vhdl-project'
      by restarting Emacs."
  :type `(repeat
	  (list :tag "Project" :indent 2
		(string :tag "Name             ")
		(string :tag "Title            ")
		(directory :tag "Default directory"
			   :validate vhdl-widget-directory-validate
			   ,(abbreviate-file-name default-directory))
		(repeat :tag "Sources          " :indent 4
			(directory :format "     %v" "./"))
		(regexp :tag "Exclude regexp   ")
		(repeat
		 :tag "Compile options  " :indent 4
		 (list :tag "Compiler" :indent 6
		       ,(let ((alist vhdl-compiler-alist) list)
			  (while alist
			    (setq list (cons (list 'const (caar alist)) list))
			    (setq alist (cdr alist)))
			  (append '(choice :tag "Compiler name")
				  (nreverse list)))
		       (string :tag "Compile options" "\\2")
		       (string :tag "Make options   " "\\2")
		       (repeat
			:tag "Exceptions   " :indent 8
			(cons :format "%v"
			      (regexp :tag "File name regexp    ")
			      (choice :format "%[Value Menu%] %v"
				      (string :tag "Options" "\\3")
				      (const :tag "Do not compile" nil))))))
		(directory :tag "Compile directory"
			   :validate vhdl-widget-directory-validate "./")
		(string :tag "Library name     " "work")
		(directory :tag "Library directory"
			   :validate vhdl-widget-directory-validate "work/")
		(file :tag "Makefile name    " "Makefile")
		(string :tag "Description: (type `C-j' for newline)"
			:format "%t\n%v\n")))
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-update-mode-menu
			  'vhdl-speedbar-refresh))
  :group 'vhdl-project)

(defcustom vhdl-project nil
  "*Specifies the default for the current project.
Select a project name from the ones defined in option `vhdl-project-alist'.
Is used to determine the project title and description to be inserted in file
headers and the source files/directories to be scanned in the hierarchy
browser.  The current project can also be changed temporarily in the menu."
  :type (let ((alist vhdl-project-alist) list)
	  (while alist
	    (setq list (cons (list 'const (caar alist)) list))
	    (setq alist (cdr alist)))
	  (append '(choice (const :tag "None" nil) (const :tag "--"))
		  (nreverse list)))
  :group 'vhdl-project)

(defcustom vhdl-project-file-name '("\\1.prj")
  "*List of file names/paths for importing/exporting project setups.
\"\\1\" is replaced by the project name (SPC is replaced by `_').
The first entry is used as file name to import/export individual project
setups.  All entries are used to automatically import project setups at
startup (see option `vhdl-project-auto-load').
Names can also have an absolute path (i.e. project setups can be stored
in global directories)."
  :type '(repeat (string :tag "File name" "\\1.prj"))
  :group 'vhdl-project)

(defcustom vhdl-project-auto-load '(startup)
  "*Automatically load project setups from files.
All project setup files that match the file names specified in option
`vhdl-project-file-name' are automatically loaded.  The project of the
\(alphabetically) last loaded setup of the first `vhdl-project-file-name'
entry is activated.
A project setup file can be obtained by exporting a project (see menu).
  At startup: project setup file is loaded at Emacs startup"
  :type '(set (const :tag "At startup" startup))
  :group 'vhdl-project)

(defcustom vhdl-project-sort t
  "*Non-nil means projects are displayed in alphabetical order."
  :type 'boolean
  :group 'vhdl-project)


(defgroup vhdl-style nil
  "Customizations for code styles."
  :group 'vhdl)

(defcustom vhdl-standard '(87 nil)
  "*VHDL standards used.
Basic standard:
  VHDL'87      : IEEE Std 1076-1987
  VHDL'93      : IEEE Std 1076-1993
Additional standards:
  VHDL-AMS     : IEEE Std 1076.1 (analog-mixed-signal)
  Math packages: IEEE Std 1076.2 (`math_real', `math_complex')

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type '(list (choice :tag "Basic standard"
		       (const :tag "VHDL'87" 87)
		       (const :tag "VHDL'93" 93))
	       (set :tag "Additional standards" :indent 2
		    (const :tag "VHDL-AMS" ams)
		    (const :tag "Math packages" math)))
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-template-map-init
			  'vhdl-mode-abbrev-table-init
			  'vhdl-template-construct-alist-init
			  'vhdl-template-package-alist-init
			  'vhdl-update-mode-menu
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-style)

(defcustom vhdl-basic-offset 2
  "*Amount of basic offset used for indentation.
This value is used by + and - symbols in `vhdl-offsets-alist'."
  :type 'integer
  :group 'vhdl-style)

(defcustom vhdl-upper-case-keywords nil
  "*Non-nil means convert keywords to upper case.
This is done when typed or expanded or by the fix case functions."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-abbrev-list-init))
  :group 'vhdl-style)

(defcustom vhdl-upper-case-types nil
  "*Non-nil means convert standardized types to upper case.
This is done when expanded or by the fix case functions."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-abbrev-list-init))
  :group 'vhdl-style)

(defcustom vhdl-upper-case-attributes nil
  "*Non-nil means convert standardized attributes to upper case.
This is done when expanded or by the fix case functions."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-abbrev-list-init))
  :group 'vhdl-style)

(defcustom vhdl-upper-case-enum-values nil
  "*Non-nil means convert standardized enumeration values to upper case.
This is done when expanded or by the fix case functions."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-abbrev-list-init))
  :group 'vhdl-style)

(defcustom vhdl-upper-case-constants t
  "*Non-nil means convert standardized constants to upper case.
This is done when expanded."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-abbrev-list-init))
  :group 'vhdl-style)


(defgroup vhdl-naming nil
  "Customizations for naming conventions."
  :group 'vhdl)

(defcustom vhdl-entity-file-name '(".*" . "\\&")
  (concat
   "*Specifies how the entity file name is obtained.
The entity file name can be obtained by modifying the entity name (e.g.
attaching or stripping off a substring).  The file extension is automatically
taken from the file name of the current buffer."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-naming)


(defgroup vhdl-template nil
  "Customizations for electrification."
  :group 'vhdl)

(defcustom vhdl-electric-keywords '(vhdl user)
  "*Type of keywords for which electrification is enabled.
  VHDL keywords: invoke built-in templates
  User keywords: invoke user models (see option `vhdl-model-alist')"
  :type '(set (const :tag "VHDL keywords" vhdl)
	      (const :tag "User model keywords" user))
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-mode-abbrev-table-init))
  :group 'vhdl-template)

(defcustom vhdl-optional-labels 'process
  "*Constructs for which labels are to be queried.
Template generators prompt for optional labels for:
  None          : no constructs
  Processes only: processes only (also procedurals in VHDL-AMS)
  All constructs: all constructs with optional labels and keyword END"
  :type '(choice (const :tag "None" none)
		 (const :tag "Processes only" process)
		 (const :tag "All constructs" all))
  :group 'vhdl-template)

(defcustom vhdl-insert-empty-lines 'unit
  "*Specifies whether to insert empty lines in some templates.
This improves readability of code.  Empty lines are inserted in:
  None             : no constructs
  Design units only: entities, architectures, configurations, packages only
  All constructs   : also all constructs with BEGIN...END parts

Replaces option `vhdl-additional-empty-lines'."
  :type '(choice (const :tag "None" none)
		 (const :tag "Design units only" unit)
		 (const :tag "All constructs" all))
  :group 'vhdl-template
  :group 'vhdl-port)

(defcustom vhdl-argument-list-indent nil
  "*Non-nil means indent argument lists relative to opening parenthesis.
That is, argument, association, and port lists start on the same line as the
opening parenthesis and subsequent lines are indented accordingly.
Otherwise, lists start on a new line and are indented as normal code."
  :type 'boolean
  :group 'vhdl-template
  :group 'vhdl-port)

(defcustom vhdl-association-list-with-formals t
  "*Non-nil means write association lists with formal parameters.
In templates, you are prompted for formal and actual parameters.
When pasting component instantiations, formals are included.
If nil, only a list of actual parameters is entered."
  :type 'boolean
  :group 'vhdl-template
  :group 'vhdl-port)

(defcustom vhdl-conditions-in-parenthesis nil
  "*Non-nil means place parenthesis around condition expressions."
  :type 'boolean
  :group 'vhdl-template)

(defcustom vhdl-zero-string "'0'"
  "*String to use for a logic zero."
  :type 'string
  :group 'vhdl-template)

(defcustom vhdl-one-string "'1'"
  "*String to use for a logic one."
  :type 'string
  :group 'vhdl-template)


(defgroup vhdl-header nil
  "Customizations for file header."
  :group 'vhdl-template)

(defcustom vhdl-file-header "\
-------------------------------------------------------------------------------
-- Title      : <title string>
-- Project    : <project>
-------------------------------------------------------------------------------
-- File       : <filename>
-- Author     : <author>
-- Company    : <company>
-- Created    : <date>
-- Last update: <date>
-- Platform   : <platform>
<projectdesc>-------------------------------------------------------------------------------
-- Description: <cursor>
<copyright>-------------------------------------------------------------------------------
-- Revisions  :
-- Date        Version  Author  Description
-- <date>  1.0      <login>\tCreated
-------------------------------------------------------------------------------

"
  "*String or file to insert as file header.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted as file header.
Type `C-j' for newlines.
If the header contains RCS keywords, they may be written as <RCS>Keyword<RCS>
if the header needs to be version controlled.

The following keywords for template generation are supported:
  <filename>    : replaced by the name of the buffer
  <author>      : replaced by the user name and email address
                  \(`user-full-name',`mail-host-address', `user-mail-address')
  <login>       : replaced by user login name (`user-login-name')
  <company>     : replaced by contents of option `vhdl-company-name'
  <date>        : replaced by the current date
  <year>        : replaced by the current year
  <project>     : replaced by title of current project (`vhdl-project')
  <projectdesc> : replaced by description of current project (`vhdl-project')
  <copyright>   : replaced by copyright string (`vhdl-copyright-string')
  <platform>    : replaced by contents of option `vhdl-platform-spec'
  <... string>  : replaced by a queried string (\"...\" is the prompt word)
  <title string>: replaced by file title in automatically generated files
  <cursor>      : final cursor position

The (multi-line) project description <projectdesc> can be used as a project
dependent part of the file header and can also contain the above keywords."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-file-footer ""
  "*String or file to insert as file footer.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted as file footer (i.e. at
the end of the file).
Type `C-j' for newlines.
The same keywords as in option `vhdl-file-header' can be used."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-company-name ""
  "*Name of company to insert in file header.
See option `vhdl-file-header'."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-copyright-string "\
-------------------------------------------------------------------------------
-- Copyright (c) <year> <company>
"
  "*Copyright string to insert in file header.
Can be multi-line string (type `C-j' for newline) and contain other file
header keywords (see option `vhdl-file-header')."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-platform-spec ""
  "*Specification of VHDL platform to insert in file header.
The platform specification should contain names and versions of the
simulation and synthesis tools used.
See option `vhdl-file-header'."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-date-format "%Y-%m-%d"
  "*Specifies the date format to use in the header.
This string is passed as argument to the command `format-time-string'.
For more information on format strings, see the documentation for the
`format-time-string' command (C-h f `format-time-string')."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-modify-date-prefix-string "-- Last update: "
  "*Prefix string of modification date in VHDL file header.
If actualization of the modification date is called (menu,
`\\[vhdl-template-modify]'), this string is searched and the rest
of the line replaced by the current date."
  :type 'string
  :group 'vhdl-header)

(defcustom vhdl-modify-date-on-saving t
  "*Non-nil means update the modification date when the buffer is saved.
Calls function `\\[vhdl-template-modify]').

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'boolean
  :group 'vhdl-header)


(defgroup vhdl-sequential-process nil
  "Customizations for sequential processes."
  :group 'vhdl-template)

(defcustom vhdl-reset-kind 'async
  "*Specifies which kind of reset to use in sequential processes."
  :type '(choice (const :tag "None" none)
		 (const :tag "Synchronous" sync)
		 (const :tag "Asynchronous" async))
  :group 'vhdl-sequential-process)

(defcustom vhdl-reset-active-high nil
  "*Non-nil means reset in sequential processes is active high.
Nil means active low."
  :type 'boolean
  :group 'vhdl-sequential-process)

(defcustom vhdl-clock-rising-edge t
  "*Non-nil means rising edge of clock triggers sequential processes.
Nil means falling edge."
  :type 'boolean
  :group 'vhdl-sequential-process)

(defcustom vhdl-clock-edge-condition 'standard
  "*Syntax of the clock edge condition.
  Standard: \"clk'event and clk = '1'\"
  Function: \"rising_edge(clk)\""
  :type '(choice (const :tag "Standard" standard)
		 (const :tag "Function" function))
  :group 'vhdl-sequential-process)

(defcustom vhdl-clock-name ""
  "*Name of clock signal to use in templates."
  :type 'string
  :group 'vhdl-sequential-process)

(defcustom vhdl-reset-name ""
  "*Name of reset signal to use in templates."
  :type 'string
  :group 'vhdl-sequential-process)


(defgroup vhdl-model nil
  "Customizations for user models."
  :group 'vhdl)

(defcustom vhdl-model-alist
  '(("Example Model"
     "<label> : process (<clock>, <reset>)
begin  -- process <label>
  if <reset> = '0' then  -- asynchronous reset (active low)
    <cursor>
  elsif <clock>'event and <clock> = '1' then  -- rising clock edge
    if <enable> = '1' then  -- synchronous load
      
    end if;
  end if;
end process <label>;"
     "e" ""))
  "*List of user models.
VHDL models (templates) can be specified by the user in this list.  They can be
invoked from the menu, through key bindings (`C-c C-m ...'), or by keyword
electrification (i.e. overriding existing or creating new keywords, see
option `vhdl-electric-keywords').
  Name       : name of model (string of words and spaces)
  String     : string or name of file to be inserted as model (newline: `C-j')
  Key Binding: key binding to invoke model, added to prefix `C-c C-m'
                (must be in double-quotes, examples: \"i\", \"\\C-p\", \"\\M-s\")
  Keyword    : keyword to invoke model

The models can contain prompts to be queried.  A prompt is of the form \"<...>\".
A prompt that appears several times is queried once and replaced throughout
the model.  Special prompts are:
  <clock> : name specified in `vhdl-clock-name' (if not empty)
  <reset> : name specified in `vhdl-reset-name' (if not empty)
  <cursor>: final cursor position
File header prompts (see variable `vhdl-file-header') are automatically
replaced, so that user models can also be used to insert different types of
headers.

If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted.
The code within the models should be correctly indented.
Type `C-j' for newlines.

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type '(repeat (list :tag "Model" :indent 2
		       (string :tag "Name       ")
		       (string :tag "String     : (type `C-j' for newline)"
			       :format "%t\n%v")
		       (sexp   :tag "Key binding" x)
		       (string :tag "Keyword    " :format "%t: %v\n")))
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-model-map-init
			  'vhdl-model-defun
			  'vhdl-mode-abbrev-table-init
			  'vhdl-update-mode-menu))
  :group 'vhdl-model)


(defgroup vhdl-port nil
  "Customizations for port translation functions."
  :group 'vhdl)

(defcustom vhdl-include-port-comments nil
  "*Non-nil means include port comments when a port is pasted."
  :type 'boolean
  :group 'vhdl-port)

(defcustom vhdl-include-direction-comments nil
  "*Non-nil means include port direction in instantiations as comments."
  :type 'boolean
  :group 'vhdl-port)

(defcustom vhdl-include-type-comments nil
  "*Non-nil means include generic/port type in instantiations as comments."
  :type 'boolean
  :group 'vhdl-port)

(defcustom vhdl-include-group-comments 'never
  "*Specifies whether to include group comments and spacings.
The comments and empty lines between groups of ports are pasted:
  Never       : never
  Declarations: in entity/component/constant/signal declarations only
  Always      : also in generic/port maps"
  :type '(choice (const :tag "Never" never)
		 (const :tag "Declarations" decl)
		 (const :tag "Always" always))
  :group 'vhdl-port)

(defcustom vhdl-actual-port-name '(".*" . "\\&")
  (concat
   "*Specifies how actual port names are obtained from formal port names.
In a component instantiation, an actual port name can be obtained by
modifying the formal port name (e.g. attaching or stripping off a substring)."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-port)

(defcustom vhdl-instance-name '(".*" . "\\&_1")
  (concat
   "*Specifies how an instance name is obtained.
The instance name can be obtained by modifying the name of the component to be
instantiated (e.g. attaching or stripping off a substring).
If TO STRING is empty, the instance name is queried."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-port)


(defgroup vhdl-testbench nil
  "Customizations for test bench generation ."
  :group 'vhdl-port)

(defcustom vhdl-testbench-entity-name '(".*" . "\\&_tb")
  (concat
   "*Specifies how the test bench entity name is obtained.
The entity name of a test bench can be obtained by modifying the name of
the component to be tested (e.g. attaching or stripping off a substring)."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-architecture-name '(".*" . "")
  (concat
   "*Specifies how the test bench architecture name is obtained.
The test bench architecture name can be obtained by modifying the name of
the component to be tested (e.g. attaching or stripping off a substring).
If TO STRING is empty, the architecture name is queried."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-configuration-name
  '("\\(.*\\) \\(.*\\)" . "\\1_\\2_cfg")
  (concat
   "*Specifies how the test bench configuration name is obtained.
The configuration name of a test bench can be obtained by modifying the entity
and/or architecture name (e.g. attaching or stripping off a substring).  The
string that is matched against the regexp is the concatenation of the entity
and the architecture name separated by a space.  This gives access to both
names (see default setting as example)."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-dut-name '(".*" . "DUT")
  (concat
   "*Specifies how a DUT instance name is obtained.
The design-under-test instance name (i.e. the component instantiated in the
test bench) can be obtained by modifying the component name (e.g. attaching
or stripping off a substring)."
   vhdl-name-doc-string)
  :type '(cons (regexp :tag "From regexp")
	       (string :tag "To string  "))
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-entity-header ""
  "*String or file to be inserted as test bench entity header.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted at the beginning of the test
bench entity template.
Type `C-j' for newlines."
  :type 'string
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-architecture-header ""
  "*String or file to be inserted as test bench architecture header.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted at the beginning of the test
bench architecture template, if a separate file is created for the
architecture.
Type `C-j' for newlines."
  :type 'string
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-declarations ""
  "*String or file to be inserted in the test bench declarative part.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted in the test bench
architecture before the BEGIN keyword.
Type `C-j' for newlines."
  :type 'string
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-statements ""
  "*String or file to be inserted in the test bench statement part.
If the string specifies an existing file name, the contents of the file is
inserted, otherwise the string itself is inserted in the test bench
architecture before the END keyword.
Type `C-j' for newlines."
  :type 'string
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-initialize-signals nil
  "*Non-nil means initialize signals with `0' when declared in test bench."
  :type 'boolean
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-include-library t
  "*Non-nil means a library/use clause for std_logic_1164 is included."
  :type 'boolean
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-include-configuration t
  "*Non-nil means a test bench configuration is attached at the end."
  :type 'boolean
  :group 'vhdl-testbench)

(defcustom vhdl-testbench-create-files 'single
  "*Specifies whether new files should be created for the test bench.
Test bench entity and architecture are inserted:
  None          : in current buffer
  Single file   : in new single file
  Separate files: in two separate files
Note that the files have the same name as the contained design unit."
  :type '(choice (const :tag "None" none)
		 (const :tag "Single file" single)
		 (const :tag "Separate files" separate))
  :group 'vhdl-testbench)


(defgroup vhdl-comment nil
  "Customizations for comments."
  :group 'vhdl)

(defcustom vhdl-self-insert-comments t
  "*Non-nil means various templates automatically insert help comments."
  :type 'boolean
  :group 'vhdl-comment)

(defcustom vhdl-prompt-for-comments t
  "*Non-nil means various templates prompt for user definable comments."
  :type 'boolean
  :group 'vhdl-comment)

(defcustom vhdl-inline-comment-column 40
  "*Column to indent and align inline comments to.
Overrides local option `comment-column'.

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'integer
  :group 'vhdl-comment)

(defcustom vhdl-end-comment-column 79
  "*End of comment column.
Comments that exceed this column number are wrapped.

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'integer
  :group 'vhdl-comment)

(defvar end-comment-column)


(defgroup vhdl-align nil
  "Customizations for alignment."
  :group 'vhdl)

(defcustom vhdl-auto-align t
  "*Non-nil means align some templates automatically after generation."
  :type 'boolean
  :group 'vhdl-align)

(defcustom vhdl-align-groups t
  "*Non-nil means align groups of code lines separately.
A group of code lines is a region of consecutive lines between two lines that
match the regexp in option `vhdl-align-group-separate'."
  :type 'boolean
  :group 'vhdl-align)

(defcustom vhdl-align-group-separate "^\\s-*$"
  "*Regexp for matching a line that separates groups of lines for alignment.
Examples:
  \"^\\s-*$\":          matches an empty line
  \"^\\s-*\\(--.*\\)?$\": matches an empty line or a comment-only line"
  :type 'regexp
  :group 'vhdl-align)

(defcustom vhdl-align-same-indent t
  "*Non-nil means align blocks with same indent separately.
When a region or the entire buffer is aligned, the code is divided into
blocks of same indent which are aligned separately (except for argument/port
lists).  This gives nicer alignment in most cases.
Option `vhdl-align-groups' still applies within these blocks."
  :type 'boolean
  :group 'vhdl-align)


(defgroup vhdl-highlight nil
  "Customizations for highlighting."
  :group 'vhdl)

(defcustom vhdl-highlight-keywords t
  "*Non-nil means highlight VHDL keywords and other standardized words.
The following faces are used:
  `font-lock-keyword-face'       : keywords
  `font-lock-type-face'          : standardized types
  `vhdl-font-lock-attribute-face': standardized attributes
  `vhdl-font-lock-enumvalue-face': standardized enumeration values
  `vhdl-font-lock-function-face' : standardized function and package names

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-names t
  "*Non-nil means highlight declaration names and construct labels.
The following faces are used:
  `font-lock-function-name-face' : names in declarations of units,
     subprograms, components, as well as labels of VHDL constructs
  `font-lock-type-face'          : names in type/nature declarations
  `vhdl-font-lock-attribute-face': names in attribute declarations
  `font-lock-variable-name-face' : names in declarations of signals,
     variables, constants, subprogram parameters, generics, and ports

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-special-words nil
  "*Non-nil means highlight words with special syntax.
The words with syntax and color specified in option `vhdl-special-syntax-alist'
are highlighted accordingly.
Can be used for visual support of naming conventions.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-forbidden-words nil
  "*Non-nil means highlight forbidden words.
The reserved words specified in option `vhdl-forbidden-words' or having the
syntax specified in option `vhdl-forbidden-syntax' are highlighted in a
warning color (face `vhdl-font-lock-reserved-words-face') to indicate not to
use them.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-verilog-keywords nil
  "*Non-nil means highlight Verilog keywords as reserved words.
Verilog keywords are highlighted in a warning color (face
`vhdl-font-lock-reserved-words-face') to indicate not to use them.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-translate-off nil
  "*Non-nil means background-highlight code excluded from translation.
That is, all code between \"-- pragma translate_off\" and
\"-- pragma translate_on\" is highlighted using a different background color
\(face `vhdl-font-lock-translate-off-face').
Note: this might slow down on-the-fly fontification (and thus editing).

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-highlight-case-sensitive nil
  "*Non-nil means consider case for highlighting.
Possible trade-off:
  non-nil  also upper-case VHDL words are highlighted, but case of words with
           special syntax is not considered
  nil      only lower-case VHDL words are highlighted, but case of words with
           special syntax is considered
Overrides local option `font-lock-keywords-case-fold-search'.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'boolean
  :group 'vhdl-highlight)

(defcustom vhdl-special-syntax-alist
  '(("generic/constant" "\\w+_[cg]" "Gold3" "BurlyWood1")
    ("type" "\\w+_t" "ForestGreen" "PaleGreen")
    ("variable" "\\w+_v" "Grey50" "Grey80"))
  "*List of special syntax to be highlighted.
If option `vhdl-highlight-special-words' is non-nil, words with the specified
syntax (as regular expression) are highlighted in the corresponding color.

  Name         : string of words and spaces
  Regexp       : regular expression describing word syntax
                  (e.g. \"\\\w+_c\" matches word with suffix \"_c\")
  Color (light): foreground color for light background
                 (matching color examples: Gold3, Grey50, LimeGreen, Tomato,
                 LightSeaGreen, DodgerBlue, Gold, PaleVioletRed)
  Color (dark) : foreground color for dark background
                 (matching color examples: BurlyWood1, Grey80, Green, Coral,
                 AquaMarine2, LightSkyBlue1, Yellow, PaleVioletRed1)

Can be used for visual support of naming conventions, such as highlighting
different kinds of signals (e.g. \"Clk50\", \"Rst_n\") or objects (e.g.
\"Signal_s\", \"Variable_v\", \"Constant_c\") by distinguishing them using
common substrings or name suffices.
For each entry, a new face is generated with the specified colors and name
\"vhdl-font-lock-\" + name + \"-face\".

NOTE: Activate a changed regexp in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\").  All other changes require restarting Emacs."
  :type '(repeat (list :tag "Face" :indent 2
		       (string :tag "Name         ")
		       (regexp :tag "Regexp       " "\\w+_")
		       (string :tag "Color (light)")
		       (string :tag "Color (dark) ")))
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-forbidden-words '()
  "*List of forbidden words to be highlighted.
If option `vhdl-highlight-forbidden-words' is non-nil, these reserved
words are highlighted in a warning color to indicate not to use them.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type '(repeat (string :format "%v"))
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-forbidden-syntax ""
  "*Syntax of forbidden words to be highlighted.
If option `vhdl-highlight-forbidden-words' is non-nil, words with this
syntax are highlighted in a warning color to indicate not to use them.
Can be used to highlight too long identifiers (e.g. \"\\w\\w\\w\\w\\w\\w\\w\\w\\w\\w+\"
highlights identifiers with 10 or more characters).

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type 'regexp
  :set (lambda (variable value)
         (vhdl-custom-set variable value
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-highlight)

(defcustom vhdl-directive-keywords '("pragma" "synopsys")
  "*List of compiler directive keywords recognized for highlighting.

NOTE: Activate the new setting in a VHDL buffer by re-fontifying it (menu
      entry \"Fontify Buffer\")."
  :type '(repeat (string :format "%v"))
  :set (lambda (variable value)
	 (vhdl-custom-set variable value
			  'vhdl-words-init 'vhdl-font-lock-init))
  :group 'vhdl-highlight)


(defgroup vhdl-speedbar nil
  "Customizations for speedbar."
  :group 'vhdl)

(defcustom vhdl-speedbar-auto-open nil
  "*Non-nil means automatically open speedbar at startup.
Alternatively, the speedbar can be opened from the VHDL menu."
  :type 'boolean 
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-display-mode 'files
  "*Specifies the default displaying mode when opening speedbar.
Alternatively, the displaying mode can be selected from the speedbar menu or
by typing `f' (files), `h' (directory hierarchy) or `H' (project hierarchy)."
  :type '(choice (const :tag "Files" files)
		 (const :tag "Directory hierarchy" directory)
		 (const :tag "Project hierarchy" project))
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-scan-limit '(10000000 (1000000 50))
  "*Limits scanning of large files and netlists.
Design units: maximum file size to scan for design units
Hierarchy (instances of subcomponents):
  File size: maximum file size to scan for instances (in bytes)
  Instances per arch: maximum number of instances to scan per architecture

\"None\" always means that there is no limit.
In case of files not or incompletely scanned, a warning message and the file
names are printed out.
Background: scanning for instances is considerably slower than scanning for
design units, especially when there are many instances.  These limits should
prevent the scanning of large netlists."
  :type '(list (choice :tag "Design units"
		       :format "%t        : %[Value Menu%] %v"
		       (const :tag "None" nil)
		       (integer :tag "File size"))
	       (list :tag "Hierarchy" :indent 2
		     (choice :tag "File size"
			     :format "%t         : %[Value Menu%] %v"
			     (const :tag "None" nil)
			     (integer :tag "Size     "))
		     (choice :tag "Instances per arch"
			     (const :tag "None" nil)
			     (integer :tag "Number   "))))
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-jump-to-unit t
  "*Non-nil means jump to the design unit code when opened in a buffer.
The buffer cursor position is left unchanged otherwise."
  :type 'boolean
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-update-on-saving t
  "*Automatically update design hierarchy when buffer is saved."
  :type 'boolean
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-save-cache '(hierarchy display)
  "*Automatically save modified hierarchy caches when exiting Emacs.
  Hierarchy: design hierarchy information
  Display:   displaying information (which design units to expand)"
  :type '(set (const :tag "Hierarchy" hierarchy)
	      (const :tag "Display"   display))
  :group 'vhdl-speedbar)

(defcustom vhdl-speedbar-cache-file-name ".emacs-vhdl-cache-\\1"
  "*Name of file for saving hierarchy cache.
\"\\1\" is replaced by the project name if a project is specified,
\"directory\" otherwise.  Can also have an absolute path (i.e. all caches can
be stored in one global directory)."
  :type 'string
  :group 'vhdl-speedbar)


(defgroup vhdl-menu nil
  "Customizations for menues."
  :group 'vhdl)

(defcustom vhdl-index-menu nil
  "*Non-nil means add an index menu for a source file when loading.
Alternatively, the speedbar can be used.  Note that the index menu scans a file
when it is opened, while speedbar only scans the file upon request."
  :type 'boolean
  :group 'vhdl-menu)

(defcustom vhdl-source-file-menu nil
  "*Non-nil means add a menu of all source files in current directory.
Alternatively, the speedbar can be used."
  :type 'boolean
  :group 'vhdl-menu)

(defcustom vhdl-hideshow-menu nil
  "*Non-nil means add hideshow menu and functionality at startup.
Hideshow can also be enabled from the VHDL Mode menu.
Hideshow allows hiding code of various VHDL constructs.

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'boolean
  :group 'vhdl-menu)

(defcustom vhdl-hide-all-init nil
  "*Non-nil means hide all design units initially after a file is loaded."
  :type 'boolean
  :group 'vhdl-menu)


(defgroup vhdl-print nil
  "Customizations for printing."
  :group 'vhdl)

(defcustom vhdl-print-two-column t
  "*Non-nil means print code in two columns and landscape format.

NOTE: Activate the new setting by restarting Emacs.
      Overrides `ps-print' settings locally."
  :type 'boolean
  :group 'vhdl-print)

(defcustom vhdl-print-customize-faces t
  "*Non-nil means use an optimized set of faces for postscript printing.

NOTE: Activate the new setting by restarting Emacs.
      Overrides `ps-print' settings locally."
  :type 'boolean
  :group 'vhdl-print)


(defgroup vhdl-misc nil
  "Miscellaneous customizations."
  :group 'vhdl)

(defcustom vhdl-intelligent-tab t
  "*Non-nil means `TAB' does indentation, word completion and tab insertion.
That is, if preceeding character is part of a word then complete word,
else if not at beginning of line then insert tab,
else if last command was a `TAB' or `RET' then dedent one step,
else indent current line (i.e. `TAB' is bound to `vhdl-electric-tab').
If nil, TAB always indents current line (i.e. `TAB' is bound to
`indent-according-to-mode').

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'boolean
  :group 'vhdl-misc)

(defcustom vhdl-indent-syntax-based t
  "*Non-nil means indent lines of code based on their syntactic context.
Otherwise, a line is indented like the previous nonblank line.  This can be
useful in large files where syntax-based indentation gets very slow."
  :type 'boolean
  :group 'vhdl-misc)

(defcustom vhdl-word-completion-case-sensitive nil
  "*Non-nil means word completion using `TAB' is case sensitive.
That is, `TAB' completes words that start with the same letters and case.
Otherwise, case is ignored."
  :type 'boolean
  :group 'vhdl-misc)

(defcustom vhdl-word-completion-in-minibuffer t
  "*Non-nil enables word completion in minibuffer (for template prompts).

NOTE: Activate the new setting by restarting Emacs."
  :type 'boolean
  :group 'vhdl-misc)

(defcustom vhdl-underscore-is-part-of-word nil
  "*Non-nil means consider the underscore character `_' as part of word.
An identifier containing underscores is then treated as a single word in
select and move operations.  All parts of an identifier separated by underscore
are treated as single words otherwise.

NOTE: Activate the new setting in a VHDL buffer by using the menu entry
      \"Activate Customization\"."
  :type 'boolean
  :set (lambda (variable value)
         (vhdl-custom-set variable value 'vhdl-mode-syntax-table-init))
  :group 'vhdl-misc)


(defgroup vhdl-related nil
  "Related general customizations."
  :group 'vhdl)

;; add related general customizations
(custom-add-to-group 'vhdl-related 'hideshow 'custom-group)
(if vhdl-xemacs
    (custom-add-to-group 'vhdl-related 'paren-mode 'custom-variable)
  (custom-add-to-group 'vhdl-related 'paren-showing 'custom-group))
(custom-add-to-group 'vhdl-related 'ps-print 'custom-group)
(custom-add-to-group 'vhdl-related 'speedbar 'custom-group)
(custom-add-to-group 'vhdl-related 'line-number-mode 'custom-variable)
(unless vhdl-xemacs
  (custom-add-to-group 'vhdl-related 'transient-mark-mode 'custom-variable))
(custom-add-to-group 'vhdl-related 'user-full-name 'custom-variable)
(custom-add-to-group 'vhdl-related 'mail-host-address 'custom-variable)
(custom-add-to-group 'vhdl-related 'user-mail-address 'custom-variable)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Internal variables

(defvar vhdl-progress-interval 1
  "*Interval used to update progress status during long operations.
If a number, percentage complete gets updated after each interval of
that many seconds.  To inhibit all messages, set this option to nil.")

(defvar vhdl-inhibit-startup-warnings-p nil
  "*If non-nil, inhibits start up compatibility warnings.")

(defvar vhdl-strict-syntax-p nil
  "*If non-nil, all syntactic symbols must be found in `vhdl-offsets-alist'.
If the syntactic symbol for a particular line does not match a symbol
in the offsets alist, an error is generated, otherwise no error is
reported and the syntactic symbol is ignored.")

(defvar vhdl-echo-syntactic-information-p nil
  "*If non-nil, syntactic info is echoed when the line is indented.")

(defconst vhdl-offsets-alist-default
  '((string                . -1000)
    (block-open            . 0)
    (block-close           . 0)
    (statement             . 0)
    (statement-cont        . vhdl-lineup-statement-cont)
    (statement-block-intro . +)
    (statement-case-intro  . +)
    (case-alternative      . +)
    (comment               . vhdl-lineup-comment)
    (arglist-intro         . +)
    (arglist-cont          . 0)
    (arglist-cont-nonempty . vhdl-lineup-arglist)
    (arglist-close         . vhdl-lineup-arglist)
    (entity                . 0)
    (configuration         . 0)
    (package               . 0)
    (architecture          . 0)
    (package-body          . 0)
    )
  "Default settings for offsets of syntactic elements.
Do not change this constant!  See the variable `vhdl-offsets-alist' for
more information.")

(defvar vhdl-offsets-alist (copy-alist vhdl-offsets-alist-default)
  "*Association list of syntactic element symbols and indentation offsets.
As described below, each cons cell in this list has the form:

    (SYNTACTIC-SYMBOL . OFFSET)

When a line is indented, `vhdl-mode' first determines the syntactic
context of the line by generating a list of symbols called syntactic
elements.  This list can contain more than one syntactic element and
the global variable `vhdl-syntactic-context' contains the context list
for the line being indented.  Each element in this list is actually a
cons cell of the syntactic symbol and a buffer position.  This buffer
position is call the relative indent point for the line.  Some
syntactic symbols may not have a relative indent point associated with
them.

After the syntactic context list for a line is generated, `vhdl-mode'
calculates the absolute indentation for the line by looking at each
syntactic element in the list.  First, it compares the syntactic
element against the SYNTACTIC-SYMBOL's in `vhdl-offsets-alist'.  When it
finds a match, it adds the OFFSET to the column of the relative indent
point.  The sum of this calculation for each element in the syntactic
list is the absolute offset for line being indented.

If the syntactic element does not match any in the `vhdl-offsets-alist',
an error is generated if `vhdl-strict-syntax-p' is non-nil, otherwise
the element is ignored.

Actually, OFFSET can be an integer, a function, a variable, or one of
the following symbols: `+', `-', `++', or `--'.  These latter
designate positive or negative multiples of `vhdl-basic-offset',
respectively: *1, *-1, *2, and *-2.  If OFFSET is a function, it is
called with a single argument containing the cons of the syntactic
element symbol and the relative indent point.  The function should
return an integer offset.

Here is the current list of valid syntactic element symbols:

 string                 -- inside multi-line string
 block-open             -- statement block open
 block-close            -- statement block close
 statement              -- a VHDL statement
 statement-cont         -- a continuation of a VHDL statement
 statement-block-intro  -- the first line in a new statement block
 statement-case-intro   -- the first line in a case alternative block
 case-alternative       -- a case statement alternative clause
 comment                -- a line containing only a comment
 arglist-intro          -- the first line in an argument list
 arglist-cont           -- subsequent argument list lines when no
                           arguments follow on the same line as the
                           the arglist opening paren
 arglist-cont-nonempty  -- subsequent argument list lines when at
                           least one argument follows on the same
                           line as the arglist opening paren
 arglist-close          -- the solo close paren of an argument list
 entity                 -- inside an entity declaration
 configuration          -- inside a configuration declaration
 package                -- inside a package declaration
 architecture           -- inside an architecture body
 package-body           -- inside a package body")

(defvar vhdl-comment-only-line-offset 0
  "*Extra offset for line which contains only the start of a comment.
Can contain an integer or a cons cell of the form:

 (NON-ANCHORED-OFFSET . ANCHORED-OFFSET)

Where NON-ANCHORED-OFFSET is the amount of offset given to
non-column-zero anchored comment-only lines, and ANCHORED-OFFSET is
the amount of offset to give column-zero anchored comment-only lines.
Just an integer as value is equivalent to (<val> . 0)")

(defvar vhdl-special-indent-hook nil
  "*Hook for user defined special indentation adjustments.
This hook gets called after a line is indented by the mode.")

(defvar vhdl-style-alist
  '(("IEEE"
     (vhdl-basic-offset . 4)
     (vhdl-offsets-alist . ())))
  "Styles of Indentation.
Elements of this alist are of the form:

  (STYLE-STRING (VARIABLE . VALUE) [(VARIABLE . VALUE) ...])

where STYLE-STRING is a short descriptive string used to select a
style, VARIABLE is any `vhdl-mode' variable, and VALUE is the intended
value for that variable when using the selected style.

There is one special case when VARIABLE is `vhdl-offsets-alist'.  In this
case, the VALUE is a list containing elements of the form:

  (SYNTACTIC-SYMBOL . VALUE)

as described in `vhdl-offsets-alist'.  These are passed directly to
`vhdl-set-offset' so there is no need to set every syntactic symbol in
your style, only those that are different from the default.")

;; dynamically append the default value of most variables
(or (assoc "Default" vhdl-style-alist)
    (let* ((varlist '(vhdl-inhibit-startup-warnings-p
		      vhdl-strict-syntax-p
		      vhdl-echo-syntactic-information-p
		      vhdl-basic-offset
		      vhdl-offsets-alist
		      vhdl-comment-only-line-offset))
	   (default (cons "Default"
			  (mapcar
			   (function
			    (lambda (var)
			      (cons var (symbol-value var))))
			   varlist))))
      (setq vhdl-style-alist (cons default vhdl-style-alist))))

(defvar vhdl-mode-hook nil
  "*Hook called by `vhdl-mode'.")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Required packages
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; mandatory
(require 'assoc)
(require 'compile)			; XEmacs
(require 'easymenu)
(require 'hippie-exp)

;; optional (minimize warning messages during compile)
(eval-when-compile
  (require 'font-lock)
  (require 'ps-print)
  (require 'speedbar))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Compatibility
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; XEmacs compatibility

;; active regions
(defun vhdl-keep-region-active ()
  "Do whatever is necessary to keep the region active in XEmacs.
Ignore byte-compiler warnings you might see."
  (and (boundp 'zmacs-region-stays)
       (setq zmacs-region-stays t)))

;; `wildcard-to-regexp' is included only in XEmacs 21
(unless (fboundp 'wildcard-to-regexp)
  (defun wildcard-to-regexp (wildcard)
    "Simplified version of `wildcard-to-regexp' from Emacs' `files.el'."
    (let* ((i (string-match "[*?]" wildcard))
	   (result (substring wildcard 0 i))
	   (len (length wildcard)))
      (when i
	(while (< i len)
	  (let ((ch (aref wildcard i)))
	    (setq result (concat result
				 (cond ((eq ch ?*)  "[^\000]*")
				       ((eq ch ??)  "[^\000]")
				       (t (char-to-string ch)))))
	    (setq i (1+ i)))))
      (concat "\\`" result "\\'"))))

;; `regexp-opt' undefined (`xemacs-devel' not installed)
;; `regexp-opt' accelerates fontification by 10-20%
(unless (fboundp 'regexp-opt)
;  (vhdl-warning-when-idle "Please install `xemacs-devel' package.")
  (defun regexp-opt (strings &optional paren)
    (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
      (concat open (mapconcat 'regexp-quote strings "\\|") close))))

;; `match-string-no-properties' undefined (XEmacs, what else?)
(unless (fboundp 'match-string-no-properties)
  (defalias 'match-string-no-properties 'match-string))

;; `subst-char-in-string' undefined
(unless (fboundp 'subst-char-in-string)
  (defun subst-char-in-string (fromchar tochar string &optional inplace)
    (let ((i (length string))
	  (newstr (if inplace string (copy-sequence string))))
      (while (> i 0)
	(setq i (1- i))
	(if (eq (aref newstr i) fromchar) (aset newstr i tochar)))
      newstr)))

;; `itimer.el': idle timer bug fix in version 1.09 (XEmacs 21.1.9)
(when (and vhdl-xemacs (string< itimer-version "1.09")
	   (not noninteractive))
  (load "itimer")
  (when (string< itimer-version "1.09")
    (message "WARNING:  Install included `itimer.el' patch first (see INSTALL file)")
    (beep) (sit-for 5)))

;; `file-expand-wildcards' undefined
(unless (fboundp 'file-expand-wildcards)
  (defun file-expand-wildcards (pattern &optional full)
    "Taken from Emacs' `files.el'."
    (let* ((nondir (file-name-nondirectory pattern))
    	   (dirpart (file-name-directory pattern))
    	   (dirs (if (and dirpart (string-match "[[*?]" dirpart))
		     (mapcar 'file-name-as-directory
			     (file-expand-wildcards (directory-file-name dirpart)))
		   (list dirpart)))
	   contents)
      (while dirs
	(when (or (null (car dirs))	; Possible if DIRPART is not wild.
		  (file-directory-p (directory-file-name (car dirs))))
	  (let ((this-dir-contents
		 (delq nil
		       (mapcar #'(lambda (name)
				   (unless (string-match "\\`\\.\\.?\\'"
							 (file-name-nondirectory name))
				     name))
			       (directory-files (or (car dirs) ".") full
						(wildcard-to-regexp nondir))))))
	    (setq contents
		  (nconc
		   (if (and (car dirs) (not full))
		       (mapcar (function (lambda (name) (concat (car dirs) name)))
			       this-dir-contents)
		     this-dir-contents)
		   contents))))
	(setq dirs (cdr dirs)))
      contents)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Compatibility with older VHDL Mode versions

(defvar vhdl-warnings nil
  "Warnings to tell the user during start up.")

(defun vhdl-run-when-idle (secs repeat function)
  "Wait until idle, then run FUNCTION."
  (if vhdl-xemacs
      (start-itimer "vhdl-mode" function secs repeat t)
;    (run-with-idle-timer secs repeat function)))
    ;; explicitely activate timer (necessary when Emacs is already idle)
    (aset (run-with-idle-timer secs repeat function) 0 nil)))

(defun vhdl-warning-when-idle (&rest args)
  "Wait until idle, then print out warning STRING and beep."
  (if noninteractive
      (vhdl-warning (apply 'format args) t)
    (unless vhdl-warnings
      (vhdl-run-when-idle .1 nil 'vhdl-print-warnings))
    (setq vhdl-warnings (cons (apply 'format args) vhdl-warnings))))

(defun vhdl-warning (string &optional nobeep)
  "Print out warning STRING and beep."
  (message (concat "WARNING:  " string))
  (unless (or nobeep noninteractive) (beep)))

(defun vhdl-print-warnings ()
  "Print out messages in variable `vhdl-warnings'."
  (let ((no-warnings (length vhdl-warnings)))
    (setq vhdl-warnings (nreverse vhdl-warnings))
    (while vhdl-warnings
      (message (concat "WARNING:  " (car vhdl-warnings)))
      (setq vhdl-warnings (cdr vhdl-warnings)))
    (beep)
    (when (> no-warnings 1)
      (message "WARNING:  See warning messages in \"%s\" buffer (type `C-c M-m')."
	       (if vhdl-xemacs " *Message-log*" "*Messages*")))))

;; Backward compatibility checks and fixes
;; option `vhdl-compiler' changed format
(unless (stringp vhdl-compiler)
  (setq vhdl-compiler "ModelSim")
  (vhdl-warning-when-idle "Option `vhdl-compiler' has changed format; customize again"))

;; option `vhdl-standard' changed format
(unless (listp vhdl-standard)
  (setq vhdl-standard '(87 nil))
  (vhdl-warning-when-idle "Option `vhdl-standard' has changed format; customize again"))

;; option `vhdl-model-alist' changed format
(when (= (length (car vhdl-model-alist)) 3)
  (let ((old-alist vhdl-model-alist)
	new-alist)
    (while old-alist
      (setq new-alist (cons (append (car old-alist) '("")) new-alist))
      (setq old-alist (cdr old-alist)))
    (setq vhdl-model-alist (nreverse new-alist))))

;; option `vhdl-project-alist' changed format
(when (= (length (car vhdl-project-alist)) 3)
  (let ((old-alist vhdl-project-alist)
	new-alist)
    (while old-alist
      (setq new-alist (cons (append (car old-alist) '("")) new-alist))
      (setq old-alist (cdr old-alist)))
    (setq vhdl-project-alist (nreverse new-alist))))

;; option `vhdl-project-alist' changed format (3.31.1)
(when (= (length (car vhdl-project-alist)) 4)
  (let ((old-alist vhdl-project-alist)
	new-alist elem)
    (while old-alist
      (setq elem (car old-alist))
      (setq new-alist
	    (cons (list (nth 0 elem) (nth 1 elem) "" (nth 2 elem)
			nil "./" "work" "work/" "Makefile" (nth 3 elem))
		  new-alist))
      (setq old-alist (cdr old-alist)))
    (setq vhdl-project-alist (nreverse new-alist)))
  (vhdl-warning-when-idle "Option `vhdl-project-alist' changed format; please re-customize"))

;; option `vhdl-project-alist' changed format (3.31.12)
(when (= (length (car vhdl-project-alist)) 10)
  (let ((tmp-alist vhdl-project-alist))
    (while tmp-alist
      (setcdr (nthcdr 3 (car tmp-alist))
	      (cons "" (nthcdr 4 (car tmp-alist))))
      (setq tmp-alist (cdr tmp-alist)))))

;; option `vhdl-compiler-alist' changed format (3.31.1)
(when (= (length (car vhdl-compiler-alist)) 7)
  (let ((old-alist vhdl-compiler-alist)
	new-alist elem)
    (while old-alist
      (setq elem (car old-alist))
      (setq new-alist
	    (cons (list (nth 0 elem) (nth 1 elem) "" "make -f \\1"
			(if (equal (nth 3 elem) "") nil (nth 3 elem))
			(nth 4 elem) "work/" "Makefile" (downcase (nth 0 elem))
			(nth 5 elem) (nth 6 elem) nil)
		  new-alist))
      (setq old-alist (cdr old-alist)))
    (setq vhdl-compiler-alist (nreverse new-alist)))
  (vhdl-warning-when-idle "Option `vhdl-compiler-alist' changed; please reset and re-customize"))

;; option `vhdl-compiler-alist' changed format (3.31.10)
(when (= (length (car vhdl-compiler-alist)) 12)
  (let ((tmp-alist vhdl-compiler-alist))
    (while tmp-alist
      (setcdr (nthcdr 4 (car tmp-alist))
	      (cons "mkdir \\1" (nthcdr 5 (car tmp-alist))))
      (setq tmp-alist (cdr tmp-alist)))))

;; option `vhdl-compiler-alist' changed format (3.31.11)
(when (= (length (car vhdl-compiler-alist)) 13)
  (let ((tmp-alist vhdl-compiler-alist))
    (while tmp-alist
      (setcdr (nthcdr 3 (car tmp-alist))
	      (cons "" (nthcdr 4 (car tmp-alist))))
      (setq tmp-alist (cdr tmp-alist)))))

;; option `vhdl-project': empty value changed from "" to nil (3.31.1)
(when (equal vhdl-project "") (setq vhdl-project nil))

;; option `vhdl-project-file-name': changed format (3.31.17 beta)
(when (stringp vhdl-project-file-name)
  (setq vhdl-project-file-name (list vhdl-project-file-name)))

;; option `speedbar-indentation-width': introduced in speedbar 0.10
(if (not (boundp 'speedbar-indentation-width))
    (defvar speedbar-indentation-width 2)
  ;; set default to 2 if not already customized
  (when (not (get 'speedbar-indentation-width 'saved-value))
    (setq speedbar-indentation-width 2)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Help functions / inline substitutions / macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defsubst vhdl-standard-p (standard)
  "Check if STANDARD is specified as used standard."
  (or (eq standard (car vhdl-standard))
       (memq standard (cadr vhdl-standard))))

(defsubst vhdl-project-p (&optional warning)
  "Return non-nil if a project is displayed, i.e. directories or files are
specified."
  (if (assoc vhdl-project vhdl-project-alist)
      vhdl-project
    (when (and vhdl-project warning)
      (vhdl-warning-when-idle "Project does not exist: \"%s\"" vhdl-project))
    nil))

(defsubst vhdl-resolve-env-variable (string)
  "Resolve environment variables in STRING."
  (while (string-match "\\(.*\\)${?\\(\\(\\w\\|_\\)+\\)}?\\(.*\\)" string)
    (setq string (concat (match-string 1 string)
			 (getenv (match-string 2 string))
			 (match-string 4 string))))
  string)

(defsubst vhdl-default-directory ()
  "Return the default directory of the current project or the directory of the
current buffer if no project is defined."
  (if (vhdl-project-p)
      (expand-file-name (vhdl-resolve-env-variable
			 (nth 1 (aget vhdl-project-alist vhdl-project))))
    default-directory))

(defmacro vhdl-prepare-search-1 (&rest body)
  "Enable case insensitive search and switch to syntax table that includes '_',
then execute BODY, and finally restore the old environment.  Used for
consistent searching."
  `(let ((case-fold-search t)		; case insensitive search
	 (current-syntax-table (syntax-table))
	 result
	 (restore-prog			; program to restore enviroment
	  '(progn
	     ;; restore syntax table
	     (set-syntax-table current-syntax-table))))
     ;; use extended syntax table
     (set-syntax-table vhdl-mode-ext-syntax-table)
     ;; execute BODY safely
     (setq result
	   (condition-case info
	       (progn ,@body)
	     (error (eval restore-prog)	; restore environment on error
		    (error (cadr info))))) ; pass error up
     ;; restore environment
     (eval restore-prog)
     result))

(defmacro vhdl-prepare-search-2 (&rest body)
  "Enable case insensitive search, switch to syntax table that includes '_',
and remove `intangible' overlays, then execute BODY, and finally restore the
old environment.  Used for consistent searching."
  `(let ((case-fold-search t)		; case insensitive search
	 (current-syntax-table (syntax-table))
	 result overlay-all-list overlay-intangible-list overlay
	 (restore-prog			; program to restore enviroment
	  '(progn
	     ;; restore syntax table
	     (set-syntax-table current-syntax-table)
	     ;; restore `intangible' overlays
	     (when (fboundp 'overlay-lists)
	       (while overlay-intangible-list
		 (overlay-put (car overlay-intangible-list) 'intangible t)
		 (setq overlay-intangible-list
		       (cdr overlay-intangible-list)))))))
     ;; use extended syntax table
     (set-syntax-table vhdl-mode-ext-syntax-table)
     ;; remove `intangible' overlays
     (when (fboundp 'overlay-lists)
       (setq overlay-all-list (overlay-lists))
       (setq overlay-all-list
	     (append (car overlay-all-list) (cdr overlay-all-list)))
       (while overlay-all-list
	 (setq overlay (car overlay-all-list))
	 (when (memq 'intangible (overlay-properties overlay))
	   (setq overlay-intangible-list
		 (cons overlay overlay-intangible-list))
	   (overlay-put overlay 'intangible nil))
	 (setq overlay-all-list (cdr overlay-all-list))))
     ;; execute BODY safely
     (setq result
	   (condition-case info
	       (progn ,@body)
	     (error (eval restore-prog)	; restore environment on error
		    (error (cadr info))))) ; pass error up
     ;; restore environment
     (eval restore-prog)
     result))

(defmacro vhdl-visit-file (file-name &rest body)
  "Visit file FILE-NAME and execute BODY."
  `(if (null ,file-name)
       (progn ,@body)
     (unless (file-directory-p ,file-name)
       (let ((source-buffer (current-buffer))
	     buf file-opened)
	 (if (find-buffer-visiting ,file-name)
	     (set-buffer (file-name-nondirectory ,file-name))
	   (unless (file-exists-p ,file-name)
	     (vhdl-warning (format "File not found: \"%s\"" ,file-name) t))
;	(set-buffer (find-file-noselect ,file-name nil t))
	   (set-buffer (create-file-buffer ,file-name))
	   (vhdl-insert-file-contents ,file-name)
	   (modify-syntax-entry ?\- ". 12" (syntax-table))
	   (modify-syntax-entry ?\n ">" (syntax-table))
	   (modify-syntax-entry ?\^M ">" (syntax-table))
	   (modify-syntax-entry ?_ "w" (syntax-table))
	   (setq file-opened t))
	 (condition-case info
	     (progn ,@body)
	   (error
	    (when file-opened (kill-buffer (current-buffer)))
	    (set-buffer source-buffer)
	    (error (cadr info))))
	 (when file-opened (kill-buffer (current-buffer)))
	 (set-buffer source-buffer)))))

(defun vhdl-insert-file-contents (filename)
  "Nicked from `insert-file-contents-literally', but allow coding system
conversion."
  (let ((format-alist nil)
	(after-insert-file-functions nil)
	(jka-compr-compression-info-list nil))
    (insert-file-contents filename t)))

(defun vhdl-sort-alist (alist)
  "Sort alist."
  (sort alist (function (lambda (a b) (string< (car a) (car b))))))

(defun vhdl-get-subdirs (directory)
  "Recursively get subdirectories of DIRECTORY."
  (let ((dir-list (list (file-name-as-directory directory)))
	file-list)
    (setq file-list (vhdl-directory-files directory t "\\w.*"))
    (while file-list
      (when (file-directory-p (car file-list))
	(setq dir-list (nconc dir-list (vhdl-get-subdirs (car file-list)))))
      (setq file-list (cdr file-list)))
    dir-list))

(defsubst vhdl-aput (alist-symbol key &optional value)
  "As `aput', but delete key-value pair if VALUE is nil."
  (if value
      (aput alist-symbol key value)
    (adelete alist-symbol key)))

(defun vhdl-delete (elt list)
  "Delete by side effect the first occurrence of ELT as a member of LIST."
  (setq list (cons nil list))
  (let ((list1 list))
    (while (and (cdr list1) (not (equal elt (cadr list1))))
      (setq list1 (cdr list1)))
    (when list
      (setcdr list1 (cddr list1))))
  (cdr list))

(defun vhdl-speedbar-refresh (&optional key)
  "Refresh directory or project with name KEY."
  (when (and (boundp 'speedbar-frame)
	     (frame-live-p speedbar-frame))
    (let ((pos (point))
	  (last-frame (selected-frame)))
      (if (null key)
	  (speedbar-refresh)
	(select-frame speedbar-frame)
	(when (save-excursion
		(goto-char (point-min))
		(re-search-forward (concat "^\\([0-9]+:\\s-*<\\)->\\s-+" key "$") nil t))
	  (goto-char (match-end 1))
	  (speedbar-do-function-pointer)
	  (backward-char 2)
	  (speedbar-do-function-pointer)
	  (message "Refreshing speedbar...done"))
	(select-frame last-frame)))))

(defun vhdl-show-messages ()
  "Get *Messages* buffer to show recent messages."
  (interactive)
  (display-buffer (if vhdl-xemacs " *Message-Log*" "*Messages*")))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Bindings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key bindings

(defvar vhdl-template-map nil
  "Keymap for VHDL templates.")

(defun vhdl-template-map-init ()
  "Initialize `vhdl-template-map'."
  (setq vhdl-template-map (make-sparse-keymap))
  ;; key bindings for VHDL templates
  (define-key vhdl-template-map "al"	'vhdl-template-alias)
  (define-key vhdl-template-map "ar"	'vhdl-template-architecture)
  (define-key vhdl-template-map "at"	'vhdl-template-assert)
  (define-key vhdl-template-map "ad"	'vhdl-template-attribute-decl)
  (define-key vhdl-template-map "as"	'vhdl-template-attribute-spec)
  (define-key vhdl-template-map "bl"	'vhdl-template-block)
  (define-key vhdl-template-map "ca"	'vhdl-template-case-is)
  (define-key vhdl-template-map "cd"	'vhdl-template-component-decl)
  (define-key vhdl-template-map "ci"	'vhdl-template-component-inst)
  (define-key vhdl-template-map "cs"	'vhdl-template-conditional-signal-asst)
  (define-key vhdl-template-map "Cb"	'vhdl-template-block-configuration)
  (define-key vhdl-template-map "Cc"	'vhdl-template-component-conf)
  (define-key vhdl-template-map "Cd"	'vhdl-template-configuration-decl)
  (define-key vhdl-template-map "Cs"	'vhdl-template-configuration-spec)
  (define-key vhdl-template-map "co"	'vhdl-template-constant)
  (define-key vhdl-template-map "di"	'vhdl-template-disconnect)
  (define-key vhdl-template-map "el"	'vhdl-template-else)
  (define-key vhdl-template-map "ei"	'vhdl-template-elsif)
  (define-key vhdl-template-map "en"	'vhdl-template-entity)
  (define-key vhdl-template-map "ex"	'vhdl-template-exit)
  (define-key vhdl-template-map "fi"	'vhdl-template-file)
  (define-key vhdl-template-map "fg"	'vhdl-template-for-generate)
  (define-key vhdl-template-map "fl"	'vhdl-template-for-loop)
  (define-key vhdl-template-map "\C-f"	'vhdl-template-footer)
  (define-key vhdl-template-map "fb"	'vhdl-template-function-body)
  (define-key vhdl-template-map "fd"	'vhdl-template-function-decl)
  (define-key vhdl-template-map "ge"	'vhdl-template-generic)
  (define-key vhdl-template-map "gd"	'vhdl-template-group-decl)
  (define-key vhdl-template-map "gt"	'vhdl-template-group-template)
  (define-key vhdl-template-map "\C-h"	'vhdl-template-header)
  (define-key vhdl-template-map "ig"	'vhdl-template-if-generate)
  (define-key vhdl-template-map "it"	'vhdl-template-if-then)
  (define-key vhdl-template-map "li"	'vhdl-template-library)
  (define-key vhdl-template-map "lo"	'vhdl-template-bare-loop)
  (define-key vhdl-template-map "\C-m"	'vhdl-template-modify)
  (define-key vhdl-template-map "\C-t"	'vhdl-template-insert-date)
  (define-key vhdl-template-map "ma"	'vhdl-template-map)
  (define-key vhdl-template-map "ne"	'vhdl-template-next)
  (define-key vhdl-template-map "ot"	'vhdl-template-others)
  (define-key vhdl-template-map "Pd"	'vhdl-template-package-decl)
  (define-key vhdl-template-map "Pb"	'vhdl-template-package-body)
  (define-key vhdl-template-map "("     'vhdl-template-paired-parens)
  (define-key vhdl-template-map "po"	'vhdl-template-port)
  (define-key vhdl-template-map "pb"	'vhdl-template-procedure-body)
  (define-key vhdl-template-map "pd"	'vhdl-template-procedure-decl)
  (define-key vhdl-template-map "pc"	'vhdl-template-process-comb)
  (define-key vhdl-template-map "ps"	'vhdl-template-process-seq)
  (define-key vhdl-template-map "rp"	'vhdl-template-report)
  (define-key vhdl-template-map "rt"	'vhdl-template-return)
  (define-key vhdl-template-map "ss"	'vhdl-template-selected-signal-asst)
  (define-key vhdl-template-map "si"	'vhdl-template-signal)
  (define-key vhdl-template-map "su"	'vhdl-template-subtype)
  (define-key vhdl-template-map "ty"	'vhdl-template-type)
  (define-key vhdl-template-map "us"	'vhdl-template-use)
  (define-key vhdl-template-map "va"	'vhdl-template-variable)
  (define-key vhdl-template-map "wa"	'vhdl-template-wait)
  (define-key vhdl-template-map "wl"	'vhdl-template-while-loop)
  (define-key vhdl-template-map "wi"	'vhdl-template-with)
  (define-key vhdl-template-map "wc"	'vhdl-template-clocked-wait)
  (define-key vhdl-template-map "\C-pb" 'vhdl-template-package-numeric-bit)
  (define-key vhdl-template-map "\C-pn" 'vhdl-template-package-numeric-std)
  (define-key vhdl-template-map "\C-ps" 'vhdl-template-package-std-logic-1164)
  (define-key vhdl-template-map "\C-pA" 'vhdl-template-package-std-logic-arith)
  (define-key vhdl-template-map "\C-pM" 'vhdl-template-package-std-logic-misc)
  (define-key vhdl-template-map "\C-pS" 'vhdl-template-package-std-logic-signed)
  (define-key vhdl-template-map "\C-pT" 'vhdl-template-package-std-logic-textio)
  (define-key vhdl-template-map "\C-pU" 'vhdl-template-package-std-logic-unsigned)
  (define-key vhdl-template-map "\C-pt" 'vhdl-template-package-textio)
  (define-key vhdl-template-map "\C-dn" 'vhdl-template-directive-translate-on)
  (define-key vhdl-template-map "\C-df" 'vhdl-template-directive-translate-off)
  (define-key vhdl-template-map "\C-dN" 'vhdl-template-directive-synthesis-on)
  (define-key vhdl-template-map "\C-dF" 'vhdl-template-directive-synthesis-off)
  (define-key vhdl-template-map "\C-q"  'vhdl-template-search-prompt)
  (when (vhdl-standard-p 'ams)
    (define-key vhdl-template-map "br"	'vhdl-template-break)
    (define-key vhdl-template-map "cu"	'vhdl-template-case-use)
    (define-key vhdl-template-map "iu"	'vhdl-template-if-use)
    (define-key vhdl-template-map "lm"	'vhdl-template-limit)
    (define-key vhdl-template-map "na"	'vhdl-template-nature)
    (define-key vhdl-template-map "pa"	'vhdl-template-procedural)
    (define-key vhdl-template-map "qf"	'vhdl-template-quantity-free)
    (define-key vhdl-template-map "qb"	'vhdl-template-quantity-branch)
    (define-key vhdl-template-map "qs"	'vhdl-template-quantity-source)
    (define-key vhdl-template-map "sn"	'vhdl-template-subnature)
    (define-key vhdl-template-map "te"	'vhdl-template-terminal)
    )
  (when (vhdl-standard-p 'math)
    (define-key vhdl-template-map "\C-pc" 'vhdl-template-package-math-complex)
    (define-key vhdl-template-map "\C-pr" 'vhdl-template-package-math-real)
    ))

;; initialize template map for VHDL Mode
(vhdl-template-map-init)

(defun vhdl-function-name (prefix string &optional postfix)
  "Generate a Lisp function name.
PREFIX, STRING and optional POSTFIX are concatenated by '-' and spaces in
STRING are replaced by `-' and substrings are converted to lower case."
  (let ((name prefix))
    (while (string-match "\\(\\w+\\)\\s-*\\(.*\\)" string)
      (setq name
	    (concat name "-" (downcase (substring string 0 (match-end 1)))))
      (setq string (substring string (match-beginning 2))))
    (when postfix (setq name (concat name "-" postfix)))
    (intern name)))

(defvar vhdl-model-map nil
  "Keymap for VHDL models.")

(defun vhdl-model-map-init ()
  "Initialize `vhdl-model-map'."
  (setq vhdl-model-map (make-sparse-keymap))
  ;; key bindings for VHDL models
  (let ((model-alist vhdl-model-alist) model)
    (while model-alist
      (setq model (car model-alist))
      (define-key vhdl-model-map (nth 2 model)
	(vhdl-function-name "vhdl-model" (nth 0 model)))
      (setq model-alist (cdr model-alist)))))

;; initialize user model map for VHDL Mode
(vhdl-model-map-init)

(defvar vhdl-mode-map nil
  "Keymap for VHDL Mode.")

(defun vhdl-mode-map-init ()
  "Initialize `vhdl-mode-map'."
  (setq vhdl-mode-map (make-sparse-keymap))
  ;; template key bindings
  (define-key vhdl-mode-map "\C-c\C-t"     vhdl-template-map)
  ;; model key bindings
  (define-key vhdl-mode-map "\C-c\C-m"     vhdl-model-map)
  ;; standard key bindings
  (define-key vhdl-mode-map "\M-a"         'vhdl-beginning-of-statement)
  (define-key vhdl-mode-map "\M-e"         'vhdl-end-of-statement)
  (define-key vhdl-mode-map "\M-\C-f"      'vhdl-forward-sexp)
  (define-key vhdl-mode-map "\M-\C-b"      'vhdl-backward-sexp)
  (define-key vhdl-mode-map "\M-\C-u"      'vhdl-backward-up-list)
  (define-key vhdl-mode-map "\M-\C-a"      'vhdl-backward-same-indent)
  (define-key vhdl-mode-map "\M-\C-e"      'vhdl-forward-same-indent)
  (unless vhdl-xemacs ; would override `M-backspace' in XEmacs
    (define-key vhdl-mode-map "\M-\C-h"      'vhdl-mark-defun))
  (define-key vhdl-mode-map "\M-\C-q"      'vhdl-indent-sexp)
  (define-key vhdl-mode-map "\M-^"         'vhdl-delete-indentation)
  ;; backspace/delete key bindings
  (define-key vhdl-mode-map [backspace]    'backward-delete-char-untabify)
  (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
    (define-key vhdl-mode-map [delete]       'delete-char)
    (define-key vhdl-mode-map [(meta delete)] 'kill-word))
  ;; mode specific key bindings
  (define-key vhdl-mode-map "\C-c\C-m\C-e" 'vhdl-electric-mode)
  (define-key vhdl-mode-map "\C-c\C-m\C-s" 'vhdl-stutter-mode)
  (define-key vhdl-mode-map "\C-c\C-s\C-p" 'vhdl-set-project)
  (define-key vhdl-mode-map "\C-c\C-p\C-d" 'vhdl-duplicate-project)
  (define-key vhdl-mode-map "\C-c\C-p\C-m" 'vhdl-import-project)
  (define-key vhdl-mode-map "\C-c\C-p\C-x" 'vhdl-export-project)
  (define-key vhdl-mode-map "\C-c\C-s\C-k" 'vhdl-set-compiler)
  (define-key vhdl-mode-map "\C-c\C-k"     'vhdl-compile)
  (define-key vhdl-mode-map "\C-c\M-\C-k"  'vhdl-make)
  (define-key vhdl-mode-map "\C-c\M-k"	   'vhdl-generate-makefile)
  (define-key vhdl-mode-map "\C-c\C-p\C-w" 'vhdl-port-copy)
  (define-key vhdl-mode-map "\C-c\C-p\M-w" 'vhdl-port-copy)
  (define-key vhdl-mode-map "\C-c\C-p\C-e" 'vhdl-port-paste-entity)
  (define-key vhdl-mode-map "\C-c\C-p\C-c" 'vhdl-port-paste-component)
  (define-key vhdl-mode-map "\C-c\C-p\C-i" 'vhdl-port-paste-instance)
  (define-key vhdl-mode-map "\C-c\C-p\C-s" 'vhdl-port-paste-signals)
  (define-key vhdl-mode-map "\C-c\C-p\M-c" 'vhdl-port-paste-constants)
  (if vhdl-xemacs ; `... C-g' not allowed in XEmacs
      (define-key vhdl-mode-map "\C-c\C-p\M-g" 'vhdl-port-paste-generic-map)
    (define-key vhdl-mode-map "\C-c\C-p\C-g" 'vhdl-port-paste-generic-map))
  (define-key vhdl-mode-map "\C-c\C-p\C-z" 'vhdl-port-paste-initializations)
  (define-key vhdl-mode-map "\C-c\C-p\C-t" 'vhdl-port-paste-testbench)
  (define-key vhdl-mode-map "\C-c\C-p\C-f" 'vhdl-port-flatten)
  (define-key vhdl-mode-map "\C-c\C-c"     'vhdl-comment-uncomment-region)
  (define-key vhdl-mode-map "\C-c-"        'vhdl-comment-append-inline)
  (define-key vhdl-mode-map "\C-c\M--"     'vhdl-comment-display-line)
  (define-key vhdl-mode-map "\C-c\C-i\C-l" 'indent-according-to-mode)
  (define-key vhdl-mode-map "\C-c\C-i\C-g" 'vhdl-indent-group)
  (define-key vhdl-mode-map "\M-\C-\\"     'vhdl-indent-region)
  (define-key vhdl-mode-map "\C-c\C-i\C-b" 'vhdl-indent-buffer)
  (define-key vhdl-mode-map "\C-c\C-a\C-a" 'vhdl-align-group)
  (define-key vhdl-mode-map "\C-c\C-a\C-i" 'vhdl-align-same-indent)
  (define-key vhdl-mode-map "\C-c\C-a\C-l" 'vhdl-align-list)
  (define-key vhdl-mode-map "\C-c\C-a\C-d" 'vhdl-align-declarations)
  (define-key vhdl-mode-map "\C-c\C-a\M-a" 'vhdl-align-region)
  (define-key vhdl-mode-map "\C-c\C-a\C-b" 'vhdl-align-buffer)
  (define-key vhdl-mode-map "\C-c\C-a\C-c" 'vhdl-align-inline-comment-group)
  (define-key vhdl-mode-map "\C-c\C-a\M-c" 'vhdl-align-inline-comment-region)
  (define-key vhdl-mode-map "\C-c\C-l\C-w" 'vhdl-line-kill)
  (define-key vhdl-mode-map "\C-c\C-l\M-w" 'vhdl-line-copy)
  (define-key vhdl-mode-map "\C-c\C-l\C-y" 'vhdl-line-yank)
  (define-key vhdl-mode-map "\C-c\C-l\t"   'vhdl-line-expand)
  (define-key vhdl-mode-map "\C-c\C-l\C-n" 'vhdl-line-transpose-next)
  (define-key vhdl-mode-map "\C-c\C-l\C-p" 'vhdl-line-transpose-previous)
  (define-key vhdl-mode-map "\C-c\C-l\C-o" 'vhdl-line-open)
  (define-key vhdl-mode-map "\C-c\C-l\C-g" 'goto-line)
  (define-key vhdl-mode-map "\C-c\C-l\C-c" 'vhdl-comment-uncomment-line)
  (define-key vhdl-mode-map "\C-c\C-x\C-p" 'vhdl-fix-clause)
  (define-key vhdl-mode-map "\C-c\C-x\M-c" 'vhdl-fix-case-region)
  (define-key vhdl-mode-map "\C-c\C-x\C-c" 'vhdl-fix-case-buffer)
  (define-key vhdl-mode-map "\C-c\C-x\M-w" 'vhdl-fixup-whitespace-region)
  (define-key vhdl-mode-map "\C-c\C-x\C-w" 'vhdl-fixup-whitespace-buffer)
  (define-key vhdl-mode-map "\C-c\M-b"     'vhdl-beautify-region)
  (define-key vhdl-mode-map "\C-c\C-b"     'vhdl-beautify-buffer)
  (define-key vhdl-mode-map "\C-c\C-u\C-s" 'vhdl-update-sensitivity-list-process)
  (define-key vhdl-mode-map "\C-c\C-u\M-s" 'vhdl-update-sensitivity-list-buffer)
  (define-key vhdl-mode-map "\C-c\C-f"     'vhdl-fontify-buffer)
  (define-key vhdl-mode-map "\C-c\M-m"     'vhdl-show-messages)
  (define-key vhdl-mode-map "\C-c\C-h"     'vhdl-doc-mode)
  (define-key vhdl-mode-map "\C-c\C-v"     'vhdl-version)
  (define-key vhdl-mode-map "\M-\t"        'tab-to-tab-stop)
  ;; insert commands bindings
  (define-key vhdl-mode-map "\C-c\C-i\C-t" 'vhdl-template-insert-construct)
  (define-key vhdl-mode-map "\C-c\C-i\C-p" 'vhdl-template-insert-package)
  (define-key vhdl-mode-map "\C-c\C-i\C-d" 'vhdl-template-insert-directive)
  (define-key vhdl-mode-map "\C-c\C-i\C-m" 'vhdl-model-insert)
  ;; electric key bindings
  (define-key vhdl-mode-map " "            'vhdl-electric-space)
  (if vhdl-intelligent-tab
      (define-key vhdl-mode-map "\t"       'vhdl-electric-tab)
    (define-key vhdl-mode-map "\t"         'indent-according-to-mode))
  (define-key vhdl-mode-map "\r"           'vhdl-electric-return)
  (define-key vhdl-mode-map "-"            'vhdl-electric-dash)
  (define-key vhdl-mode-map "["            'vhdl-electric-open-bracket)
  (define-key vhdl-mode-map "]"            'vhdl-electric-close-bracket)
  (define-key vhdl-mode-map "'"            'vhdl-electric-quote)
  (define-key vhdl-mode-map ";"            'vhdl-electric-semicolon)
  (define-key vhdl-mode-map ","            'vhdl-electric-comma)
  (define-key vhdl-mode-map "."            'vhdl-electric-period)
  (when (vhdl-standard-p 'ams)
    (define-key vhdl-mode-map "="          'vhdl-electric-equal)))

;; initialize mode map for VHDL Mode
(vhdl-mode-map-init)

;; define special minibuffer keymap for enabling word completion in minibuffer
;; (useful in template generator prompts)
(defvar vhdl-minibuffer-local-map (copy-keymap minibuffer-local-map)
  "Keymap for minibuffer used in VHDL Mode.")

(when vhdl-word-completion-in-minibuffer
  (define-key vhdl-minibuffer-local-map "\t" 'vhdl-minibuffer-tab))

;; set up electric character functions to work with
;; `delete-selection-mode' (Emacs) and `pending-delete-mode' (XEmacs)
(mapcar
 (function
  (lambda (sym)
    (put sym 'delete-selection t)	; for `delete-selection-mode' (Emacs)
    (put sym 'pending-delete t)))	; for `pending-delete-mode' (XEmacs)
 '(vhdl-electric-space
   vhdl-electric-tab
   vhdl-electric-return
   vhdl-electric-dash
   vhdl-electric-open-bracket
   vhdl-electric-close-bracket
   vhdl-electric-quote
   vhdl-electric-semicolon
   vhdl-electric-comma
   vhdl-electric-period
   vhdl-electric-equal))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Syntax table

(defvar vhdl-mode-syntax-table nil
  "Syntax table used in `vhdl-mode' buffers.")

(defvar vhdl-mode-ext-syntax-table nil
  "Syntax table extended by `_' used in `vhdl-mode' buffers.")

(defun vhdl-mode-syntax-table-init ()
  "Initialize `vhdl-mode-syntax-table'."
  (setq vhdl-mode-syntax-table (make-syntax-table))
  ;; define punctuation
  (modify-syntax-entry ?\# "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\$ "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\% "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\& "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\' "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\* "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\+ "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\. "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\/ "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\: "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\; "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\< "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\= "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\> "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\\ "."    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\| "."    vhdl-mode-syntax-table)
  ;; define string
  (modify-syntax-entry ?\" "\""   vhdl-mode-syntax-table)
  ;; define underscore
  (when vhdl-underscore-is-part-of-word
    (modify-syntax-entry ?\_ "w"   vhdl-mode-syntax-table))
  ;; a single hyphen is punctuation, but a double hyphen starts a comment
  (modify-syntax-entry ?\- ". 12" vhdl-mode-syntax-table)
  ;; and \n and \^M end a comment
  (modify-syntax-entry ?\n ">"    vhdl-mode-syntax-table)
  (modify-syntax-entry ?\^M ">"   vhdl-mode-syntax-table)
  ;; define parentheses to match
  (modify-syntax-entry ?\( "()"   vhdl-mode-syntax-table)
  (modify-syntax-entry ?\) ")("   vhdl-mode-syntax-table)
  (modify-syntax-entry ?\[ "(]"   vhdl-mode-syntax-table)
  (modify-syntax-entry ?\] ")["   vhdl-mode-syntax-table)
  (modify-syntax-entry ?\{ "(}"   vhdl-mode-syntax-table)
  (modify-syntax-entry ?\} "){"   vhdl-mode-syntax-table)
  ;; extended syntax table including '_' (for simpler search regexps)
  (setq vhdl-mode-ext-syntax-table (copy-syntax-table vhdl-mode-syntax-table))
  (modify-syntax-entry ?_ "w" vhdl-mode-ext-syntax-table))

;; initialize syntax table for VHDL Mode
(vhdl-mode-syntax-table-init)

(defvar vhdl-syntactic-context nil
  "Buffer local variable containing syntactic analysis list.")
(make-variable-buffer-local 'vhdl-syntactic-context)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Abbrev ook bindings

(defvar vhdl-mode-abbrev-table nil
  "Abbrev table to use in `vhdl-mode' buffers.")

(defun vhdl-mode-abbrev-table-init ()
  "Initialize `vhdl-mode-abbrev-table'."
  (when vhdl-mode-abbrev-table (clear-abbrev-table vhdl-mode-abbrev-table))
  (define-abbrev-table 'vhdl-mode-abbrev-table
    (append
     (when (memq 'vhdl vhdl-electric-keywords)
       ;; VHDL'93 keywords
       '(
	 ("--"            "" vhdl-template-display-comment-hook 0)
	 ("abs"           "" vhdl-template-default-hook 0)
	 ("access"        "" vhdl-template-default-hook 0)
	 ("after"         "" vhdl-template-default-hook 0)
	 ("alias"         "" vhdl-template-alias-hook 0)
	 ("all"           "" vhdl-template-default-hook 0)
	 ("and"           "" vhdl-template-default-hook 0)
	 ("arch"          "" vhdl-template-architecture-hook 0)
	 ("architecture"  "" vhdl-template-architecture-hook 0)
	 ("array"         "" vhdl-template-default-hook 0)
	 ("assert"        "" vhdl-template-assert-hook 0)
	 ("attr"          "" vhdl-template-attribute-hook 0)
	 ("attribute"     "" vhdl-template-attribute-hook 0)
	 ("begin"         "" vhdl-template-default-indent-hook 0)
	 ("block"         "" vhdl-template-block-hook 0)
	 ("body"          "" vhdl-template-default-hook 0)
	 ("buffer"        "" vhdl-template-default-hook 0)
	 ("bus"           "" vhdl-template-default-hook 0)
	 ("case"          "" vhdl-template-case-hook 0)
	 ("comp"          "" vhdl-template-component-hook 0)
	 ("component"     "" vhdl-template-component-hook 0)
	 ("cond"          "" vhdl-template-conditional-signal-asst-hook 0)
	 ("conditional"   "" vhdl-template-conditional-signal-asst-hook 0)
	 ("conf"          "" vhdl-template-configuration-hook 0)
	 ("configuration" "" vhdl-template-configuration-hook 0)
	 ("cons"          "" vhdl-template-constant-hook 0)
	 ("constant"      "" vhdl-template-constant-hook 0)
	 ("disconnect"    "" vhdl-template-disconnect-hook 0)
	 ("downto"        "" vhdl-template-default-hook 0)
	 ("else"          "" vhdl-template-else-hook 0)
	 ("elseif"        "" vhdl-template-elsif-hook 0)
	 ("elsif"         "" vhdl-template-elsif-hook 0)
	 ("end"           "" vhdl-template-default-indent-hook 0)
	 ("entity"        "" vhdl-template-entity-hook 0)
	 ("exit"          "" vhdl-template-exit-hook 0)
	 ("file"          "" vhdl-template-file-hook 0)
	 ("for"           "" vhdl-template-for-hook 0)
	 ("func"          "" vhdl-template-function-hook 0)
	 ("function"      "" vhdl-template-function-hook 0)
	 ("generic"       "" vhdl-template-generic-hook 0)
	 ("group"         "" vhdl-template-group-hook 0)
	 ("guarded"       "" vhdl-template-default-hook 0)
	 ("if"            "" vhdl-template-if-hook 0)
	 ("impure"        "" vhdl-template-default-hook 0)
	 ("in"            "" vhdl-template-default-hook 0)
	 ("inertial"      "" vhdl-template-default-hook 0)
	 ("inout"         "" vhdl-template-default-hook 0)
	 ("inst"          "" vhdl-template-instance-hook 0)
	 ("instance"      "" vhdl-template-instance-hook 0)
	 ("is"            "" vhdl-template-default-hook 0)
	 ("label"         "" vhdl-template-default-hook 0)
	 ("library"       "" vhdl-template-library-hook 0)
	 ("linkage"       "" vhdl-template-default-hook 0)
	 ("literal"       "" vhdl-template-default-hook 0)
	 ("loop"          "" vhdl-template-bare-loop-hook 0)
	 ("map"           "" vhdl-template-map-hook 0)
	 ("mod"           "" vhdl-template-default-hook 0)
	 ("nand"          "" vhdl-template-default-hook 0)
	 ("new"           "" vhdl-template-default-hook 0)
	 ("next"          "" vhdl-template-next-hook 0)
	 ("nor"           "" vhdl-template-default-hook 0)
	 ("not"           "" vhdl-template-default-hook 0)
	 ("null"          "" vhdl-template-default-hook 0)
	 ("of"            "" vhdl-template-default-hook 0)
	 ("on"            "" vhdl-template-default-hook 0)
	 ("open"          "" vhdl-template-default-hook 0)
	 ("or"            "" vhdl-template-default-hook 0)
	 ("others"        "" vhdl-template-others-hook 0)
	 ("out"           "" vhdl-template-default-hook 0)
	 ("pack"          "" vhdl-template-package-hook 0)
	 ("package"       "" vhdl-template-package-hook 0)
	 ("port"          "" vhdl-template-port-hook 0)
	 ("postponed"     "" vhdl-template-default-hook 0)
	 ("procedure"     "" vhdl-template-procedure-hook 0)
	 ("process"       "" vhdl-template-process-hook 0)
	 ("pure"          "" vhdl-template-default-hook 0)
	 ("range"         "" vhdl-template-default-hook 0)
	 ("record"        "" vhdl-template-default-hook 0)
	 ("register"      "" vhdl-template-default-hook 0)
	 ("reject"        "" vhdl-template-default-hook 0)
	 ("rem"           "" vhdl-template-default-hook 0)
	 ("report"        "" vhdl-template-report-hook 0)
	 ("return"        "" vhdl-template-return-hook 0)
	 ("rol"           "" vhdl-template-default-hook 0)
	 ("ror"           "" vhdl-template-default-hook 0)
	 ("select"        "" vhdl-template-selected-signal-asst-hook 0)
	 ("severity"      "" vhdl-template-default-hook 0)
	 ("shared"        "" vhdl-template-default-hook 0)
	 ("sig"           "" vhdl-template-signal-hook 0)
	 ("signal"        "" vhdl-template-signal-hook 0)
	 ("sla"           "" vhdl-template-default-hook 0)
	 ("sll"           "" vhdl-template-default-hook 0)
	 ("sra"           "" vhdl-template-default-hook 0)
	 ("srl"           "" vhdl-template-default-hook 0)
	 ("subtype"       "" vhdl-template-subtype-hook 0)
	 ("then"          "" vhdl-template-default-hook 0)
	 ("to"            "" vhdl-template-default-hook 0)
	 ("transport"     "" vhdl-template-default-hook 0)
	 ("type"          "" vhdl-template-type-hook 0)
	 ("unaffected"    "" vhdl-template-default-hook 0)
	 ("units"         "" vhdl-template-default-hook 0)
	 ("until"         "" vhdl-template-default-hook 0)
	 ("use"           "" vhdl-template-use-hook 0)
	 ("var"           "" vhdl-template-variable-hook 0)
	 ("variable"      "" vhdl-template-variable-hook 0)
	 ("wait"          "" vhdl-template-wait-hook 0)
	 ("when"          "" vhdl-template-when-hook 0)
	 ("while"         "" vhdl-template-while-loop-hook 0)
	 ("with"          "" vhdl-template-with-hook 0)
	 ("xnor"          "" vhdl-template-default-hook 0)
	 ("xor"           "" vhdl-template-default-hook 0)
	 ))
     ;; VHDL-AMS keywords
     (when (and (memq 'vhdl vhdl-electric-keywords) (vhdl-standard-p 'ams))
       '(
	 ("across"     "" vhdl-template-default-hook 0)
	 ("break"      "" vhdl-template-break-hook 0)
	 ("limit"      "" vhdl-template-limit-hook 0)
	 ("nature"     "" vhdl-template-nature-hook 0)
	 ("noise"      "" vhdl-template-default-hook 0)
	 ("procedural" "" vhdl-template-procedural-hook 0)
	 ("quantity"   "" vhdl-template-quantity-hook 0)
	 ("reference"  "" vhdl-template-default-hook 0)
	 ("spectrum"   "" vhdl-template-default-hook 0)
	 ("subnature"  "" vhdl-template-subnature-hook 0)
	 ("terminal"   "" vhdl-template-terminal-hook 0)
	 ("through"    "" vhdl-template-default-hook 0)
	 ("tolerance"  "" vhdl-template-default-hook 0)
	 ))
     ;; user model keywords
     (when (memq 'user vhdl-electric-keywords)
       (let ((alist vhdl-model-alist)
	     abbrev-list keyword)
	 (while alist
	   (setq keyword (nth 3 (car alist)))
	   (unless (equal keyword "")
	     (setq abbrev-list
		   (cons (list keyword ""
			       (vhdl-function-name
				"vhdl-model" (nth 0 (car alist)) "hook") 0)
			 abbrev-list)))
	   (setq alist (cdr alist)))
	 abbrev-list)))))

;; initialize abbrev table for VHDL Mode
(vhdl-mode-abbrev-table-init)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Template completion lists

(defvar vhdl-template-construct-alist nil
  "List of built-in construct templates.")

(defun vhdl-template-construct-alist-init ()
  "Initialize `vhdl-template-construct-alist'."
  (setq
   vhdl-template-construct-alist
   (append
    '(
      ("alias declaration"		   vhdl-template-alias)
      ("architecture body"		   vhdl-template-architecture)
      ("assertion"			   vhdl-template-assert)
      ("attribute declaration"		   vhdl-template-attribute-decl)
      ("attribute specification"	   vhdl-template-attribute-spec)
      ("block configuration"		   vhdl-template-block-configuration)
      ("block statement"		   vhdl-template-block)
      ("case statement"			   vhdl-template-case-is)
      ("component configuration"	   vhdl-template-component-conf)
      ("component declaration"		   vhdl-template-component-decl)
      ("component instantiation statement" vhdl-template-component-inst)
      ("conditional signal assignment"	   vhdl-template-conditional-signal-asst)
      ("configuration declaration"	   vhdl-template-configuration-decl)
      ("configuration specification" 	   vhdl-template-configuration-spec)
      ("constant declaration"		   vhdl-template-constant)
      ("disconnection specification"	   vhdl-template-disconnect)
      ("entity declaration"		   vhdl-template-entity)
      ("exit statement"			   vhdl-template-exit)
      ("file declaration"		   vhdl-template-file)
      ("generate statement"		   vhdl-template-generate)
      ("generic clause"			   vhdl-template-generic)
      ("group declaration"		   vhdl-template-group-decl)
      ("group template declaration" 	   vhdl-template-group-template)
      ("if statement"			   vhdl-template-if-then)
      ("library clause"			   vhdl-template-library)
      ("loop statement"			   vhdl-template-loop)
      ("next statement"			   vhdl-template-next)
      ("package declaration"		   vhdl-template-package-decl)
      ("package body"			   vhdl-template-package-body)
      ("port clause"			   vhdl-template-port)
      ("process statement"	 	   vhdl-template-process)
      ("report statement"		   vhdl-template-report)
      ("return statement"		   vhdl-template-return)
      ("selected signal assignment"	   vhdl-template-selected-signal-asst)
      ("signal declaration"		   vhdl-template-signal)
      ("subprogram declaration"		   vhdl-template-subprogram-decl)
      ("subprogram body"		   vhdl-template-subprogram-body)
      ("subtype declaration"		   vhdl-template-subtype)
      ("type declaration"		   vhdl-template-type)
      ("use clause"			   vhdl-template-use)
      ("variable declaration"	 	   vhdl-template-variable)
      ("wait statement"			   vhdl-template-wait)
      )
    (when (vhdl-standard-p 'ams)
      '(
	("break statement"		     vhdl-template-break)
	("nature declaration"		     vhdl-template-nature)
	("quantity declaration"		     vhdl-template-quantity)
	("simultaneous case statement"	     vhdl-template-case-use)
	("simultaneous if statement"	     vhdl-template-if-use)
	("simultaneous procedural statement" vhdl-template-procedural)
	("step limit specification"	     vhdl-template-limit)
	("subnature declaration"	     vhdl-template-subnature)
	("terminal declaration"		     vhdl-template-terminal)
	)))))

;; initialize for VHDL Mode
(vhdl-template-construct-alist-init)

(defvar vhdl-template-package-alist nil
  "List of built-in package templates.")

(defun vhdl-template-package-alist-init ()
  "Initialize `vhdl-template-package-alist'."
  (setq
   vhdl-template-package-alist
   (append
    '(
      ("numeric_bit"	    vhdl-template-package-numeric-bit)
      ("numeric_std"	    vhdl-template-package-numeric-std)
      ("std_logic_1164"	    vhdl-template-package-std-logic-1164)
      ("std_logic_arith"    vhdl-template-package-std-logic-arith)
      ("std_logic_misc"     vhdl-template-package-std-logic-misc)
      ("std_logic_signed"   vhdl-template-package-std-logic-signed)
      ("std_logic_textio"   vhdl-template-package-std-logic-textio)
      ("std_logic_unsigned" vhdl-template-package-std-logic-unsigned)
      ("textio"		    vhdl-template-package-textio)
      )
    (when (vhdl-standard-p 'math)
      '(
	("math_complex"	vhdl-template-package-math-complex)
	("math_real"	vhdl-template-package-math-real)
	)))))

;; initialize for VHDL Mode
(vhdl-template-package-alist-init)

(defvar vhdl-template-directive-alist
  '(
    ("translate_on"	vhdl-template-directive-translate-on)
    ("translate_off"	vhdl-template-directive-translate-off)
    ("synthesis_on"	vhdl-template-directive-synthesis-on)
    ("synthesis_off"	vhdl-template-directive-synthesis-off)
    )
  "List of built-in directive templates.")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Menues
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; VHDL menu (using `easy-menu.el')

(defun vhdl-customize ()
  "Call the customize function with `vhdl' as argument."
  (interactive)
  (customize-browse 'vhdl))

(defun vhdl-create-mode-menu ()
  "Create VHDL Mode menu."
  `("VHDL"
    ,(append
      '("Project"
	["None"			(vhdl-set-project "")
				:style radio :selected (null vhdl-project)]
	"--")
      ;; add menu entries for defined projects
      (let ((project-alist vhdl-project-alist) menu-alist name)
	(while project-alist
	  (setq name (caar project-alist))
	  (setq menu-alist
		(cons `[,name (vhdl-set-project ,name)
			:style radio :selected (equal ,name vhdl-project)]
		      menu-alist))
	  (setq project-alist (cdr project-alist)))
	(if vhdl-project-sort
	    (sort menu-alist
		  (function (lambda (a b) (string< (elt a 0) (elt b 0)))))
	  (nreverse menu-alist)))
      '("--" "--"
	["Select Project..."	vhdl-set-project t]
	"--"
	["Duplicate Project"	vhdl-duplicate-project vhdl-project]
	["Import Project..."	vhdl-import-project
				:keys "C-c C-p C-m" :active t]
	["Export Project"	vhdl-export-project vhdl-project]
	"--"
	["Customize Project..." (customize-option 'vhdl-project-alist) t]))
    "--"
    ("Compile"
     ["Compile Buffer"		vhdl-compile t]
     ["Stop Compilation"	kill-compilation t]
     "--"
     ["Make"			vhdl-make t]
     ["Generate Makefile"	vhdl-generate-makefile t]
     "--"
     ["Next Error"		next-error t]
     ["Previous Error"		previous-error t]
     ["First Error"		first-error t]
     "--"
     ,(append
       '("Compiler")
       ;; add menu entries for defined compilers
       (let ((comp-alist vhdl-compiler-alist) menu-alist name)
	 (while comp-alist
	   (setq name (caar comp-alist))
	   (setq menu-alist
		 (cons `[,name (setq vhdl-compiler ,name)
			 :style radio :selected (equal ,name vhdl-compiler)]
		       menu-alist))
	   (setq comp-alist (cdr comp-alist)))
	 (nreverse menu-alist))
       '("--" "--"
	 ["Select Compiler..."	vhdl-set-compiler t]
	 "--"
	 ["Customize Compiler..."
	  (customize-option 'vhdl-compiler-alist) t])))
    "--"
    ,(append
      '("Template"
	("VHDL Construct 1"
	 ["Alias"		vhdl-template-alias t]
	 ["Architecture"	vhdl-template-architecture t]
	 ["Assert"		vhdl-template-assert t]
	 ["Attribute (Decl)"	vhdl-template-attribute-decl t]
	 ["Attribute (Spec)"	vhdl-template-attribute-spec t]
	 ["Block"		vhdl-template-block t]
	 ["Case"		vhdl-template-case-is t]
	 ["Component (Decl)"	vhdl-template-component-decl t]
	 ["(Component) Instance"	vhdl-template-component-inst t]
	 ["Conditional (Signal Asst)"	vhdl-template-conditional-signal-asst t]
	 ["Configuration (Block)"	vhdl-template-block-configuration t]
	 ["Configuration (Comp)"	vhdl-template-component-conf t]
	 ["Configuration (Decl)"	vhdl-template-configuration-decl t]
	 ["Configuration (Spec)"	vhdl-template-configuration-spec t]
	 ["Constant"		vhdl-template-constant t]
	 ["Disconnect"		vhdl-template-disconnect t]
	 ["Else"		vhdl-template-else t]
	 ["Elsif"		vhdl-template-elsif t]
	 ["Entity"		vhdl-template-entity t]
	 ["Exit"		vhdl-template-exit t]
	 ["File"		vhdl-template-file t]
	 ["For (Generate)"	vhdl-template-for-generate t]
	 ["For (Loop)"		vhdl-template-for-loop t]
	 ["Function (Body)"	vhdl-template-function-body t]
	 ["Function (Decl)"	vhdl-template-function-decl t]
	 ["Generic"		vhdl-template-generic t]
	 ["Group (Decl)"	vhdl-template-group-decl t]
	 ["Group (Template)"	vhdl-template-group-template t])
	("VHDL Construct 2"
	 ["If (Generate)"	vhdl-template-if-generate t]
	 ["If (Then)"		vhdl-template-if-then t]
	 ["Library"		vhdl-template-library t]
	 ["Loop"		vhdl-template-bare-loop t]
	 ["Map"			vhdl-template-map t]
	 ["Next"		vhdl-template-next t]
	 ["Others (Aggregate)"	vhdl-template-others t]
	 ["Package (Decl)"	vhdl-template-package-decl t]
	 ["Package (Body)"	vhdl-template-package-body t]
	 ["Port"		vhdl-template-port t]
	 ["Procedure (Body)"	vhdl-template-procedure-body t]
	 ["Procedure (Decl)"	vhdl-template-procedure-decl t]
	 ["Process (Comb)"	vhdl-template-process-comb t]
	 ["Process (Seq)"	vhdl-template-process-seq t]
	 ["Report"		vhdl-template-report t]
	 ["Return"		vhdl-template-return t]
	 ["Select"		vhdl-template-selected-signal-asst t]
	 ["Signal"		vhdl-template-signal t]
	 ["Subtype"		vhdl-template-subtype t]
	 ["Type"		vhdl-template-type t]
	 ["Use"			vhdl-template-use t]
	 ["Variable"		vhdl-template-variable t]
	 ["Wait"		vhdl-template-wait t]
	 ["(Clocked Wait)"	vhdl-template-clocked-wait t]
	 ["When"		vhdl-template-when t]
	 ["While (Loop)"	vhdl-template-while-loop t]
	 ["With"		vhdl-template-with t]))
      (when (vhdl-standard-p 'ams)
	'(("VHDL-AMS Construct"
	   ["Break"		vhdl-template-break t]
	   ["Case (Use)"	vhdl-template-case-use t]
	   ["If (Use)"		vhdl-template-if-use t]
	   ["Limit"		vhdl-template-limit t]
	   ["Nature"		vhdl-template-nature t]
	   ["Procedural"	vhdl-template-procedural t]
	   ["Quantity (Free)"	vhdl-template-quantity-free t]
	   ["Quantity (Branch)"	vhdl-template-quantity-branch t]
	   ["Quantity (Source)"	vhdl-template-quantity-source t]
	   ["Subnature"		vhdl-template-subnature t]
	   ["Terminal"		vhdl-template-terminal t])))
      '(["Insert Construct..."	vhdl-template-insert-construct
				:keys "C-c C-i C-t"]
	"--")
      (list
       (append
	'("Package")
	(when (vhdl-standard-p 'math)
	  '(["math_complex"	vhdl-template-package-math-complex t]
	    ["math_real"	vhdl-template-package-math-real t]))
	'(["numeric_bit"	vhdl-template-package-numeric-bit t]
	  ["numeric_std"	vhdl-template-package-numeric-std t]
	  ["std_logic_1164"	vhdl-template-package-std-logic-1164 t]
	  ["textio"		vhdl-template-package-textio t]
	  "--"
	  ["std_logic_arith"	vhdl-template-package-std-logic-arith t]
	  ["std_logic_signed"	vhdl-template-package-std-logic-signed t]
	  ["std_logic_unsigned"	vhdl-template-package-std-logic-unsigned t]
	  ["std_logic_misc"	vhdl-template-package-std-logic-misc t]
	  ["std_logic_textio"	vhdl-template-package-std-logic-textio t]
	  "--"
	  ["Insert Package..."	vhdl-template-insert-package
				:keys "C-c C-i C-p"])))
      '(("Directive"
	 ["translate_on"	vhdl-template-directive-translate-on t]
	 ["translate_off"	vhdl-template-directive-translate-off t]
	 ["synthesis_on"	vhdl-template-directive-synthesis-on t]
	 ["synthesis_off"	vhdl-template-directive-synthesis-off t]
	 "--"
	 ["Insert Directive..."	vhdl-template-insert-directive
				:keys "C-c C-i C-d"])
	"--"
	["Insert Header"	vhdl-template-header :keys "C-c C-t C-h"]
	["Insert Footer"	vhdl-template-footer t]
	["Insert Date"		vhdl-template-insert-date t]
	["Modify Date"		vhdl-template-modify :keys "C-c C-t C-m"]
	"--"
	["Query Next Prompt"	vhdl-template-search-prompt t]))
    ,(append
      '("Model")
      ;; add menu entries for defined models
      (let ((model-alist vhdl-model-alist) menu-alist model)
	(while model-alist
	  (setq model (car model-alist))
	  (setq menu-alist
		(cons
		 (vector
		  (nth 0 model)
		  (vhdl-function-name "vhdl-model" (nth 0 model))
		  :keys (concat "C-c C-m " (key-description (nth 2 model))))
		 menu-alist))
	  (setq model-alist (cdr model-alist)))
	(nreverse menu-alist))
      '("--" "--"
	["Insert Model..."	vhdl-model-insert :keys "C-c C-i C-m"]
	["Customize Model..."	(customize-option 'vhdl-model-alist) t]))
    ("Port"
     ["Copy"			vhdl-port-copy t]
     "--"
     ["Paste As Entity"		vhdl-port-paste-entity vhdl-port-list]
     ["Paste As Component"	vhdl-port-paste-component vhdl-port-list]
     ["Paste As Instance"	vhdl-port-paste-instance
				:keys "C-c C-p C-i" :active vhdl-port-list]
     ["Paste As Signals"	vhdl-port-paste-signals vhdl-port-list]
     ["Paste As Constants"	vhdl-port-paste-constants vhdl-port-list]
     ["Paste As Generic Map"	vhdl-port-paste-generic-map vhdl-port-list]
     ["Paste As Initializations" vhdl-port-paste-initializations vhdl-port-list]
     "--"
     ["Paste As Test Bench"	vhdl-port-paste-testbench vhdl-port-list]
     "--"
     ["Flatten"			vhdl-port-flatten vhdl-port-list])
    "--"
    ("Comment"
     ["(Un)Comment Out Region"	vhdl-comment-uncomment-region (mark)]
     "--"
     ["Insert Inline Comment"	vhdl-comment-append-inline t]
     ["Insert Horizontal Line"	vhdl-comment-display-line t]
     ["Insert Display Comment"	vhdl-comment-display t]
     "--"
     ["Fill Comment"		fill-paragraph t]
     ["Fill Comment Region"	fill-region (mark)]
     ["Kill Comment Region"	vhdl-comment-kill-region (mark)]
     ["Kill Inline Comment Region" vhdl-comment-kill-inline-region (mark)])
    ("Line"
     ["Kill"			vhdl-line-kill t]
     ["Copy"			vhdl-line-copy t]
     ["Yank"			vhdl-line-yank t]
     ["Expand"			vhdl-line-expand t]
     "--"
     ["Transpose Next"		vhdl-line-transpose-next t]
     ["Transpose Prev"		vhdl-line-transpose-previous t]
     ["Open"			vhdl-line-open t]
     ["Join"			vhdl-delete-indentation t]
     "--"
     ["Goto"			goto-line t]
     ["(Un)Comment Out"		vhdl-comment-uncomment-line t])
    ("Move"
     ["Forward Statement"	vhdl-end-of-statement t]
     ["Backward Statement"	vhdl-beginning-of-statement t]
     ["Forward Expression"	vhdl-forward-sexp t]
     ["Backward Expression"	vhdl-backward-sexp t]
     ["Forward Same Indent"	vhdl-forward-same-indent t]
     ["Backward Same Indent"	vhdl-backward-same-indent t]
     ["Forward Function"	vhdl-end-of-defun t]
     ["Backward Function"	vhdl-beginning-of-defun t]
     ["Mark Function"		vhdl-mark-defun t])
    "--"
    ("Indent"
     ["Line"			indent-according-to-mode :keys "C-c C-i C-l"]
     ["Group"			vhdl-indent-group :keys "C-c C-i C-g"]
     ["Region"			vhdl-indent-region (mark)]
     ["Buffer"			vhdl-indent-buffer :keys "C-c C-i C-b"])
    ("Align"
     ["Group"			vhdl-align-group t]
     ["Same Indent"		vhdl-align-same-indent :keys "C-c C-a C-i"]
     ["List"			vhdl-align-list t]
     ["Declarations"		vhdl-align-declarations t]
     ["Region"			vhdl-align-region (mark)]
     ["Buffer"			vhdl-align-buffer t]
     "--"
     ["Inline Comment Group"	vhdl-align-inline-comment-group t]
     ["Inline Comment Region"	vhdl-align-inline-comment-region (mark)]
     ["Inline Comment Buffer"	vhdl-align-inline-comment-buffer t])
    ("Beautify"
     ["Region"			vhdl-beautify-region (mark)]
     ["Buffer"			vhdl-beautify-buffer t])
    ("Fix"
     ["Generic/Port Clause"	vhdl-fix-clause t]
     "--"
     ["Case Region"		vhdl-fix-case-region (mark)]
     ["Case Buffer"		vhdl-fix-case-buffer t]
     "--"
     ["Whitespace Region"	vhdl-fixup-whitespace-region (mark)]
     ["Whitespace Buffer"	vhdl-fixup-whitespace-buffer t]
     "--"
     ["Trailing Spaces Buffer"	vhdl-remove-trailing-spaces t])
    ("Update"
     ["Sensitivity List"	vhdl-update-sensitivity-list-process t]
     ["Sensitivity List Buffer"	vhdl-update-sensitivity-list-buffer t])
    "--"
    ["Fontify Buffer"		vhdl-fontify-buffer t]
    ["Show Messages"		vhdl-show-messages t]
    ["Syntactic Info"		vhdl-show-syntactic-information t]
    "--"
    ["Speedbar"			vhdl-speedbar t]
    ["Hide/Show"		vhdl-hs-minor-mode t]
    "--"
    ("Documentation"
     ["VHDL Mode"		vhdl-doc-mode :keys "C-c C-h"]
     ["Release Notes"		(vhdl-doc-variable 'vhdl-doc-release-notes) t]
     ["Reserved Words"		(vhdl-doc-variable 'vhdl-doc-keywords) t]
     ["Coding Style"		(vhdl-doc-variable 'vhdl-doc-coding-style) t])
    ["Version"			vhdl-version t]
    ["Bug Report..."		vhdl-submit-bug-report t]
    "--"
    ("Options"
     ("Mode"
      ["Electric Mode"
       (progn (customize-set-variable 'vhdl-electric-mode
				      (not vhdl-electric-mode))
	      (vhdl-mode-line-update))
       :style toggle :selected vhdl-electric-mode :keys "C-c C-m C-e"]
      ["Stutter Mode"
       (progn (customize-set-variable 'vhdl-stutter-mode
				      (not vhdl-stutter-mode))
	      (vhdl-mode-line-update))
       :style toggle :selected vhdl-stutter-mode :keys "C-c C-m C-s"]
      ["Indent Tabs Mode"
       (customize-set-variable 'vhdl-indent-tabs-mode
			       (not vhdl-indent-tabs-mode))
       :style toggle :selected vhdl-indent-tabs-mode])
     ("Project"
      ["Project Setup..." (customize-option 'vhdl-project-alist) t]
      ,(append
	'("Selected Project at Startup"
	  ["None" (progn (customize-set-variable 'vhdl-project nil)
			 (vhdl-set-project ""))
	   :style radio :selected (null vhdl-project)]
	  "--")
	;; add menu entries for defined projects
	(let ((project-alist vhdl-project-alist) menu-alist name)
	  (while project-alist
	    (setq name (caar project-alist))
	    (setq menu-alist
		  (cons `[,name (progn (customize-set-variable
					'vhdl-project ,name)
				       (vhdl-set-project ,name))
			  :style radio :selected (equal ,name vhdl-project)]
			menu-alist))
	    (setq project-alist (cdr project-alist)))
	  (nreverse menu-alist)))
      ["Setup File Name..." (customize-option 'vhdl-project-file-name) t]
      ("Auto Load Setup File"
       ["At Startup"
	(customize-set-variable 'vhdl-project-auto-load
				(if (memq 'startup vhdl-project-auto-load)
				   (delq 'startup vhdl-project-auto-load)
				 (cons 'startup vhdl-project-auto-load)))
       :style toggle :selected (memq 'startup vhdl-project-auto-load)])
      ["Sort Projects"
       (customize-set-variable 'vhdl-project-sort (not vhdl-project-sort))
       :style toggle :selected vhdl-project-sort])
     ("Compiler"
      ["Compiler Setup..." (customize-option 'vhdl-compiler-alist) t]
      ,(append
	'("Selected Compiler at Startup")
	;; add menu entries for defined compilers
	(let ((comp-alist vhdl-compiler-alist) menu-list name)
	  (while comp-alist
	    (setq name (caar comp-alist))
	    (setq menu-list
		  (cons `[,name (customize-set-variable 'vhdl-compiler ,name)
			  :style radio :selected (equal ,name vhdl-compiler)]
			menu-list))
	    (setq comp-alist (cdr comp-alist)))
	  (nreverse menu-list)))
      ["Use Local Error Regexp"
       (customize-set-variable 'vhdl-compile-use-local-error-regexp
			       (not vhdl-compile-use-local-error-regexp))
       :style toggle :selected vhdl-compile-use-local-error-regexp]
      ["Makefile Generation Hook..."
       (customize-option 'vhdl-makefile-generation-hook) t])
     ("Style"
      ("VHDL Standard"
       ["VHDL'87"
	(progn (customize-set-variable 'vhdl-standard
				       (list '87 (cadr vhdl-standard)))
	       (vhdl-activate-customizations))
	:style radio :selected (eq '87 (car vhdl-standard))]
       ["VHDL'93"
	(progn (customize-set-variable 'vhdl-standard
				       (list '93 (cadr vhdl-standard)))
	       (vhdl-activate-customizations))
	:style radio :selected (eq '93 (car vhdl-standard))]
       "--"
       ["VHDL-AMS"
	(progn (customize-set-variable
		'vhdl-standard (list (car vhdl-standard)
				     (if (memq 'ams (cadr vhdl-standard))
					 (delq 'ams (cadr vhdl-standard))
				       (cons 'ams (cadr vhdl-standard)))))
	       (vhdl-activate-customizations))
	:style toggle :selected (memq 'ams (cadr vhdl-standard))]
       ["Math Packages"
	(progn (customize-set-variable
		'vhdl-standard (list (car vhdl-standard)
				     (if (memq 'math (cadr vhdl-standard))
					 (delq 'math (cadr vhdl-standard))
				       (cons 'math (cadr vhdl-standard)))))
	       (vhdl-activate-customizations))
	:style toggle :selected (memq 'math (cadr vhdl-standard))])
      ["Indentation Offset..." (customize-option 'vhdl-basic-offset) t]
      ["Upper Case Keywords"
       (customize-set-variable 'vhdl-upper-case-keywords
			       (not vhdl-upper-case-keywords))
       :style toggle :selected vhdl-upper-case-keywords]
      ["Upper Case Types"
       (customize-set-variable 'vhdl-upper-case-types
			       (not vhdl-upper-case-types))
       :style toggle :selected vhdl-upper-case-types]
      ["Upper Case Attributes"
       (customize-set-variable 'vhdl-upper-case-attributes
			       (not vhdl-upper-case-attributes))
       :style toggle :selected vhdl-upper-case-attributes]
      ["Upper Case Enumeration Values"
       (customize-set-variable 'vhdl-upper-case-enum-values
			       (not vhdl-upper-case-enum-values))
       :style toggle :selected vhdl-upper-case-enum-values]
      ["Upper Case Constants"
       (customize-set-variable 'vhdl-upper-case-constants
			       (not vhdl-upper-case-constants))
       :style toggle :selected vhdl-upper-case-constants])
     ("Naming"
      ["Entity File Name..." (customize-option 'vhdl-entity-file-name) t])
     ("Template"
      ("Electric Keywords"
       ["VHDL Keywords"
	(customize-set-variable 'vhdl-electric-keywords
				(if (memq 'vhdl vhdl-electric-keywords)
				    (delq 'vhdl vhdl-electric-keywords)
				  (cons 'vhdl vhdl-electric-keywords)))
	:style toggle :selected (memq 'vhdl vhdl-electric-keywords)]
       ["User Model Keywords"
	(customize-set-variable 'vhdl-electric-keywords
				(if (memq 'user vhdl-electric-keywords)
				     (delq 'user vhdl-electric-keywords)
				   (cons 'user vhdl-electric-keywords)))
	:style toggle :selected (memq 'user vhdl-electric-keywords)])
      ("Insert Optional Labels"
       ["None"
	(customize-set-variable 'vhdl-optional-labels 'none)
	:style radio :selected (eq 'none vhdl-optional-labels)]
       ["Processes Only"
	(customize-set-variable 'vhdl-optional-labels 'process)
	:style radio :selected (eq 'process vhdl-optional-labels)]
       ["All Constructs"
	(customize-set-variable 'vhdl-optional-labels 'all)
	:style radio :selected (eq 'all vhdl-optional-labels)])
      ("Insert Empty Lines"
       ["None"
	(customize-set-variable 'vhdl-insert-empty-lines 'none)
	:style radio :selected (eq 'none vhdl-insert-empty-lines)]
       ["Design Units Only"
	(customize-set-variable 'vhdl-insert-empty-lines 'unit)
	:style radio :selected (eq 'unit vhdl-insert-empty-lines)]
       ["All Constructs"
	(customize-set-variable 'vhdl-insert-empty-lines 'all)
	:style radio :selected (eq 'all vhdl-insert-empty-lines)])
      ["Argument List Indent"
       (customize-set-variable 'vhdl-argument-list-indent
			       (not vhdl-argument-list-indent))
       :style toggle :selected vhdl-argument-list-indent]
      ["Association List with Formals"
       (customize-set-variable 'vhdl-association-list-with-formals
			       (not vhdl-association-list-with-formals))
       :style toggle :selected vhdl-association-list-with-formals]
      ["Conditions in Parenthesis"
       (customize-set-variable 'vhdl-conditions-in-parenthesis
			       (not vhdl-conditions-in-parenthesis))
       :style toggle :selected vhdl-conditions-in-parenthesis]
      ["Zero String..." (customize-option 'vhdl-zero-string) t]
      ["One String..." (customize-option 'vhdl-one-string) t]
      ("File Header"
       ["Header String..." (customize-option 'vhdl-file-header) t]
       ["Footer String..." (customize-option 'vhdl-file-footer) t]
       ["Company Name..." (customize-option 'vhdl-company-name) t]
       ["Copyright String..." (customize-option 'vhdl-copyright-string) t]
       ["Platform Specification..." (customize-option 'vhdl-platform-spec) t]
       ["Date Format..." (customize-option 'vhdl-date-format) t]
       ["Modify Date Prefix String..."
	(customize-option 'vhdl-modify-date-on-saving) t]
       ["Modify Date on Saving"
	(progn (customize-set-variable 'vhdl-modify-date-on-saving
				       (not vhdl-modify-date-on-saving))
	       (vhdl-activate-customizations))
	:style toggle :selected vhdl-modify-date-on-saving])
      ("Sequential Process"
       ("Kind of Reset"
	["None"
	 (customize-set-variable 'vhdl-reset-kind 'none)
	 :style radio :selected (eq 'none vhdl-reset-kind)]
	["Synchronous"
	 (customize-set-variable 'vhdl-reset-kind 'sync)
	 :style radio :selected (eq 'sync vhdl-reset-kind)]
	["Asynchronous"
	 (customize-set-variable 'vhdl-reset-kind 'async)
	 :style radio :selected (eq 'async vhdl-reset-kind)])
       ["Reset is Active High"
	(customize-set-variable 'vhdl-reset-active-high
				(not vhdl-reset-active-high))
	:style toggle :selected vhdl-reset-active-high]
       ["Use Rising Clock Edge"
	(customize-set-variable 'vhdl-clock-rising-edge
				(not vhdl-clock-rising-edge))
	:style toggle :selected vhdl-clock-rising-edge]
       ("Clock Edge Condition"
	["Standard"
	 (customize-set-variable 'vhdl-clock-edge-condition 'standard)
	 :style radio :selected (eq 'standard vhdl-clock-edge-condition)]
	["Function \"rising_edge\""
	 (customize-set-variable 'vhdl-clock-edge-condition 'function)
	 :style radio :selected (eq 'function vhdl-clock-edge-condition)])
       ["Clock Name..." (customize-option 'vhdl-clock-name) t]
       ["Reset Name..." (customize-option 'vhdl-reset-name) t]))
     ("Model"
      ["Model Definition..." (customize-option 'vhdl-model-alist) t])
     ("Port"
      ["Include Port Comments"
       (customize-set-variable 'vhdl-include-port-comments
			       (not vhdl-include-port-comments))
       :style toggle :selected vhdl-include-port-comments]
      ["Include Direction Comments"
       (customize-set-variable 'vhdl-include-direction-comments
			       (not vhdl-include-direction-comments))
       :style toggle :selected vhdl-include-direction-comments]
      ["Include Type Comments"
       (customize-set-variable 'vhdl-include-type-comments
			       (not vhdl-include-type-comments))
       :style toggle :selected vhdl-include-type-comments]
      ("Include Group Comments"
       ["Never"
	(customize-set-variable 'vhdl-include-group-comments 'never)
	:style radio :selected (eq 'never vhdl-include-group-comments)]
       ["Declarations"
	(customize-set-variable 'vhdl-include-group-comments 'decl)
	:style radio :selected (eq 'decl vhdl-include-group-comments)]
       ["Always"
	(customize-set-variable 'vhdl-include-group-comments 'always)
	:style radio :selected (eq 'always vhdl-include-group-comments)])
      ["Actual Port Name..." (customize-option 'vhdl-actual-port-name) t]
      ["Instance Name..." (customize-option 'vhdl-instance-name) t]
      ("Testbench"
       ["Entity Name..." (customize-option 'vhdl-testbench-entity-name) t]
       ["Architecture Name..."
	(customize-option 'vhdl-testbench-architecture-name) t]
       ["Configuration Name..."
	(customize-option 'vhdl-testbench-configuration-name) t]
       ["DUT Name..." (customize-option 'vhdl-testbench-dut-name) t]
       ["Entity Header..." (customize-option 'vhdl-testbench-entity-header) t]
       ["Architecture Header..."
	(customize-option 'vhdl-testbench-architecture-header) t]
       ["Declarations..." (customize-option 'vhdl-testbench-declarations) t]
       ["Statements..." (customize-option 'vhdl-testbench-statements) t]
       ["Initialize Signals"
	(customize-set-variable 'vhdl-testbench-initialize-signals
				(not vhdl-testbench-initialize-signals))
	:style toggle :selected vhdl-testbench-initialize-signals]
       ["Include Library Clause"
	(customize-set-variable 'vhdl-testbench-include-library
				(not vhdl-testbench-include-library))
	:style toggle :selected vhdl-testbench-include-library]
       ["Include Configuration"
	(customize-set-variable 'vhdl-testbench-include-configuration
				(not vhdl-testbench-include-configuration))
	:style toggle :selected vhdl-testbench-include-configuration]
       ("Create Files"
	["None"
	 (customize-set-variable 'vhdl-testbench-create-files 'none)
	 :style radio :selected (eq 'none vhdl-testbench-create-files)]
	["Single"
	 (customize-set-variable 'vhdl-testbench-create-files 'single)
	 :style radio :selected (eq 'single vhdl-testbench-create-files)]
	["Separate"
	 (customize-set-variable 'vhdl-testbench-create-files 'separate)
	 :style radio :selected (eq 'separate vhdl-testbench-create-files)])))
     ("Comment"
      ["Self Insert Comments"
       (customize-set-variable 'vhdl-self-insert-comments
			       (not vhdl-self-insert-comments))
       :style toggle :selected vhdl-self-insert-comments]
      ["Prompt for Comments"
       (customize-set-variable 'vhdl-prompt-for-comments
			       (not vhdl-prompt-for-comments))
       :style toggle :selected vhdl-prompt-for-comments]
      ["Inline Comment Column..."
       (customize-option 'vhdl-inline-comment-column) t]
      ["End Comment Column..." (customize-option 'vhdl-end-comment-column) t])
     ("Align"
      ["Auto Align Templates"
       (customize-set-variable 'vhdl-auto-align (not vhdl-auto-align))
       :style toggle :selected vhdl-auto-align]
      ["Align Line Groups"
       (customize-set-variable 'vhdl-align-groups (not vhdl-align-groups))
       :style toggle :selected vhdl-align-groups]
      ["Group Separation String..."
       (customize-set-variable 'vhdl-align-group-separate) t]
      ["Align Lines with Same Indent"
       (customize-set-variable 'vhdl-align-same-indent
			       (not vhdl-align-same-indent))
       :style toggle :selected vhdl-align-same-indent])
     ("Highlight"
      ["Highlight Keywords"
       (progn (customize-set-variable 'vhdl-highlight-keywords
				      (not vhdl-highlight-keywords))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-keywords]
      ["Highlight Names"
       (progn (customize-set-variable 'vhdl-highlight-names
				      (not vhdl-highlight-names))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-names]
      ["Highlight Special Words"
       (progn (customize-set-variable 'vhdl-highlight-special-words
				      (not vhdl-highlight-special-words))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-special-words]
      ["Highlight Forbidden Words"
       (progn (customize-set-variable 'vhdl-highlight-forbidden-words
				      (not vhdl-highlight-forbidden-words))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-forbidden-words]
      ["Highlight Verilog Keywords"
       (progn (customize-set-variable 'vhdl-highlight-verilog-keywords
				      (not vhdl-highlight-verilog-keywords))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-verilog-keywords]
      ["Highlight \"translate_off\""
       (progn (customize-set-variable 'vhdl-highlight-translate-off
				      (not vhdl-highlight-translate-off))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-translate-off]
      ["Case Sensitive Highlighting"
       (progn (customize-set-variable 'vhdl-highlight-case-sensitive
				      (not vhdl-highlight-case-sensitive))
	      (vhdl-fontify-buffer))
       :style toggle :selected vhdl-highlight-case-sensitive]
      ["Special Syntax Definition..."
       (customize-option 'vhdl-special-syntax-alist) t]
      ["Forbidden Words..." (customize-option 'vhdl-forbidden-words) t]
      ["Forbidden Syntax..." (customize-option 'vhdl-forbidden-syntax) t]
      ["Directive Keywords..." (customize-option 'vhdl-directive-keywords) t]
      ["Colors..." (customize-group 'vhdl-highlight-faces) t])
     ("Speedbar"
      ["Auto Open at Startup"
       (customize-set-variable 'vhdl-speedbar-auto-open
			       (not vhdl-speedbar-auto-open))
       :style toggle :selected vhdl-speedbar-auto-open]
      ("Default Displaying Mode"
       ["Files"
	(customize-set-variable 'vhdl-speedbar-display-mode 'files)
	:style radio :selected (eq 'files vhdl-speedbar-display-mode)]
       ["Directory Hierarchy"
	(customize-set-variable 'vhdl-speedbar-display-mode 'directory)
	:style radio :selected (eq 'directory vhdl-speedbar-display-mode)]
       ["Project Hierarchy"
	(customize-set-variable 'vhdl-speedbar-display-mode 'project)
	:style radio :selected (eq 'project vhdl-speedbar-display-mode)])
      ["Indentation Offset..."
       (customize-option 'speedbar-indentation-width) t]
      ["Scan Size Limits..." (customize-option 'vhdl-speedbar-scan-limit) t]
      ["Jump to Unit when Opening"
       (customize-set-variable 'vhdl-speedbar-jump-to-unit
			       (not vhdl-speedbar-jump-to-unit))
       :style toggle :selected vhdl-speedbar-jump-to-unit]
      ["Update Hierarchy on File Saving"
       (customize-set-variable 'vhdl-speedbar-update-on-saving
			       (not vhdl-speedbar-update-on-saving))
       :style toggle :selected vhdl-speedbar-update-on-saving]
      ("Save in Cache File"
       ["Hierarchy Information"
	(customize-set-variable 'vhdl-speedbar-save-cache
				(if (memq 'hierarchy vhdl-speedbar-save-cache)
				    (delq 'hierarchy vhdl-speedbar-save-cache)
				  (cons 'hierarchy vhdl-speedbar-save-cache)))
	:style toggle :selected (memq 'hierarchy vhdl-speedbar-save-cache)]
       ["Displaying Status"
	(customize-set-variable 'vhdl-speedbar-save-cache
				(if (memq 'display vhdl-speedbar-save-cache)
				    (delq 'display vhdl-speedbar-save-cache)
				  (cons 'display vhdl-speedbar-save-cache)))
	:style toggle :selected (memq 'display vhdl-speedbar-save-cache)])
      ["Cache File Name..."
       (customize-option 'vhdl-speedbar-cache-file-name) t])
     ("Menu"
      ["Add Index Menu when Loading File"
       (progn (customize-set-variable 'vhdl-index-menu (not vhdl-index-menu))
	      (vhdl-index-menu-init))
       :style toggle :selected vhdl-index-menu]
      ["Add Source File Menu when Loading File"
       (progn (customize-set-variable 'vhdl-source-file-menu
				      (not vhdl-source-file-menu))
	      (vhdl-add-source-files-menu))
       :style toggle :selected vhdl-source-file-menu]
      ["Add Hideshow Menu at Startup"
       (progn (customize-set-variable 'vhdl-hideshow-menu
				      (not vhdl-hideshow-menu))
	      (vhdl-activate-customizations))
       :style toggle :selected vhdl-hideshow-menu]
      ["Hide Everything Initially"
       (customize-set-variable 'vhdl-hide-all-init (not vhdl-hide-all-init))
       :style toggle :selected vhdl-hide-all-init])
     ("Print"
      ["In Two Column Format"
       (progn (customize-set-variable 'vhdl-print-two-column
				      (not vhdl-print-two-column))
	      (message "Activate new setting by saving options and restarting Emacs"))
       :style toggle :selected vhdl-print-two-column]
      ["Use Customized Faces"
       (progn (customize-set-variable 'vhdl-print-customize-faces
				      (not vhdl-print-customize-faces))
	      (message "Activate new setting by saving options and restarting Emacs"))
       :style toggle :selected vhdl-print-customize-faces])
     ("Miscellaneous"
      ["Use Intelligent Tab"
       (progn (customize-set-variable 'vhdl-intelligent-tab
				      (not vhdl-intelligent-tab))
	      (vhdl-activate-customizations))
       :style toggle :selected vhdl-intelligent-tab]
      ["Indent Syntax-Based"
       (customize-set-variable 'vhdl-indent-syntax-based
			       (not vhdl-indent-syntax-based))
       :style toggle :selected vhdl-indent-syntax-based]
      ["Word Completion is Case Sensitive"
       (customize-set-variable 'vhdl-word-completion-case-sensitive
			       (not vhdl-word-completion-case-sensitive))
       :style toggle :selected vhdl-word-completion-case-sensitive]
      ["Word Completion in Minibuffer"
       (progn (customize-set-variable 'vhdl-word-completion-in-minibuffer
				      (not vhdl-word-completion-in-minibuffer))
	      (message "Activate new setting by saving options and restarting Emacs"))
       :style toggle :selected vhdl-word-completion-in-minibuffer]
      ["Underscore is Part of Word"
       (progn (customize-set-variable 'vhdl-underscore-is-part-of-word
				      (not vhdl-underscore-is-part-of-word))
	      (vhdl-activate-customizations))
       :style toggle :selected vhdl-underscore-is-part-of-word])
     ["Related..." (customize-browse 'vhdl-related) t]
     "--"
     ["Save Options" customize-save-customized t]
     "--"
     ("Customize"
      ["Browse Customization Group..." vhdl-customize t]
      ["Activate Customization"	vhdl-activate-customizations t]))))

(defvar vhdl-mode-menu-list (vhdl-create-mode-menu)
  "VHDL Mode menu.")

(defun vhdl-update-mode-menu ()
  "Update VHDL Mode menu."
  (interactive)
  (easy-menu-remove vhdl-mode-menu-list) ; for XEmacs
  (setq vhdl-mode-menu-list (vhdl-create-mode-menu))
  (easy-menu-add vhdl-mode-menu-list)	; for XEmacs
  (easy-menu-define vhdl-mode-menu vhdl-mode-map
		    "Menu keymap for VHDL Mode." vhdl-mode-menu-list))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Index menu (using `imenu.el'), also used for speedbar (using `speedbar.el')

(defconst vhdl-imenu-generic-expression
  '(
    ("Subprogram"
     "^\\s-*\\(\\(\\(impure\\|pure\\)\\s-+\\|\\)function\\|procedure\\)\\s-+\\(\"?\\(\\w\\|\\s_\\)+\"?\\)"
     4)
    ("Instance"
     "^\\s-*\\(\\(\\w\\|\\s_\\)+\\s-*:\\(\\s-\\|\n\\)*\\(\\w\\|\\s_\\)+\\)\\(\\s-\\|\n\\)+\\(generic\\|port\\)\\s-+map\\>"
     1)
    ("Component"
     "^\\s-*\\(component\\)\\s-+\\(\\(\\w\\|\\s_\\)+\\)"
     2)
    ("Procedural"
     "^\\s-*\\(\\(\\w\\|\\s_\\)+\\)\\s-*:\\(\\s-\\|\n\\)*\\(procedural\\)"
     1)
    ("Process"
     "^\\s-*\\(\\(\\w\\|\\s_\\)+\\)\\s-*:\\(\\s-\\|\n\\)*\\(\\(postponed\\s-+\\|\\)process\\)"
     1)
    ("Block"
     "^\\s-*\\(\\(\\w\\|\\s_\\)+\\)\\s-*:\\(\\s-\\|\n\\)*\\(block\\)"
     1)
    ("Package"
     "^\\s-*\\(package\\( body\\|\\)\\)\\s-+\\(\\(\\w\\|\\s_\\)+\\)"
     3)
    ("Configuration"
     "^\\s-*\\(configuration\\)\\s-+\\(\\(\\w\\|\\s_\\)+\\s-+of\\s-+\\(\\w\\|\\s_\\)+\\)"
     2)
    ("Architecture"
     "^\\s-*\\(architecture\\)\\s-+\\(\\(\\w\\|\\s_\\)+\\s-+of\\s-+\\(\\w\\|\\s_\\)+\\)"
     2)
    ("Entity"
     "^\\s-*\\(entity\\)\\s-+\\(\\(\\w\\|\\s_\\)+\\)"
     2)
    )
  "Imenu generic expression for VHDL Mode.  See `imenu-generic-expression'.")

(defun vhdl-index-menu-init ()
  "Initialize index menu."
  (set (make-local-variable 'imenu-case-fold-search) t)
  (set (make-local-variable 'imenu-generic-expression)
       vhdl-imenu-generic-expression)
  (when (and vhdl-index-menu (fboundp 'imenu))
    (if (or (not (boundp 'font-lock-maximum-size))
	    (> font-lock-maximum-size (buffer-size)))
	(imenu-add-to-menubar "Index")
      (message "Scanning buffer for index...buffer too big"))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Source file menu (using `easy-menu.el')

(defvar vhdl-sources-menu nil)

(defun vhdl-directory-files (directory &optional full match)
  "Call `directory-files' if DIRECTORY exists, otherwise generate error
message."
  (if (not (file-directory-p directory))
      (vhdl-warning-when-idle "No such directory: \"%s\"" directory)
    (let ((dir (directory-files directory full match)))
      (setq dir (delete "." dir))
      (setq dir (delete ".." dir))
      dir)))

(defun vhdl-get-source-files (&optional full directory)
  "Get list of VHDL source files in DIRECTORY or current directory."
  (let ((mode-alist auto-mode-alist)
	filename-regexp)
    ;; create regular expressions for matching file names
    (setq filename-regexp "\\`[^.].*\\(")
    (while mode-alist
      (when (eq (cdar mode-alist) 'vhdl-mode)
	(setq filename-regexp
	      (concat filename-regexp (caar mode-alist) "\\|")))
      (setq mode-alist (cdr mode-alist)))
    (setq filename-regexp
	  (concat (substring filename-regexp 0
			     (string-match "\\\\|$" filename-regexp)) "\\)"))
    ;; find files
    (nreverse (vhdl-directory-files
	       (or directory default-directory) full filename-regexp))))

(defun vhdl-add-source-files-menu ()
  "Scan directory for all VHDL source files and generate menu.
The directory of the current source file is scanned."
  (interactive)
  (message "Scanning directory for source files ...")
  (let ((newmap (current-local-map))
	(file-list (vhdl-get-source-files))
	menu-list found)
    ;; Create list for menu
    (setq found nil)
    (while file-list
      (setq found t)
      (setq menu-list (cons (vector (car file-list)
				   (list 'find-file (car file-list)) t)
			   menu-list))
      (setq file-list (cdr file-list)))
    (setq menu-list (vhdl-menu-split menu-list 25))
    (when found (setq menu-list (cons "--" menu-list)))
    (setq menu-list (cons ["*Rescan*" vhdl-add-source-files-menu t] menu-list))
    (setq menu-list (cons "Sources" menu-list))
    ;; Create menu
    (easy-menu-add menu-list)
    (easy-menu-define vhdl-sources-menu newmap
		      "VHDL source files menu" menu-list))
  (message ""))

(defun vhdl-menu-split (list n)
  "Split menu LIST into several submenues, if number of elements > N."
  (if (> (length list) n)
      (let ((remain list)
	    (result '())
	    (sublist '())
	    (menuno 1)
	    (i 0))
	(while remain
	  (setq sublist (cons (car remain) sublist))
	  (setq remain (cdr remain))
	  (setq i (+ i 1))
	  (if (= i n)
	      (progn
		(setq result (cons (cons (format "Sources %s" menuno)
					 (nreverse sublist)) result))
		(setq i 0)
		(setq menuno (+ menuno 1))
		(setq sublist '()))))
	(and sublist
	     (setq result (cons (cons (format "Sources %s" menuno)
				      (nreverse sublist)) result)))
	(nreverse result))
    list))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Mode definition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; performs all buffer local initializations

;;;###autoload
(defun vhdl-mode ()
  "Major mode for editing VHDL code.

Usage:
------

  TEMPLATE INSERTION (electrification):
    After typing a VHDL keyword and entering `SPC', you are prompted for
    arguments while a template is generated for that VHDL construct.  Typing
    `RET' or `C-g' at the first \(mandatory) prompt aborts the current
    template generation.  Optional arguments are indicated by square
    brackets and removed if the queried string is left empty.  Prompts for
    mandatory arguments remain in the code if the queried string is left
    empty.  They can be queried again by `C-c C-t C-q'.  Enabled
    electrification is indicated by `/e' in the modeline.

      Typing `M-SPC' after a keyword inserts a space without calling the
    template generator.  Automatic template generation (i.e.
    electrification) can be disabled (enabled) by typing `C-c C-m C-e' or by
    setting option `vhdl-electric-mode' (see OPTIONS).

      Template generators can be invoked from the VHDL menu, by key
    bindings, by typing `C-c C-i C-c' and choosing a construct, or by typing
    the keyword (i.e. first word of menu entry not in parenthesis) and
    `SPC'.  The following abbreviations can also be used: arch, attr, cond,
    conf, comp, cons, func, inst, pack, sig, var.

      Template styles can be customized in customization group
    `vhdl-template' \(see OPTIONS).


  HEADER INSERTION:
    A file header can be inserted by `C-c C-t C-h'.  A file footer
    (template at the end of the file) can be inserted by `C-c C-t C-f'.
    See customization group `vhdl-header'.


  STUTTERING:
    Double striking of some keys inserts cumbersome VHDL syntax elements.
    Stuttering can be disabled (enabled) by typing `C-c C-m C-s' or by
    option `vhdl-stutter-mode'.  Enabled stuttering is indicated by `/s' in
    the modeline.  The stuttering keys and their effects are:

      ;;   -->  \" : \"       [   -->  (        --    -->  comment
      ;;;  -->  \" := \"      [[  -->  [        --CR  -->  comment-out code
      ..   -->  \" => \"      ]   -->  )        ---   -->  horizontal line
      ,,   -->  \" <= \"      ]]  -->  ]        ----  -->  display comment
      ==   -->  \" == \"      ''  -->  \\\"


  WORD COMPLETION:
    Typing `TAB' after a (not completed) word looks for a VHDL keyword or a
    word in the buffer that starts alike, inserts it and adjusts case.
    Re-typing `TAB' toggles through alternative word completions.  This also
    works in the minibuffer (i.e. in template generator prompts).

      Typing `TAB' after `(' looks for and inserts complete parenthesized
    expressions (e.g. for array index ranges).  All keywords as well as
    standard types and subprograms of VHDL have predefined abbreviations
    \(e.g. type \"std\" and `TAB' will toggle through all standard types
    beginning with \"std\").

      Typing `TAB' after a non-word character indents the line if at the
    beginning of a line (i.e. no preceding non-blank characters), and
    inserts a tabulator stop otherwise.  `M-TAB' always inserts a tabulator
    stop.


  COMMENTS:
        `--'       puts a single comment.
        `---'      draws a horizontal line for separating code segments.
        `----'     inserts a display comment, i.e. two horizontal lines
                   with a comment in between.
        `--CR'     comments out code on that line.  Re-hitting CR comments
                   out following lines.
        `C-c C-c'  comments out a region if not commented out,
                   uncomments a region if already commented out.

      You are prompted for comments after object definitions (i.e. signals,
    variables, constants, ports) and after subprogram and process
    specifications if option `vhdl-prompt-for-comments' is non-nil.
    Comments are automatically inserted as additional labels (e.g. after
    begin statements) and as help comments if `vhdl-self-insert-comments' is
    non-nil.

      Inline comments (i.e. comments after a piece of code on the same line)
    are indented at least to `vhdl-inline-comment-column'.  Comments go at
    maximum to `vhdl-end-comment-column'.  `RET' after a space in a comment
    will open a new comment line.  Typing beyond `vhdl-end-comment-column'
    in a comment automatically opens a new comment line.  `M-q' re-fills
    multi-line comments.


  INDENTATION:
    `TAB' indents a line if at the beginning of the line.  The amount of
    indentation is specified by option `vhdl-basic-offset'.  `C-c C-i C-l'
    always indents the current line (is bound to `TAB' if option
    `vhdl-intelligent-tab' is nil).

      Indentation can be done for a group of lines (`C-c C-i C-g'), a region
    \(`M-C-\\') or the entire buffer (menu).  Argument and port lists are
    indented normally (nil) or relative to the opening parenthesis (non-nil)
    according to option `vhdl-argument-list-indent'.

      If option `vhdl-indent-tabs-mode' is nil, spaces are used instead of
    tabs.  `M-x tabify' and `M-x untabify' allow to convert spaces to tabs
    and vice versa.

|     Syntax-based indentation can be very slow in large files.  Option
|   `vhdl-indent-syntax-based' allows to use faster but simpler indentation.


  ALIGNMENT:
    The alignment functions align operators, keywords, and inline comments
    to beautify the code.  `C-c C-a C-a' aligns a group of consecutive lines
|   separated by blank lines, `C-c C-a C-i' a block of lines with same
|   indent.  `C-c C-a C-l' aligns all lines belonging to a list enclosed by
    a pair of parentheses (e.g. port clause/map, argument list), and `C-c
    C-a C-d' all lines within the declarative part of a design unit.  `C-c
    C-a M-a' aligns an entire region.  `C-c C-a C-c' aligns inline comments
    for a group of lines, and `C-c C-a M-c' for a region.

      If option `vhdl-align-groups' is non-nil, groups of code lines
|   separated by special lines (see option `vhdl-align-group-separate') are
    aligned individually.  If option `vhdl-align-same-indent' is non-nil,
    blocks of lines with same indent are aligned separately.  Some templates
    are automatically aligned after generation if option `vhdl-auto-align'
    is non-nil.

|     Alignment tries to align inline comments at
|   `vhdl-inline-comment-column' and tries inline comment not to exceed
|   `vhdl-end-comment-column'.

      `C-c C-x M-w' fixes up whitespace in a region.  That is, operator
    symbols are surrounded by one space, and multiple spaces are eliminated.


| CODE BEAUTIFICATION:
|   `C-c M-b' and `C-c C-b' beautify the code of a region or of the entire
|   buffer respectively.  This inludes indentation, alignment, and case
|   fixing.  Code beautification can also be run non-interactively using the
|   command:
|
|     emacs -batch -l ~/.emacs filename.vhd -f vhdl-beautify-buffer


  PORT TRANSLATION:
    Generic and port clauses from entity or component declarations can be
    copied (`C-c C-p C-w') and pasted as entity and component declarations,
    as component instantiations and corresponding internal constants and
    signals, as a generic map with constants as actual parameters, and as
|   internal signal initializations (menu).

      To include formals in component instantiations, see option
    `vhdl-association-list-with-formals'.  To include comments in pasting,
    see options `vhdl-include-...-comments'.

      A clause with several generic/port names on the same line can be
    flattened (`C-c C-p C-f') so that only one name per line exists.  Names
    for actual ports, instances, test benches, and design-under-test
    instances can be derived from existing names according to options
    `vhdl-...-name'.  See customization group `vhdl-port'.


| TEST BENCH GENERATION:
|   A copied port can also be pasted as a test bench.  The generated test
|   bench includes an entity, an architecture, and an optional
|   configuration.  The architecture contains the component declaration and
|   instantiation of the DUT as well as internal constant and signal
|   declarations.  Additional user-defined templates can be inserted.  The
|   names used for entity/architecture/configuration/DUT as well as the file
|   structure to be generated can be customized. See customization group
|  `vhdl-testbench'.


  KEY BINDINGS:
    Key bindings (`C-c ...') exist for most commands (see in menu).


  VHDL MENU:
    All commands can be found in the VHDL menu including their key bindings.


  FILE BROWSER:
    The speedbar allows browsing of directories and file contents.  It can
    be accessed from the VHDL menu and is automatically opened if option
    `vhdl-speedbar-auto-open' is non-nil.

      In speedbar, open files and directories with `mouse-2' on the name and
    browse/rescan their contents with `mouse-2'/`S-mouse-2' on the `+'.


  DESIGN HIERARCHY BROWSER:
    The speedbar can also be used for browsing the hierarchy of design units
    contained in the source files of the current directory or the specified
    projects (see option `vhdl-project-alist').

|     The speedbar can be switched between file, directory hierarchy and
|   project hierarchy browsing mode in the speedbar menu or by typing `f',
|   `h' or `H' in speedbar.

      In speedbar, open design units with `mouse-2' on the name and browse
|   their hierarchy with `mouse-2' on the `+'.  Ports can directly be copied
|   from entities and components (in packages).  Individual design units and
|   complete designs can directly be compiled (\"Make\" menu entry).

|     The hierarchy is automatically updated upon saving a modified source
|   file when option `vhdl-speedbar-update-on-saving' is non-nil.  The
|   hierarchy is only updated for projects that have been opened once in the
|   speedbar.  The hierarchy is cached between Emacs sessions in a file (see
|   options in group `vhdl-speedbar').
|
|     Simple design consistency checks are done during scanning, such as
|   multiple declarations of the same unit or missing primary units that are
|   required by secondary units.


  SOURCE FILE COMPILATION:
    The syntax of the current buffer can be analyzed by calling a VHDL
    compiler (menu, `C-c C-k').  The compiler to be used is specified by
    option `vhdl-compiler'.  The available compilers are listed in option
    `vhdl-compiler-alist' including all required compilation command,
    command options, compilation directory, and error message syntax
    information.  New compilers can be added.

      All the source files of an entire design can be compiled by the `make'
    command (menu, `C-c M-C-k') if an appropriate Makefile exists.


| MAKEFILE GENERATION:
|   Makefiles can be generated automatically by an internal generation
|   routine (`C-c M-k').  The library unit dependency information is
|   obtained from the hierarchy browser.  Makefile generation can be
|   customized for each compiler in option `vhdl-compiler-alist'.
|
|     Makefile generation can also be run non-interactively using the
|   command:
|
|       emacs -batch -l ~/.emacs -l vhdl-mode
|             [-compiler compilername] [-project projectname]
|             -f vhdl-generate-makefile
|
|     The Makefile's default target \"all\" compiles the entire design, the
|   target \"clean\" removes it and the target \"library\" creates the
|   library directory if not existent.  The Makefile also includes a target
|   for each primary library unit which allows selective compilation of this
|   unit, its secondary units and its subhierarchy (example: compilation of
|   a design specified by a configuration).  User specific parts can be
|   inserted into a Makefile with option `vhdl-makefile-generation-hook'.
|
|   Limitations:
|     - Only library units and dependencies within the current library are
|       considered.  Makefiles for designs that span multiple libraries are
|       not (yet) supported.
|     - Only one-level configurations are supported (also hierarchical),
|       but configurations that go down several levels are not.
|     - The \"others\" keyword in configurations is not supported.


  PROJECTS:
|   Projects can be defined in option `vhdl-project-alist' and a current
|   project be selected using option `vhdl-project' (permanently) or from
|   the menu or speedbar (temporarily).  For each project, title and
|   description strings (for the file headers), source files/directories
|   (for the hierarchy browser and Makefile generation), library name, and
|   compiler-dependent options, exceptions and compilation directory can be
|   specified.  Compilation settings overwrite the settings of option
|   `vhdl-compiler-alist'.
|
|     Project setups can be exported (i.e. written to a file) and imported.
|   Imported setups are not automatically saved in `vhdl-project-alist' but
|   can be saved afterwards in its customization buffer.  When starting
|   Emacs with VHDL Mode (i.e. load a VHDL file or use \"emacs -l
|   vhdl-mode\") in a directory with an existing project setup file, it is
|   automatically loaded and its project activated if option
|   `vhdl-project-auto-load' is non-nil.  Names/paths of the project setup
|   files can be specified in option `vhdl-project-file-name'.  Multiple
|   project setups can be automatically loaded from global directories.
|   This is an alternative to specifying project setups with option
|   `vhdl-project-alist'.


  SPECIAL MENUES:
    As an alternative to the speedbar, an index menu can be added (set
    option `vhdl-index-menu' to non-nil) or made accessible as a mouse menu
    (e.g. add \"(global-set-key '[S-down-mouse-3] 'imenu)\" to your start-up
    file) for browsing the file contents.  Also, a source file menu can be
    added (set option `vhdl-source-file-menu' to non-nil) for browsing the
    current directory for VHDL source files.


  VHDL STANDARDS:
    The VHDL standards to be used are specified in option `vhdl-standard'.
    Available standards are: VHDL'87/'93, VHDL-AMS, and Math Packages.


  KEYWORD CASE:
    Lower and upper case for keywords and standardized types, attributes,
    and enumeration values is supported.  If the option
    `vhdl-upper-case-keywords' is set to non-nil, keywords can be typed in
    lower case and are converted into upper case automatically (not for
    types, attributes, and enumeration values).  The case of keywords,
    types, attributes,and enumeration values can be fixed for an entire
    region (menu) or buffer (`C-c C-x C-c') according to the options
    `vhdl-upper-case-{keywords,types,attributes,enum-values}'.


  HIGHLIGHTING (fontification):
    Keywords and standardized types, attributes, enumeration values, and
    function names (controlled by option `vhdl-highlight-keywords'), as well
    as comments, strings, and template prompts are highlighted using
    different colors.  Unit, subprogram, signal, variable, constant,
    parameter and generic/port names in declarations as well as labels are
    highlighted if option `vhdl-highlight-names' is non-nil.

      Additional reserved words or words with a forbidden syntax (e.g. words
    that should be avoided) can be specified in option
    `vhdl-forbidden-words' or `vhdl-forbidden-syntax' and be highlighted in
    a warning color (option `vhdl-highlight-forbidden-words').  Verilog
    keywords are highlighted as forbidden words if option
    `vhdl-highlight-verilog-keywords' is non-nil.

      Words with special syntax can be highlighted by specifying their
    syntax and color in option `vhdl-special-syntax-alist' and by setting
    option `vhdl-highlight-special-words' to non-nil.  This allows to
    establish some naming conventions (e.g. to distinguish different kinds
    of signals or other objects by using name suffices) and to support them
    visually.

      Option `vhdl-highlight-case-sensitive' can be set to non-nil in order
    to support case-sensitive highlighting.  However, keywords are then only
    highlighted if written in lower case.

      Code between \"translate_off\" and \"translate_on\" pragmas is
    highlighted using a different background color if option
    `vhdl-highlight-translate-off' is non-nil.

      For documentation and customization of the used colors see
    customization group `vhdl-highlight-faces' (`M-x customize-group').  For
    highlighting of matching parenthesis, see customization group
    `paren-showing'.


  USER MODELS:
    VHDL models (templates) can be specified by the user and made accessible
    in the menu, through key bindings (`C-c C-m ...'), or by keyword
    electrification.  See option `vhdl-model-alist'.


  HIDE/SHOW:
    The code of blocks, processes, subprograms, component declarations and
    instantiations, generic/port clauses, and configuration declarations can
    be hidden using the `Hide/Show' menu or by pressing `S-mouse-2' within
    the code (see customization group `vhdl-menu').  XEmacs: limited
    functionality due to old `hideshow.el' package.


  CODE UPDATING:
    - Sensitivity List: `C-c C-u C-s' updates the sensitivity list of the
      current process, `C-c C-u M-s' of all processes in the current buffer.
      Limitations:
        - Only declared local signals (ports, signals declared in
          architecture and blocks) are automatically inserted.
        - Global signals declared in packages are not automatically inserted.
          Insert them once manually (will be kept afterwards).
        - Out parameters of procedures are considered to be read.
      Use option `vhdl-entity-file-name' to specify the entity file name
      \(used to obtain the port names).


  CODE FIXING:
    `C-c C-x C-p' fixes the closing parenthesis of a generic/port clause
    \(e.g. if the closing parenthesis is on the wrong line or is missing).


  PRINTING:
    Postscript printing with different faces (an optimized set of faces is
    used if `vhdl-print-customize-faces' is non-nil) or colors \(if
    `ps-print-color-p' is non-nil) is possible using the standard Emacs
    postscript printing commands.  Option `vhdl-print-two-column' defines
    appropriate default settings for nice landscape two-column printing.
    The paper format can be set by option `ps-paper-type'.  Do not forget to
    switch `ps-print-color-p' to nil for printing on black-and-white
    printers.


| OPTIONS:
|   User options allow customization of VHDL Mode.  All options are
|   accessible from the \"Options\" menu entry.  Simple options (switches
|   and choices) can directly be changed, while for complex options a
|   customization buffer is opened.  Changed options can be saved for future
|   sessions using the \"Save Options\" menu entry.
|
|     Options and their detailed descriptions can also be accessed by using
|   the \"Customize\" menu entry or the command `M-x customize-option' (`M-x
|   customize-group' for groups).  Some customizations only take effect
    after some action (read the NOTE in the option documentation).
    Customization can also be done globally (i.e. site-wide, read the
    INSTALL file).

|     Not all options are described in this documentation, so go and see
|   what other useful user options there are (`M-x vhdl-customize' or menu)!


  FILE EXTENSIONS:
    As default, files with extensions \".vhd\" and \".vhdl\" are
    automatically recognized as VHDL source files.  To add an extension
    \".xxx\", add the following line to your Emacs start-up file (`.emacs'):

      \(setq auto-mode-alist (cons '(\"\\\\.xxx\\\\'\" . vhdl-mode) auto-mode-alist))


  HINTS:
|   - To start Emacs with open VHDL hierarchy browser without having to load
|     a VHDL file first, use the command:
|
|       emacs -l vhdl-mode -f speedbar-frame-mode

    - Type `C-g C-g' to interrupt long operations or if Emacs hangs.

    - Some features only work on properly indented code.


  RELEASE NOTES:
    See also the release notes (menu) for added features in new releases.


Maintenance:
------------

To submit a bug report, enter `M-x vhdl-submit-bug-report' within VHDL Mode.
Add a description of the problem and include a reproducible test case.

Questions and enhancement requests can be sent to <reto@gnu.org>.

The `vhdl-mode-announce' mailing list informs about new VHDL Mode releases.
The `vhdl-mode-victims' mailing list informs about new VHDL Mode beta
releases.  You are kindly invited to participate in beta testing.  Subscribe
to above mailing lists by sending an email to <reto@gnu.org>.

VHDL Mode is officially distributed at
http://opensource.ethz.ch/emacs/vhdl-mode.html
where the latest version can be found.


Known problems:
---------------

- Indentation bug in simultaneous if- and case-statements (VHDL-AMS).
- XEmacs: Incorrect start-up when automatically opening speedbar.


                                                The VHDL Mode Authors
                                            Reto Zimmermann and Rod Whitby

Key bindings:
-------------

\\{vhdl-mode-map}"
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'vhdl-mode)
  (setq mode-name "VHDL")

  ;; set maps and tables
  (use-local-map vhdl-mode-map)
  (set-syntax-table vhdl-mode-syntax-table)
  (setq local-abbrev-table vhdl-mode-abbrev-table)

  ;; set local variables
  (set (make-local-variable 'paragraph-start)
       "\\s-*\\(--+\\s-*$\\|[^ -]\\|$\\)")
  (set (make-local-variable 'paragraph-separate) paragraph-start)
  (set (make-local-variable 'paragraph-ignore-fill-prefix) t)
  (set (make-local-variable 'require-final-newline) t)
  (set (make-local-variable 'parse-sexp-ignore-comments) t)
  (set (make-local-variable 'indent-line-function) 'vhdl-indent-line)
  (set (make-local-variable 'comment-start) "--")
  (set (make-local-variable 'comment-end) "")
  (set (make-local-variable 'comment-column) vhdl-inline-comment-column)
  (set (make-local-variable 'end-comment-column) vhdl-end-comment-column)
  (set (make-local-variable 'comment-start-skip) "--+\\s-*")
  (set (make-local-variable 'comment-multi-line) nil)
  (set (make-local-variable 'indent-tabs-mode) vhdl-indent-tabs-mode)
  (set (make-local-variable 'hippie-expand-verbose) nil)

  ;; setup the comment indent variable in a Emacs version portable way
  ;; ignore any byte compiler warnings you might get here
  (when (boundp 'comment-indent-function)
    (make-local-variable 'comment-indent-function)
    (setq comment-indent-function 'vhdl-comment-indent))

  ;; initialize font locking
  (set (make-local-variable 'font-lock-defaults)
       (list
	'vhdl-font-lock-keywords nil
	(not vhdl-highlight-case-sensitive) '((?\_ . "w")) 'beginning-of-line
	'(font-lock-syntactic-keywords . vhdl-font-lock-syntactic-keywords)))
  (set (make-local-variable 'font-lock-support-mode) 'lazy-lock-mode)
  (set (make-local-variable 'lazy-lock-defer-contextually) nil)
  (set (make-local-variable 'lazy-lock-defer-on-the-fly) t)
;  (set (make-local-variable 'lazy-lock-defer-time) 0.1)
  (set (make-local-variable 'lazy-lock-defer-on-scrolling) t)
  (turn-on-font-lock)

  ;; variables for source file compilation
  (when vhdl-compile-use-local-error-regexp
    (set (make-local-variable 'compilation-error-regexp-alist) nil)
    (set (make-local-variable 'compilation-file-regexp-alist) nil))

  ;; add index menu
  (vhdl-index-menu-init)
  ;; add source file menu
  (if vhdl-source-file-menu (vhdl-add-source-files-menu))
  ;; add VHDL menu
  (easy-menu-add vhdl-mode-menu-list)	; for XEmacs
  (easy-menu-define vhdl-mode-menu vhdl-mode-map
		    "Menu keymap for VHDL Mode." vhdl-mode-menu-list)
  ;; initialize hideshow and add menu
  (vhdl-hideshow-init)
  (run-hooks 'menu-bar-update-hook)

  ;; miscellaneous
  (vhdl-ps-print-init)
  (vhdl-write-file-hooks-init)
  (vhdl-mode-line-update)
  (message "VHDL Mode %s.%s" vhdl-version
	   (if noninteractive "" "  See menu for documentation and release notes."))

  ;; run hooks
  (run-hooks 'vhdl-mode-hook))

(defun vhdl-activate-customizations ()
  "Activate all customizations on local variables."
  (interactive)
  (vhdl-mode-map-init)
  (use-local-map vhdl-mode-map)
  (set-syntax-table vhdl-mode-syntax-table)
  (setq comment-column vhdl-inline-comment-column)
  (setq end-comment-column vhdl-end-comment-column)
  (vhdl-write-file-hooks-init)
  (vhdl-update-mode-menu)
  (vhdl-hideshow-init)
  (run-hooks 'menu-bar-update-hook)
  (vhdl-mode-line-update))

(defun vhdl-write-file-hooks-init ()
  "Add/remove hooks when buffer is saved."
  (if vhdl-modify-date-on-saving
      (add-hook 'local-write-file-hooks 'vhdl-template-modify-noerror)
    (remove-hook 'local-write-file-hooks 'vhdl-template-modify-noerror))
  (make-local-variable 'after-save-hook)
  (add-hook 'after-save-hook 'vhdl-add-modified-file))

(defun vhdl-process-command-line-option (option)
  "Process command line options for VHDL Mode."
  (cond
   ;; set compiler
   ((equal option "-compiler")
    (vhdl-set-compiler (car command-line-args-left))
    (setq command-line-args-left (cdr command-line-args-left)))
   ;; set project
   ((equal option "-project")
    (vhdl-set-project (car command-line-args-left))
    (setq command-line-args-left (cdr command-line-args-left)))))

;; make Emacs process VHDL Mode options
(setq command-switch-alist
      (append command-switch-alist
	      '(("-compiler" . vhdl-process-command-line-option)
		("-project" . vhdl-process-command-line-option))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Keywords and standardized words
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defconst vhdl-93-keywords
  '(
    "abs" "access" "after" "alias" "all" "and" "architecture" "array"
    "assert" "attribute"
    "begin" "block" "body" "buffer" "bus"
    "case" "component" "configuration" "constant"
    "disconnect" "downto"
    "else" "elsif" "end" "entity" "exit"
    "file" "for" "function"
    "generate" "generic" "group" "guarded"
    "if" "impure" "in" "inertial" "inout" "is"
    "label" "library" "linkage" "literal" "loop"
    "map" "mod"
    "nand" "new" "next" "nor" "not" "null"
    "of" "on" "open" "or" "others" "out"
    "package" "port" "postponed" "procedure" "process" "pure"
    "range" "record" "register" "reject" "rem" "report" "return"
    "rol" "ror"
    "select" "severity" "shared" "signal" "sla" "sll" "sra" "srl" "subtype"
    "then" "to" "transport" "type"
    "unaffected" "units" "until" "use"
    "variable"
    "wait" "when" "while" "with"
    "xnor" "xor"
    )
  "List of VHDL'93 keywords.")

(defconst vhdl-ams-keywords
  '(
    "across" "break" "limit" "nature" "noise" "procedural" "quantity"
    "reference" "spectrum" "subnature" "terminal" "through"
    "tolerance"
    )
  "List of VHDL-AMS keywords.")

(defconst vhdl-verilog-keywords
  '(
    "`define" "`else" "`endif" "`ifdef" "`include" "`timescale" "`undef"
    "always" "and" "assign" "begin" "buf" "bufif0" "bufif1"
    "case" "casex" "casez" "cmos" "deassign" "default" "defparam" "disable"
    "edge" "else" "end" "endattribute" "endcase" "endfunction" "endmodule"
    "endprimitive" "endspecify" "endtable" "endtask" "event"
    "for" "force" "forever" "fork" "function"
    "highz0" "highz1" "if" "initial" "inout" "input" "integer" "join" "large"
    "macromodule" "makefile" "medium" "module"
    "nand" "negedge" "nmos" "nor" "not" "notif0" "notif1" "or" "output"
    "parameter" "pmos" "posedge" "primitive" "pull0" "pull1" "pulldown"
    "pullup"
    "rcmos" "real" "realtime" "reg" "release" "repeat" "rnmos" "rpmos" "rtran"
    "rtranif0" "rtranif1"
    "scalared" "signed" "small" "specify" "specparam" "strength" "strong0"
    "strong1" "supply" "supply0" "supply1"
    "table" "task" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
    "triand" "trior" "trireg"
    "vectored" "wait" "wand" "weak0" "weak1" "while" "wire" "wor" "xnor" "xor"
    )
  "List of Verilog keywords as candidate for additional reserved words.")

(defconst vhdl-93-types
  '(
    "boolean" "bit" "bit_vector" "character" "severity_level" "integer"
    "real" "time" "natural" "positive" "string" "line" "text" "side"
    "unsigned" "signed" "delay_length" "file_open_kind" "file_open_status"
    "std_logic" "std_logic_vector"
    "std_ulogic" "std_ulogic_vector"
    )
  "List of VHDL'93 standardized types.")

(defconst vhdl-ams-types
  '(
    "domain_type" "real_vector"
    )
  "List of VHDL-AMS standardized types.")

(defconst vhdl-math-types
  '(
    "complex" "complex_polar"
    )
  "List of Math Packages standardized types.")

(defconst vhdl-93-attributes
  '(
    "base" "left" "right" "high" "low" "pos" "val" "succ"
    "pred" "leftof" "rightof" "range" "reverse_range"
    "length" "delayed" "stable" "quiet" "transaction"
    "event" "active" "last_event" "last_active" "last_value"
    "driving" "driving_value" "ascending" "value" "image"
    "simple_name" "instance_name" "path_name"
    "foreign"
    )
  "List of VHDL'93 standardized attributes.")

(defconst vhdl-ams-attributes
  '(
    "across" "through"
    "reference" "contribution" "tolerance"
    "dot" "integ" "delayed" "above" "zoh" "ltf" "ztf"
    "ramp" "slew"
    )
  "List of VHDL-AMS standardized attributes.")

(defconst vhdl-93-enum-values
  '(
    "true" "false"
    "note" "warning" "error" "failure"
    "read_mode" "write_mode" "append_mode"
    "open_ok" "status_error" "name_error" "mode_error"
    "fs" "ps" "ns" "us" "ms" "sec" "min" "hr"
    "right" "left"
    )
  "List of VHDL'93 standardized enumeration values.")

(defconst vhdl-ams-enum-values
  '(
    "quiescent_domain" "time_domain" "frequency_domain"
    )
  "List of VHDL-AMS standardized enumeration values.")

(defconst vhdl-math-constants
  '(
    "math_e" "math_1_over_e"
    "math_pi" "math_two_pi" "math_1_over_pi"
    "math_half_pi" "math_q_pi" "math_3_half_pi"
    "math_log_of_2" "math_log_of_10" "math_log2_of_e" "math_log10_of_e"
    "math_sqrt2" "math_sqrt1_2" "math_sqrt_pi"
    "math_deg_to_rad" "math_rad_to_deg"
    "cbase_1" "cbase_j" "czero"
    )
  "List of Math Packages standardized constants.")

(defconst vhdl-93-functions
  '(
    "now" "resolved" "rising_edge" "falling_edge"
    "read" "readline" "write" "writeline" "endfile"
    "resize" "is_X" "std_match"
    "shift_left" "shift_right" "rotate_left" "rotate_right"
    "to_unsigned" "to_signed" "to_integer"
    "to_stdLogicVector" "to_stdULogic" "to_stdULogicVector"
    "to_bit" "to_bitVector" "to_X01" "to_X01Z" "to_UX01" "to_01"
    "conv_unsigned" "conv_signed" "conv_integer" "conv_std_logic_vector"
    "shl" "shr" "ext" "sxt"
    )
  "List of VHDL'93 standardized functions.")

(defconst vhdl-ams-functions
  '(
    "frequency"
    )
  "List of VHDL-AMS standardized functions.")

(defconst vhdl-math-functions
  '(
    "sign" "ceil" "floor" "round" "trunc" "fmax" "fmin" "uniform"
    "sqrt" "cbrt" "exp" "log"
    "sin" "cos" "tan" "arcsin" "arccos" "arctan"
    "sinh" "cosh" "tanh" "arcsinh" "arccosh" "arctanh"
    "cmplx" "complex_to_polar" "polar_to_complex" "arg" "conj"
    )
  "List of Math Packages standardized functions.")

(defconst vhdl-93-packages
  '(
    "std_logic_1164" "numeric_std" "numeric_bit"
    "standard" "textio"
    "std_logic_arith" "std_logic_signed" "std_logic_unsigned"
    "std_logic_misc" "std_logic_textio"
    "ieee" "std" "work"
    )
  "List of VHDL'93 standardized packages and libraries.")

(defconst vhdl-math-packages
  '(
    "math_real" "math_complex"
    )
  "List of Math Packages standardized packages and libraries.")

(defvar vhdl-keywords nil
  "List of VHDL keywords.")

(defvar vhdl-types nil
  "List of VHDL standardized types.")

(defvar vhdl-attributes nil
  "List of VHDL standardized attributes.")

(defvar vhdl-enum-values nil
  "List of VHDL standardized enumeration values.")

(defvar vhdl-constants nil
  "List of VHDL standardized constants.")

(defvar vhdl-functions nil
  "List of VHDL standardized functions.")

(defvar vhdl-packages nil
  "List of VHDL standardized packages and libraries.")

(defvar vhdl-reserved-words nil
  "List of additional reserved words.")

(defvar vhdl-keywords-regexp nil
  "Regexp for VHDL keywords.")

(defvar vhdl-types-regexp nil
  "Regexp for VHDL standardized types.")

(defvar vhdl-attributes-regexp nil
  "Regexp for VHDL standardized attributes.")

(defvar vhdl-enum-values-regexp nil
  "Regexp for VHDL standardized enumeration values.")

(defvar vhdl-functions-regexp nil
  "Regexp for VHDL standardized functions.")

(defvar vhdl-packages-regexp nil
  "Regexp for VHDL standardized packages and libraries.")

(defvar vhdl-reserved-words-regexp nil
  "Regexp for additional reserved words.")

(defvar vhdl-directive-keywords-regexp nil
  "Regexp for compiler directive keywords.")

(defun vhdl-words-init ()
  "Initialize reserved words."
  (setq vhdl-keywords
	(append vhdl-93-keywords
		(when (vhdl-standard-p 'ams) vhdl-ams-keywords)))
  (setq vhdl-types
	(append vhdl-93-types
		(when (vhdl-standard-p 'ams) vhdl-ams-types)
		(when (vhdl-standard-p 'math) vhdl-math-types)))
  (setq vhdl-attributes
	(append vhdl-93-attributes
		(when (vhdl-standard-p 'ams) vhdl-ams-attributes)))
  (setq vhdl-enum-values
	(append vhdl-93-enum-values
		(when (vhdl-standard-p 'ams) vhdl-ams-enum-values)))
  (setq vhdl-constants
	(append (when (vhdl-standard-p 'math) vhdl-math-constants)))
  (setq vhdl-functions
	(append vhdl-93-functions
		(when (vhdl-standard-p 'ams) vhdl-ams-functions)
		(when (vhdl-standard-p 'math) vhdl-math-functions)))
  (setq vhdl-packages
	(append vhdl-93-packages
		(when (vhdl-standard-p 'math) vhdl-math-packages)))
  (setq vhdl-reserved-words
	(append (when vhdl-highlight-forbidden-words vhdl-forbidden-words)
		(when vhdl-highlight-verilog-keywords vhdl-verilog-keywords)
		'("")))
  (setq vhdl-keywords-regexp
	(concat "\\<\\(" (regexp-opt vhdl-keywords) "\\)\\>"))
  (setq vhdl-types-regexp
	(concat "\\<\\(" (regexp-opt vhdl-types) "\\)\\>"))
  (setq vhdl-attributes-regexp
	(concat "\\<\\(" (regexp-opt vhdl-attributes) "\\)\\>"))
  (setq vhdl-enum-values-regexp
	(concat "\\<\\(" (regexp-opt vhdl-enum-values) "\\)\\>"))
  (setq vhdl-functions-regexp
	(concat "\\<\\(" (regexp-opt vhdl-functions) "\\)\\>"))
  (setq vhdl-packages-regexp
	(concat "\\<\\(" (regexp-opt vhdl-packages) "\\)\\>"))
  (setq vhdl-reserved-words-regexp
	(concat "\\<\\("
		(unless (equal vhdl-forbidden-syntax "")
		  (concat vhdl-forbidden-syntax "\\|"))
		(regexp-opt vhdl-reserved-words)
		"\\)\\>"))
  (setq vhdl-directive-keywords-regexp
	(concat "\\<\\(" (mapconcat 'regexp-quote
				    vhdl-directive-keywords "\\|") "\\)\\>"))
  (vhdl-abbrev-list-init))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Words to expand

(defvar vhdl-abbrev-list nil
  "Predefined abbreviations for VHDL.")

(defun vhdl-abbrev-list-init ()
  (setq vhdl-abbrev-list
	(append
	 (list vhdl-upper-case-keywords) vhdl-keywords
	 (list vhdl-upper-case-types) vhdl-types
	 (list vhdl-upper-case-attributes) vhdl-attributes
	 (list vhdl-upper-case-enum-values) vhdl-enum-values
	 (list vhdl-upper-case-constants) vhdl-constants
	 (list nil) vhdl-functions
	 (list nil) vhdl-packages)))

;; initialize reserved words for VHDL Mode
(vhdl-words-init)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Indentation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Syntax analysis

;; constant regular expressions for looking at various constructs

(defconst vhdl-symbol-key "\\(\\w\\|\\s_\\)+"
  "Regexp describing a VHDL symbol.
We cannot use just `word' syntax class since `_' cannot be in word
class.  Putting underscore in word class breaks forward word movement
behavior that users are familiar with.")

(defconst vhdl-case-header-key "case[( \t\n][^;=>]+[) \t\n]is"
  "Regexp describing a case statement header key.")

(defconst vhdl-label-key
  (concat "\\(" vhdl-symbol-key "\\s-*:\\)[^=]")
  "Regexp describing a VHDL label.")

;; Macro definitions:

(defmacro vhdl-point (position)
  "Return the value of point at certain commonly referenced POSITIONs.
POSITION can be one of the following symbols:

bol  -- beginning of line
eol  -- end of line
bod  -- beginning of defun
boi  -- back to indentation
eoi  -- last whitespace on line
ionl -- indentation of next line
iopl -- indentation of previous line
bonl -- beginning of next line
bopl -- beginning of previous line

This function does not modify point or mark."
  (or (and (eq 'quote (car-safe position))
	   (null (cddr position)))
      (error "Bad buffer position requested: %s" position))
  (setq position (nth 1 position))
  `(let ((here (point)))
     ,@(cond
	((eq position 'bol)  '((beginning-of-line)))
	((eq position 'eol)  '((end-of-line)))
	((eq position 'bod)  '((save-match-data
				 (vhdl-beginning-of-defun))))
	((eq position 'boi)  '((back-to-indentation)))
	((eq position 'eoi)  '((end-of-line)(skip-chars-backward " \t")))
	((eq position 'bonl) '((forward-line 1)))
	((eq position 'bopl) '((forward-line -1)))
	((eq position 'iopl)
	 '((forward-line -1)
	   (back-to-indentation)))
	((eq position 'ionl)
	 '((forward-line 1)
	   (back-to-indentation)))
	(t (error "Unknown buffer position requested: %s" position))
	)
     (prog1
	 (point)
       (goto-char here))
     ;; workaround for an Emacs18 bug -- blech! Well, at least it
     ;; doesn't hurt for v19
     ,@nil
     ))

(defmacro vhdl-safe (&rest body)
  "Safely execute BODY, return nil if an error occurred."
  `(condition-case nil
       (progn ,@body)
     (error nil)))

(defmacro vhdl-add-syntax (symbol &optional relpos)
  "A simple macro to append the syntax in SYMBOL to the syntax list.
Try to increase performance by using this macro."
  `(setq vhdl-syntactic-context
	 (cons (cons ,symbol ,relpos) vhdl-syntactic-context)))

(defmacro vhdl-has-syntax (symbol)
  "A simple macro to return check the syntax list.
Try to increase performance by using this macro."
  `(assoc ,symbol vhdl-syntactic-context))

;; Syntactic element offset manipulation:

(defun vhdl-read-offset (langelem)
  "Read new offset value for LANGELEM from minibuffer.
Return a legal value only."
  (let ((oldoff (format "%s" (cdr-safe (assq langelem vhdl-offsets-alist))))
	(errmsg "Offset must be int, func, var, or one of +, -, ++, --: ")
	(prompt "Offset: ")
	offset input interned)
    (while (not offset)
      (setq input (read-string prompt oldoff)
	    offset (cond ((string-equal "+" input) '+)
			 ((string-equal "-" input) '-)
			 ((string-equal "++" input) '++)
			 ((string-equal "--" input) '--)
			 ((string-match "^-?[0-9]+$" input)
			  (string-to-int input))
			 ((fboundp (setq interned (intern input)))
			  interned)
			 ((boundp interned) interned)
			 ;; error, but don't signal one, keep trying
			 ;; to read an input value
			 (t (ding)
			    (setq prompt errmsg)
			    nil))))
    offset))

(defun vhdl-set-offset (symbol offset &optional add-p)
  "Change the value of a syntactic element symbol in `vhdl-offsets-alist'.
SYMBOL is the syntactic element symbol to change and OFFSET is the new
offset for that syntactic element.  Optional ADD says to add SYMBOL to
`vhdl-offsets-alist' if it doesn't already appear there."
  (interactive
   (let* ((langelem
	   (intern (completing-read
		    (concat "Syntactic symbol to change"
			    (if current-prefix-arg " or add" "")
			    ": ")
		    (mapcar
		     (function
		      (lambda (langelem)
			(cons (format "%s" (car langelem)) nil)))
		     vhdl-offsets-alist)
		    nil (not current-prefix-arg)
		    ;; initial contents tries to be the last element
		    ;; on the syntactic analysis list for the current
		    ;; line
		    (let* ((syntax (vhdl-get-syntactic-context))
			   (len (length syntax))
			   (ic (format "%s" (car (nth (1- len) syntax)))))
		      ic)
		    )))
	  (offset (vhdl-read-offset langelem)))
     (list langelem offset current-prefix-arg)))
  ;; sanity check offset
  (or (eq offset '+)
      (eq offset '-)
      (eq offset '++)
      (eq offset '--)
      (integerp offset)
      (fboundp offset)
      (boundp offset)
      (error "Offset must be int, func, var, or one of +, -, ++, --: %s"
	     offset))
  (let ((entry (assq symbol vhdl-offsets-alist)))
    (if entry
	(setcdr entry offset)
      (if add-p
	  (setq vhdl-offsets-alist
		(cons (cons symbol offset) vhdl-offsets-alist))
	(error "%s is not a valid syntactic symbol" symbol))))
  (vhdl-keep-region-active))

(defun vhdl-set-style (style &optional local)
  "Set `vhdl-mode' variables to use one of several different indentation styles.
STYLE is a string representing the desired style and optional LOCAL is
a flag which, if non-nil, means to make the style variables being
changed buffer local, instead of the default, which is to set the
global variables.  Interactively, the flag comes from the prefix
argument.  The styles are chosen from the `vhdl-style-alist' variable."
  (interactive (list (completing-read "Use which VHDL indentation style? "
				      vhdl-style-alist nil t)
		     current-prefix-arg))
  (let ((vars (cdr (assoc style vhdl-style-alist))))
    (or vars
	(error "Invalid VHDL indentation style `%s'" style))
    ;; set all the variables
    (mapcar
     (function
      (lambda (varentry)
	(let ((var (car varentry))
	      (val (cdr varentry)))
	  (and local
	       (make-local-variable var))
	  ;; special case for vhdl-offsets-alist
	  (if (not (eq var 'vhdl-offsets-alist))
	      (set var val)
	    ;; reset vhdl-offsets-alist to the default value first
	    (setq vhdl-offsets-alist (copy-alist vhdl-offsets-alist-default))
	    ;; now set the langelems that are different
	    (mapcar
	     (function
	      (lambda (langentry)
		(let ((langelem (car langentry))
		      (offset (cdr langentry)))
		  (vhdl-set-offset langelem offset)
		  )))
	     val))
	  )))
     vars))
  (vhdl-keep-region-active))

(defun vhdl-get-offset (langelem)
  "Get offset from LANGELEM which is a cons cell of the form:
\(SYMBOL . RELPOS).  The symbol is matched against
vhdl-offsets-alist and the offset found there is either returned,
or added to the indentation at RELPOS.  If RELPOS is nil, then
the offset is simply returned."
  (let* ((symbol (car langelem))
	 (relpos (cdr langelem))
	 (match  (assq symbol vhdl-offsets-alist))
	 (offset (cdr-safe match)))
    ;; offset can be a number, a function, a variable, or one of the
    ;; symbols + or -
    (cond
     ((not match)
      (if vhdl-strict-syntax-p
	  (error "Don't know how to indent a %s" symbol)
	(setq offset 0
	      relpos 0)))
     ((eq offset '+)  (setq offset vhdl-basic-offset))
     ((eq offset '-)  (setq offset (- vhdl-basic-offset)))
     ((eq offset '++) (setq offset (* 2 vhdl-basic-offset)))
     ((eq offset '--) (setq offset (* 2 (- vhdl-basic-offset))))
     ((and (not (numberp offset))
	   (fboundp offset))
      (setq offset (funcall offset langelem)))
     ((not (numberp offset))
      (setq offset (eval offset)))
     )
    (+ (if (and relpos
		(< relpos (vhdl-point 'bol)))
	   (save-excursion
	     (goto-char relpos)
	     (current-column))
	 0)
       offset)))

;; Syntactic support functions:

;; Returns `comment' if in a comment, `string' if in a string literal,
;; or nil if not in a literal at all.  Optional LIM is used as the
;; backward limit of the search.  If omitted, or nil, (point-min) is
;; used.

(defun vhdl-in-literal (&optional lim)
  "Determine if point is in a VHDL literal."
  (save-excursion
    (let ((state (parse-partial-sexp (vhdl-point 'bol) (point))))
      (cond
       ((nth 3 state) 'string)
       ((nth 4 state) 'comment)
       (t nil)))))

;; This is the best we can do in Win-Emacs.
(defun vhdl-win-il (&optional lim)
  "Determine if point is in a VHDL literal."
  (save-excursion
    (let* ((here (point))
	   (state nil)
	   (match nil)
	   (lim  (or lim (vhdl-point 'bod))))
      (goto-char lim )
      (while (< (point) here)
	(setq match
	      (and (re-search-forward "--\\|[\"']"
				      here 'move)
		   (buffer-substring (match-beginning 0) (match-end 0))))
	(setq state
	      (cond
	       ;; no match
	       ((null match) nil)
	       ;; looking at the opening of a VHDL style comment
	       ((string= "--" match)
		(if (<= here (progn (end-of-line) (point))) 'comment))
	       ;; looking at the opening of a double quote string
	       ((string= "\"" match)
		(if (not (save-restriction
			   ;; this seems to be necessary since the
			   ;; re-search-forward will not work without it
			   (narrow-to-region (point) here)
			   (re-search-forward
			    ;; this regexp matches a double quote
			    ;; which is preceded by an even number
			    ;; of backslashes, including zero
			    "\\([^\\]\\|^\\)\\(\\\\\\\\\\)*\"" here 'move)))
		    'string))
	       ;; looking at the opening of a single quote string
	       ((string= "'" match)
		(if (not (save-restriction
			   ;; see comments from above
			   (narrow-to-region (point) here)
			   (re-search-forward
			    ;; this matches a single quote which is
			    ;; preceded by zero or two backslashes.
			    "\\([^\\]\\|^\\)\\(\\\\\\\\\\)?'"
			    here 'move)))
		    'string))
	       (t nil)))
	) ; end-while
      state)))

(and (string-match "Win-Emacs" emacs-version)
     (fset 'vhdl-in-literal 'vhdl-win-il))

;; Skipping of "syntactic whitespace".  Syntactic whitespace is
;; defined as lexical whitespace or comments.  Search no farther back
;; or forward than optional LIM.  If LIM is omitted, (point-min) is
;; used for backward skipping, (point-max) is used for forward
;; skipping.

(defun vhdl-forward-syntactic-ws (&optional lim)
  "Forward skip of syntactic whitespace."
  (save-restriction
    (let* ((lim (or lim (point-max)))
	   (here lim)
	   (hugenum (point-max)))
      (narrow-to-region lim (point))
      (while (/= here (point))
	(setq here (point))
	(forward-comment hugenum)))))

;; This is the best we can do in Win-Emacs.
(defun vhdl-win-fsws (&optional lim)
  "Forward skip syntactic whitespace for Win-Emacs."
  (let ((lim (or lim (point-max)))
	stop)
    (while (not stop)
      (skip-chars-forward " \t\n\r\f" lim)
      (cond
       ;; vhdl comment
       ((looking-at "--") (end-of-line))
       ;; none of the above
       (t (setq stop t))))))

(and (string-match "Win-Emacs" emacs-version)
     (fset 'vhdl-forward-syntactic-ws 'vhdl-win-fsws))

(defun vhdl-backward-syntactic-ws (&optional lim)
  "Backward skip over syntactic whitespace."
  (save-restriction
    (let* ((lim (or lim (point-min)))
	   (here lim)
	   (hugenum (- (point-max))))
      (if (< lim (point))
	  (progn
	    (narrow-to-region lim (point))
	    (while (/= here (point))
	      (setq here (point))
	      (forward-comment hugenum)))))))

;; This is the best we can do in Win-Emacs.
(defun vhdl-win-bsws (&optional lim)
  "Backward skip syntactic whitespace for Win-Emacs."
  (let ((lim (or lim (vhdl-point 'bod)))
	stop)
    (while (not stop)
      (skip-chars-backward " \t\n\r\f" lim)
      (cond
       ;; vhdl comment
       ((eq (vhdl-in-literal lim) 'comment)
	(skip-chars-backward "^-" lim)
	(skip-chars-backward "-" lim)
	(while (not (or (and (= (following-char) ?-)
			     (= (char-after (1+ (point))) ?-))
			(<= (point) lim)))
	  (skip-chars-backward "^-" lim)
	  (skip-chars-backward "-" lim)))
       ;; none of the above
       (t (setq stop t))))))

(and (string-match "Win-Emacs" emacs-version)
    (fset 'vhdl-backward-syntactic-ws 'vhdl-win-bsws))

;; Functions to help finding the correct indentation column:

(defun vhdl-first-word (point)
  "If the keyword at POINT is at boi, then return (current-column) at
that point, else nil."
  (save-excursion
    (and (goto-char point)
	 (eq (point) (vhdl-point 'boi))
	 (current-column))))

(defun vhdl-last-word (point)
  "If the keyword at POINT is at eoi, then return (current-column) at
that point, else nil."
  (save-excursion
    (and (goto-char point)
	 (save-excursion (or (eq (progn (forward-sexp) (point))
				 (vhdl-point 'eoi))
			     (looking-at "\\s-*\\(--\\)?")))
	 (current-column))))

;; Core syntactic evaluation functions:

(defconst vhdl-libunit-re
  "\\b\\(architecture\\|configuration\\|entity\\|package\\)\\b[^_]")

(defun vhdl-libunit-p ()
  (and
   (save-excursion
     (forward-sexp)
     (skip-chars-forward " \t\n")
     (not (looking-at "is\\b[^_]")))
   (save-excursion
     (backward-sexp)
     (and (not (looking-at "use\\b[^_]"))
	  (progn
	    (forward-sexp)
	    (vhdl-forward-syntactic-ws)
	    (/= (following-char) ?:))))
   ))

(defconst vhdl-defun-re
  "\\b\\(architecture\\|block\\|configuration\\|entity\\|package\\|process\\|procedural\\|procedure\\|function\\)\\b[^_]")

(defun vhdl-defun-p ()
  (save-excursion
    (if (looking-at "block\\|process\\|procedural")
	;; "block", "process", "procedural":
	(save-excursion
	  (backward-sexp)
	  (not (looking-at "end\\s-+\\w")))
      ;; "architecture", "configuration", "entity",
      ;; "package", "procedure", "function":
      t)))

(defun vhdl-corresponding-defun ()
  "If the word at the current position corresponds to a \"defun\"
keyword, then return a string that can be used to find the
corresponding \"begin\" keyword, else return nil."
  (save-excursion
    (and (looking-at vhdl-defun-re)
	 (vhdl-defun-p)
	 (if (looking-at "block\\|process\\|procedural")
	     ;; "block", "process". "procedural:
	     (buffer-substring (match-beginning 0) (match-end 0))
	   ;; "architecture", "configuration", "entity", "package",
	   ;; "procedure", "function":
	   "is"))))

(defconst vhdl-begin-fwd-re
  "\\b\\(is\\|begin\\|block\\|component\\|generate\\|then\\|else\\|loop\\|process\\|procedural\\|units\\|record\\|for\\)\\b\\([^_]\\|\\'\\)"
  "A regular expression for searching forward that matches all known
\"begin\" keywords.")

(defconst vhdl-begin-bwd-re
  "\\b\\(is\\|begin\\|block\\|component\\|generate\\|then\\|else\\|loop\\|process\\|procedural\\|units\\|record\\|for\\)\\b[^_]"
  "A regular expression for searching backward that matches all known
\"begin\" keywords.")

(defun vhdl-begin-p (&optional lim)
  "Return t if we are looking at a real \"begin\" keyword.
Assumes that the caller will make sure that we are looking at
vhdl-begin-fwd-re, and are not inside a literal, and that we are not in
the middle of an identifier that just happens to contain a \"begin\"
keyword."
  (cond
   ;; "[architecture|case|configuration|entity|package|
   ;;   procedure|function] ... is":
   ((and (looking-at "i")
	 (save-excursion
	   ;; Skip backward over first sexp (needed to skip over a
	   ;; procedure interface list, and is harmless in other
	   ;; situations).  Note that we need "return" in the
	   ;; following search list so that we don't run into
	   ;; semicolons in the function interface list.
	   (backward-sexp)
	   (let (foundp)
	     (while (and (not foundp)
			 (re-search-backward
			  ";\\|\\b\\(architecture\\|case\\|configuration\\|entity\\|package\\|procedure\\|return\\|is\\|begin\\|process\\|procedural\\|block\\)\\b[^_]"
			  lim 'move))
	       (if (or (= (preceding-char) ?_)
		       (vhdl-in-literal lim))
		   (backward-char)
		 (setq foundp t))))
	   (and (/= (following-char) ?\;)
		(not (looking-at "is\\|begin\\|process\\|procedural\\|block")))))
    t)
   ;; "begin", "then":
   ((looking-at "be\\|t")
    t)
   ;; "else":
   ((and (looking-at "e")
	 ;; make sure that the "else" isn't inside a
	 ;; conditional signal assignment.
	 (save-excursion
	   (re-search-backward ";\\|\\bwhen\\b[^_]" lim 'move)
	   (or (eq (following-char) ?\;)
	       (eq (point) lim))))
    t)
   ;; "block", "generate", "loop", "process", "procedural",
   ;; "units", "record":
   ((and (looking-at "bl\\|[glpur]")
	 (save-excursion
	   (backward-sexp)
	   (not (looking-at "end\\s-+\\w"))))
    t)
   ;; "component":
   ((and (looking-at "c")
	 (save-excursion
	   (backward-sexp)
	   (not (looking-at "end\\s-+\\w")))
	 ;; look out for the dreaded entity class in an attribute
	 (save-excursion
	   (vhdl-backward-syntactic-ws lim)
	   (/= (preceding-char) ?:)))
    t)
   ;; "for" (inside configuration declaration):
   ((and (looking-at "f")
	 (save-excursion
	   (backward-sexp)
	   (not (looking-at "end\\s-+\\w")))
	 (vhdl-has-syntax 'configuration))
    t)
   ))

(defun vhdl-corresponding-mid (&optional lim)
  (cond
   ((looking-at "is\\|block\\|generate\\|process\\|procedural")
    "begin")
   ((looking-at "then")
    "<else>")
   (t
    "end")))

(defun vhdl-corresponding-end (&optional lim)
  "If the word at the current position corresponds to a \"begin\"
keyword, then return a vector containing enough information to find
the corresponding \"end\" keyword, else return nil.  The keyword to
search forward for is aref 0.  The column in which the keyword must
appear is aref 1 or nil if any column is suitable.
Assumes that the caller will make sure that we are not in the middle
of an identifier that just happens to contain a \"begin\" keyword."
  (save-excursion
    (and (looking-at vhdl-begin-fwd-re)
	 (/= (preceding-char) ?_)
	 (not (vhdl-in-literal lim))
	 (vhdl-begin-p lim)
	 (cond
	  ;; "is", "generate", "loop":
	  ((looking-at "[igl]")
	   (vector "end"
		   (and (vhdl-last-word (point))
			(or (vhdl-first-word (point))
			    (save-excursion
			      (vhdl-beginning-of-statement-1 lim)
			      (vhdl-backward-skip-label lim)
			      (vhdl-first-word (point)))))))
	  ;; "begin", "else", "for":
	  ((looking-at "be\\|[ef]")
	   (vector "end"
		   (and (vhdl-last-word (point))
			(or (vhdl-first-word (point))
			    (save-excursion
			      (vhdl-beginning-of-statement-1 lim)
			      (vhdl-backward-skip-label lim)
			      (vhdl-first-word (point)))))))
	  ;; "component", "units", "record":
	  ((looking-at "[cur]")
	   ;; The first end found will close the block
	   (vector "end" nil))
	  ;; "block", "process", "procedural":
	  ((looking-at "bl\\|p")
	   (vector "end"
		   (or (vhdl-first-word (point))
		       (save-excursion
			 (vhdl-beginning-of-statement-1 lim)
			 (vhdl-backward-skip-label lim)
			 (vhdl-first-word (point))))))
	  ;; "then":
	  ((looking-at "t")
	   (vector "elsif\\|else\\|end\\s-+if"
		   (and (vhdl-last-word (point))
			(or (vhdl-first-word (point))
			    (save-excursion
			      (vhdl-beginning-of-statement-1 lim)
			      (vhdl-backward-skip-label lim)
			      (vhdl-first-word (point)))))))
	  ))))

(defconst vhdl-end-fwd-re "\\b\\(end\\|else\\|elsif\\)\\b\\([^_]\\|\\'\\)")

(defconst vhdl-end-bwd-re "\\b\\(end\\|else\\|elsif\\)\\b[^_]")

(defun vhdl-end-p (&optional lim)
  "Return t if we are looking at a real \"end\" keyword.
Assumes that the caller will make sure that we are looking at
vhdl-end-fwd-re, and are not inside a literal, and that we are not in
the middle of an identifier that just happens to contain an \"end\"
keyword."
  (or (not (looking-at "else"))
      ;; make sure that the "else" isn't inside a conditional signal
      ;; assignment.
      (save-excursion
	(re-search-backward ";\\|\\bwhen\\b[^_]" lim 'move)
	(or (eq (following-char) ?\;)
	    (eq (point) lim)))))

(defun vhdl-corresponding-begin (&optional lim)
  "If the word at the current position corresponds to an \"end\"
keyword, then return a vector containing enough information to find
the corresponding \"begin\" keyword, else return nil.  The keyword to
search backward for is aref 0.     The column in which the keyword must
appear is aref 1 or nil if any column is suitable.  The supplementary
keyword to search forward for is aref 2 or nil if this is not
required.  If aref 3 is t, then the \"begin\" keyword may be found in
the middle of a statement.
Assumes that the caller will make sure that we are not in the middle
of an identifier that just happens to contain an \"end\" keyword."
  (save-excursion
    (let (pos)
      (if (and (looking-at vhdl-end-fwd-re)
	       (not (vhdl-in-literal lim))
	       (vhdl-end-p lim))
	  (if (looking-at "el")
	      ;; "else", "elsif":
	      (vector "if\\|elsif" (vhdl-first-word (point)) "then" nil)
	    ;; "end ...":
	    (setq pos (point))
	    (forward-sexp)
	    (skip-chars-forward " \t\n")
	    (cond
	     ;; "end if":
	     ((looking-at "if\\b[^_]")
	      (vector "else\\|elsif\\|if"
		      (vhdl-first-word pos)
		      "else\\|then" nil))
	     ;; "end component":
	     ((looking-at "component\\b[^_]")
	      (vector (buffer-substring (match-beginning 1)
					(match-end 1))
		      (vhdl-first-word pos)
		      nil nil))
	     ;; "end units", "end record":
	     ((looking-at "\\(units\\|record\\)\\b[^_]")
	      (vector (buffer-substring (match-beginning 1)
					(match-end 1))
		      (vhdl-first-word pos)
		      nil t))
	     ;; "end block", "end process", "end procedural":
	     ((looking-at "\\(block\\|process\\|procedural\\)\\b[^_]")
	      (vector "begin" (vhdl-first-word pos) nil nil))
	     ;; "end case":
	     ((looking-at "case\\b[^_]")
	      (vector "case" (vhdl-first-word pos) "is" nil))
	     ;; "end generate":
	     ((looking-at "generate\\b[^_]")
	      (vector "generate\\|for\\|if"
		      (vhdl-first-word pos)
		      "generate" nil))
	     ;; "end loop":
	     ((looking-at "loop\\b[^_]")
	      (vector "loop\\|while\\|for"
		      (vhdl-first-word pos)
		      "loop" nil))
	     ;; "end for" (inside configuration declaration):
	     ((looking-at "for\\b[^_]")
	      (vector "for" (vhdl-first-word pos) nil nil))
	     ;; "end [id]":
	     (t
	      (vector "begin\\|architecture\\|configuration\\|entity\\|package\\|procedure\\|function"
		      (vhdl-first-word pos)
		      ;; return an alist of (statement . keyword) mappings
		      '(
			;; "begin ... end [id]":
			("begin"          . nil)
			;; "architecture ... is ... begin ... end [id]":
			("architecture"   . "is")
			;; "configuration ... is ... end [id]":
			("configuration"  . "is")
			;; "entity ... is ... end [id]":
			("entity"         . "is")
			;; "package ... is ... end [id]":
			("package"        . "is")
			;; "procedure ... is ... begin ... end [id]":
			("procedure"      . "is")
			;; "function ... is ... begin ... end [id]":
			("function"       . "is")
			)
		      nil))
	     ))) ; "end ..."
      )))

(defconst vhdl-leader-re
  "\\b\\(block\\|component\\|process\\|procedural\\|for\\)\\b[^_]")

(defun vhdl-end-of-leader ()
  (save-excursion
    (cond ((looking-at "block\\|process\\|procedural")
	   (if (save-excursion
		 (forward-sexp)
		 (skip-chars-forward " \t\n")
		 (= (following-char) ?\())
	       (forward-sexp 2)
	     (forward-sexp))
	   (when (looking-at "[ \t\n]*is")
	     (goto-char (match-end 0)))
	   (point))
	  ((looking-at "component")
	   (forward-sexp 2)
	   (when (looking-at "[ \t\n]*is")
	     (goto-char (match-end 0)))
	   (point))
	  ((looking-at "for")
	   (forward-sexp 2)
	   (skip-chars-forward " \t\n")
	   (while (looking-at "[,:(]")
	     (forward-sexp)
	     (skip-chars-forward " \t\n"))
	   (point))
	  (t nil)
	  )))

(defconst vhdl-trailer-re
  "\\b\\(is\\|then\\|generate\\|loop\\)\\b[^_]")

(defconst vhdl-statement-fwd-re
  "\\b\\(if\\|for\\|while\\)\\b\\([^_]\\|\\'\\)"
  "A regular expression for searching forward that matches all known
\"statement\" keywords.")

(defconst vhdl-statement-bwd-re
  "\\b\\(if\\|for\\|while\\)\\b[^_]"
  "A regular expression for searching backward that matches all known
\"statement\" keywords.")

(defun vhdl-statement-p (&optional lim)
  "Return t if we are looking at a real \"statement\" keyword.
Assumes that the caller will make sure that we are looking at
vhdl-statement-fwd-re, and are not inside a literal, and that we are not
in the middle of an identifier that just happens to contain a
\"statement\" keyword."
  (cond
   ;; "for" ... "generate":
   ((and (looking-at "f")
	 ;; Make sure it's the start of a parameter specification.
	 (save-excursion
	   (forward-sexp 2)
	   (skip-chars-forward " \t\n")
	   (looking-at "in\\b[^_]"))
	 ;; Make sure it's not an "end for".
	 (save-excursion
	   (backward-sexp)
	   (not (looking-at "end\\s-+\\w"))))
    t)
   ;; "if" ... "then", "if" ... "generate", "if" ... "loop":
   ((and (looking-at "i")
	 ;; Make sure it's not an "end if".
	 (save-excursion
	   (backward-sexp)
	   (not (looking-at "end\\s-+\\w"))))
    t)
   ;; "while" ... "loop":
   ((looking-at "w")
    t)
   ))

(defconst vhdl-case-alternative-re "when[( \t\n][^;=>]+=>"
  "Regexp describing a case statement alternative key.")

(defun vhdl-case-alternative-p (&optional lim)
  "Return t if we are looking at a real case alternative.
Assumes that the caller will make sure that we are looking at
vhdl-case-alternative-re, and are not inside a literal, and that
we are not in the middle of an identifier that just happens to
contain a \"when\" keyword."
  (save-excursion
    (let (foundp)
      (while (and (not foundp)
		  (re-search-backward ";\\|<=" lim 'move))
	(if (or (= (preceding-char) ?_)
		(vhdl-in-literal lim))
	    (backward-char)
	  (setq foundp t)))
      (or (eq (following-char) ?\;)
	  (eq (point) lim)))
    ))

;; Core syntactic movement functions:

(defconst vhdl-b-t-b-re
  (concat vhdl-begin-bwd-re "\\|" vhdl-end-bwd-re))

(defun vhdl-backward-to-block (&optional lim)
  "Move backward to the previous \"begin\" or \"end\" keyword."
  (let (foundp)
    (while (and (not foundp)
		(re-search-backward vhdl-b-t-b-re lim 'move))
      (if (or (= (preceding-char) ?_)
	      (vhdl-in-literal lim))
	  (backward-char)
	(cond
	 ;; "begin" keyword:
	 ((and (looking-at vhdl-begin-fwd-re)
	       (/= (preceding-char) ?_)
	       (vhdl-begin-p lim))
	  (setq foundp 'begin))
	 ;; "end" keyword:
	 ((and (looking-at vhdl-end-fwd-re)
	       (/= (preceding-char) ?_)
	       (vhdl-end-p lim))
	  (setq foundp 'end))
	 ))
      )
    foundp
    ))

(defun vhdl-forward-sexp (&optional count lim)
  "Move forward across one balanced expression (sexp).
With COUNT, do it that many times."
  (interactive "p")
  (let ((count (or count 1))
	(case-fold-search t)
	end-vec target)
    (save-excursion
      (while (> count 0)
	;; skip whitespace
	(skip-chars-forward " \t\n")
	;; Check for an unbalanced "end" keyword
	(if (and (looking-at vhdl-end-fwd-re)
		 (/= (preceding-char) ?_)
		 (not (vhdl-in-literal lim))
		 (vhdl-end-p lim)
		 (not (looking-at "else")))
	    (error
	     "Containing expression ends prematurely in vhdl-forward-sexp"))
	;; If the current keyword is a "begin" keyword, then find the
	;; corresponding "end" keyword.
	(if (setq end-vec (vhdl-corresponding-end lim))
	    (let (
		  ;; end-re is the statement keyword to search for
		  (end-re
		   (concat "\\b\\(" (aref end-vec 0) "\\)\\b\\([^_]\\|\\'\\)"))
		  ;; column is either the statement keyword target column
		  ;; or nil
		  (column (aref end-vec 1))
		  (eol (vhdl-point 'eol))
		  foundp literal placeholder)
	      ;; Look for the statement keyword.
	      (while (and (not foundp)
			  (re-search-forward end-re nil t)
			  (setq placeholder (match-end 1))
			  (goto-char (match-beginning 0)))
		;; If we are in a literal, or not in the right target
		;; column and not on the same line as the begin, then
		;; try again.
		(if (or (and column
			     (/= (current-indentation) column)
			     (> (point) eol))
			(= (preceding-char) ?_)
			(setq literal (vhdl-in-literal lim)))
		    (if (eq literal 'comment)
			(end-of-line)
		      (forward-char))
		  ;; An "else" keyword corresponds to both the opening brace
		  ;; of the following sexp and the closing brace of the
		  ;; previous sexp.
		  (if (not (looking-at "else"))
		      (goto-char placeholder))
		  (setq foundp t))
		)
	      (if (not foundp)
		  (error "Unbalanced keywords in vhdl-forward-sexp"))
	      )
	  ;; If the current keyword is not a "begin" keyword, then just
	  ;; perform the normal forward-sexp.
	  (forward-sexp)
	  )
	(setq count (1- count))
	)
      (setq target (point)))
    (goto-char target)
    nil))

(defun vhdl-backward-sexp (&optional count lim)
  "Move backward across one balanced expression (sexp).
With COUNT, do it that many times.  LIM bounds any required backward
searches."
  (interactive "p")
  (let ((count (or count 1))
	(case-fold-search t)
	begin-vec target)
    (save-excursion
      (while (> count 0)
	;; Perform the normal backward-sexp, unless we are looking at
	;; "else" - an "else" keyword corresponds to both the opening brace
	;; of the following sexp and the closing brace of the previous sexp.
	(if (and (looking-at "else\\b\\([^_]\\|\\'\\)")
		 (/= (preceding-char) ?_)
		 (not (vhdl-in-literal lim)))
	    nil
	  (backward-sexp)
	  (if (and (looking-at vhdl-begin-fwd-re)
		   (/= (preceding-char) ?_)
		   (not (vhdl-in-literal lim))
		   (vhdl-begin-p lim))
	      (error "Containing expression ends prematurely in vhdl-backward-sexp")))
	;; If the current keyword is an "end" keyword, then find the
	;; corresponding "begin" keyword.
	(if (and (setq begin-vec (vhdl-corresponding-begin lim))
		 (/= (preceding-char) ?_))
	    (let (
		  ;; begin-re is the statement keyword to search for
		  (begin-re
		   (concat "\\b\\(" (aref begin-vec 0) "\\)\\b[^_]"))
		  ;; column is either the statement keyword target column
		  ;; or nil
		  (column (aref begin-vec 1))
		  ;; internal-p controls where the statement keyword can
		  ;; be found.
		  (internal-p (aref begin-vec 3))
		  (last-backward (point)) last-forward
		  foundp literal keyword)
	      ;; Look for the statement keyword.
	      (while (and (not foundp)
			  (re-search-backward begin-re lim t)
			  (setq keyword
				(buffer-substring (match-beginning 1)
						  (match-end 1))))
		;; If we are in a literal or in the wrong column,
		;; then try again.
		(if (or (and column
			     (and (/= (current-indentation) column)
				  ;; possibly accept current-column as
				  ;; well as current-indentation.
				  (or (not internal-p)
				      (/= (current-column) column))))
			(= (preceding-char) ?_)
			(vhdl-in-literal lim))
		    (backward-char)
		  ;; If there is a supplementary keyword, then
		  ;; search forward for it.
		  (if (and (setq begin-re (aref begin-vec 2))
			   (or (not (listp begin-re))
			       ;; If begin-re is an alist, then find the
			       ;; element corresponding to the actual
			       ;; keyword that we found.
			       (progn
				 (setq begin-re
				       (assoc keyword begin-re))
				 (and begin-re
				      (setq begin-re (cdr begin-re))))))
		      (and
		       (setq begin-re
			     (concat "\\b\\(" begin-re "\\)\\b[^_]"))
		       (save-excursion
			 (setq last-forward (point))
			 ;; Look for the supplementary keyword
			 ;; (bounded by the backward search start
			 ;; point).
			 (while (and (not foundp)
				     (re-search-forward begin-re
							last-backward t)
				     (goto-char (match-beginning 1)))
			   ;; If we are in a literal, then try again.
			   (if (or (= (preceding-char) ?_)
				   (setq literal
					 (vhdl-in-literal last-forward)))
			       (if (eq literal 'comment)
				   (goto-char
				    (min (vhdl-point 'eol) last-backward))
				 (forward-char))
			     ;; We have found the supplementary keyword.
			     ;; Save the position of the keyword in foundp.
			     (setq foundp (point)))
			   )
			 foundp)
		       ;; If the supplementary keyword was found, then
		       ;; move point to the supplementary keyword.
		       (goto-char foundp))
		    ;; If there was no supplementary keyword, then
		    ;; point is already at the statement keyword.
		    (setq foundp t)))
		) ; end of the search for the statement keyword
	      (if (not foundp)
		  (error "Unbalanced keywords in vhdl-backward-sexp"))
	      ))
	(setq count (1- count))
	)
      (setq target (point)))
    (goto-char target)
    nil))

(defun vhdl-backward-up-list (&optional count limit)
  "Move backward out of one level of blocks.
With argument, do this that many times."
  (interactive "p")
  (let ((count (or count 1))
	target)
    (save-excursion
      (while (> count 0)
	(if (looking-at vhdl-defun-re)
	    (error "Unbalanced blocks"))
	(vhdl-backward-to-block limit)
	(setq count (1- count)))
      (setq target (point)))
    (goto-char target)))

(defun vhdl-end-of-defun (&optional count)
  "Move forward to the end of a VHDL defun."
  (interactive)
  (let ((case-fold-search t))
    (vhdl-beginning-of-defun)
    (if (not (looking-at "block\\|process\\|procedural"))
	(re-search-forward "\\bis\\b"))
    (vhdl-forward-sexp)))

(defun vhdl-mark-defun ()
  "Put mark at end of this \"defun\", point at beginning."
  (interactive)
  (let ((case-fold-search t))
    (push-mark)
    (vhdl-beginning-of-defun)
    (push-mark)
    (if (not (looking-at "block\\|process\\|procedural"))
	(re-search-forward "\\bis\\b"))
    (vhdl-forward-sexp)
    (exchange-point-and-mark)))

(defun vhdl-beginning-of-libunit ()
  "Move backward to the beginning of a VHDL library unit.
Returns the location of the corresponding begin keyword, unless search
stops due to beginning or end of buffer.
Note that if point is between the \"libunit\" keyword and the
corresponding \"begin\" keyword, then that libunit will not be
recognised, and the search will continue backwards.  If point is
at the \"begin\" keyword, then the defun will be recognised.  The
returned point is at the first character of the \"libunit\" keyword."
  (let ((last-forward (point))
	(last-backward
	 ;; Just in case we are actually sitting on the "begin"
	 ;; keyword, allow for the keyword and an extra character,
	 ;; as this will be used when looking forward for the
	 ;; "begin" keyword.
	 (save-excursion (forward-word 1) (1+ (point))))
	foundp literal placeholder)
    ;; Find the "libunit" keyword.
    (while (and (not foundp)
		(re-search-backward vhdl-libunit-re nil 'move))
      ;; If we are in a literal, or not at a real libunit, then try again.
      (if (or (= (preceding-char) ?_)
	      (vhdl-in-literal (point-min))
	      (not (vhdl-libunit-p)))
	  (backward-char)
	;; Find the corresponding "begin" keyword.
	(setq last-forward (point))
	(while (and (not foundp)
		    (re-search-forward "\\bis\\b[^_]" last-backward t)
		    (setq placeholder (match-beginning 0)))
	  (if (or (= (preceding-char) ?_)
		  (setq literal (vhdl-in-literal last-forward)))
	      ;; It wasn't a real keyword, so keep searching.
	      (if (eq literal 'comment)
		  (goto-char
		   (min (vhdl-point 'eol) last-backward))
		(forward-char))
	    ;; We have found the begin keyword, loop will exit.
	    (setq foundp placeholder)))
	;; Go back to the libunit keyword
	(goto-char last-forward)))
    foundp))

(defun vhdl-beginning-of-defun (&optional count)
  "Move backward to the beginning of a VHDL defun.
With argument, do it that many times.
Returns the location of the corresponding begin keyword, unless search
stops due to beginning or end of buffer."
  ;; Note that if point is between the "defun" keyword and the
  ;; corresponding "begin" keyword, then that defun will not be
  ;; recognised, and the search will continue backwards.  If point is
  ;; at the "begin" keyword, then the defun will be recognised.  The
  ;; returned point is at the first character of the "defun" keyword.
  (interactive "p")
  (let ((count (or count 1))
	(case-fold-search t)
	(last-forward (point))
	foundp)
    (while (> count 0)
      (setq foundp nil)
      (goto-char last-forward)
      (let ((last-backward
	     ;; Just in case we are actually sitting on the "begin"
	     ;; keyword, allow for the keyword and an extra character,
	     ;; as this will be used when looking forward for the
	     ;; "begin" keyword.
	     (save-excursion (forward-word 1) (1+ (point))))
	    begin-string literal)
	(while (and (not foundp)
		    (re-search-backward vhdl-defun-re nil 'move))
	  ;; If we are in a literal, then try again.
	  (if (or (= (preceding-char) ?_)
		  (vhdl-in-literal (point-min)))
	      (backward-char)
	    (if (setq begin-string (vhdl-corresponding-defun))
		;; This is a real defun keyword.
		;; Find the corresponding "begin" keyword.
		;; Look for the begin keyword.
		(progn
		  ;; Save the search start point.
		  (setq last-forward (point))
		  (while (and (not foundp)
			      (search-forward begin-string last-backward t))
		    (if (or (= (preceding-char) ?_)
			    (save-match-data
			      (setq literal (vhdl-in-literal last-forward))))
			;; It wasn't a real keyword, so keep searching.
			(if (eq literal 'comment)
			    (goto-char
			     (min (vhdl-point 'eol) last-backward))
			  (forward-char))
		      ;; We have found the begin keyword, loop will exit.
		      (setq foundp (match-beginning 0)))
		    )
		  ;; Go back to the defun keyword
		  (goto-char last-forward)) ; end search for begin keyword
	      ))
	  ) ; end of the search for the defun keyword
	)
      (setq count (1- count))
      )
    (vhdl-keep-region-active)
    foundp))

(defun vhdl-beginning-of-statement (&optional count lim)
  "Go to the beginning of the innermost VHDL statement.
With prefix arg, go back N - 1 statements.  If already at the
beginning of a statement then go to the beginning of the preceding
one.  If within a string or comment, or next to a comment (only
whitespace between), move by sentences instead of statements.

When called from a program, this function takes 2 optional args: the
prefix arg, and a buffer position limit which is the farthest back to
search."
  (interactive "p")
  (let ((count (or count 1))
	(case-fold-search t)
	(lim (or lim (point-min)))
	(here (point))
	state)
    (save-excursion
      (goto-char lim)
      (setq state (parse-partial-sexp (point) here nil nil)))
    (if (and (interactive-p)
	     (or (nth 3 state)
		 (nth 4 state)
		 (looking-at (concat "[ \t]*" comment-start-skip))))
	(forward-sentence (- count))
      (while (> count 0)
	(vhdl-beginning-of-statement-1 lim)
	(setq count (1- count))))
    ;; its possible we've been left up-buf of lim
    (goto-char (max (point) lim))
    )
  (vhdl-keep-region-active))

(defconst vhdl-e-o-s-re
  (concat ";\\|" vhdl-begin-fwd-re "\\|" vhdl-statement-fwd-re))

(defun vhdl-end-of-statement ()
  "Very simple implementation."
  (interactive)
  (re-search-forward vhdl-e-o-s-re))

(defconst vhdl-b-o-s-re
  (concat ";\\|\(\\|\)\\|\\bwhen\\b[^_]\\|"
	  vhdl-begin-bwd-re "\\|" vhdl-statement-bwd-re))

(defun vhdl-beginning-of-statement-1 (&optional lim)
  "Move to the start of the current statement, or the previous
statement if already at the beginning of one."
  (let ((lim (or lim (point-min)))
	(here (point))
	(pos (point))
	donep)
    ;; go backwards one balanced expression, but be careful of
    ;; unbalanced paren being reached
    (if (not (vhdl-safe (progn (backward-sexp) t)))
	(progn
	  (backward-up-list 1)
	  (forward-char)
	  (vhdl-forward-syntactic-ws here)
	  (setq donep t)))
    (while (and (not donep)
		(not (bobp))
		;; look backwards for a statement boundary
		(re-search-backward vhdl-b-o-s-re lim 'move))
      (if (or (= (preceding-char) ?_)
	      (vhdl-in-literal lim))
	  (backward-char)
	(cond
	 ;; If we are looking at an open paren, then stop after it
	 ((eq (following-char) ?\()
	  (forward-char)
	  (vhdl-forward-syntactic-ws here)
	  (setq donep t))
	 ;; If we are looking at a close paren, then skip it
	 ((eq (following-char) ?\))
	  (forward-char)
	  (setq pos (point))
	  (backward-sexp)
	  (if (< (point) lim)
	      (progn (goto-char pos)
		     (vhdl-forward-syntactic-ws here)
		     (setq donep t))))
	 ;; If we are looking at a semicolon, then stop
	 ((eq (following-char) ?\;)
	  (progn
	    (forward-char)
	    (vhdl-forward-syntactic-ws here)
	    (setq donep t)))
	 ;; If we are looking at a "begin", then stop
	 ((and (looking-at vhdl-begin-fwd-re)
	       (/= (preceding-char) ?_)
	       (vhdl-begin-p nil))
	  ;; If it's a leader "begin", then find the
	  ;; right place
	  (if (looking-at vhdl-leader-re)
	      (save-excursion
		;; set a default stop point at the begin
		(setq pos (point))
		;; is the start point inside the leader area ?
		(goto-char (vhdl-end-of-leader))
		(vhdl-forward-syntactic-ws here)
		(if (< (point) here)
		    ;; start point was not inside leader area
		    ;; set stop point at word after leader
		    (setq pos (point))))
	    (forward-word 1)
	    (vhdl-forward-syntactic-ws here)
	    (setq pos (point)))
	  (goto-char pos)
	  (setq donep t))
	 ;; If we are looking at a "statement", then stop
	 ((and (looking-at vhdl-statement-fwd-re)
	       (/= (preceding-char) ?_)
	       (vhdl-statement-p nil))
	  (setq donep t))
	 ;; If we are looking at a case alternative key, then stop
	 ((and (looking-at vhdl-case-alternative-re)
	       (vhdl-case-alternative-p lim))
	  (save-excursion
	    ;; set a default stop point at the when
	    (setq pos (point))
	    ;; is the start point inside the case alternative key ?
	    (looking-at vhdl-case-alternative-re)
	    (goto-char (match-end 0))
	    (vhdl-forward-syntactic-ws here)
	    (if (< (point) here)
		;; start point was not inside the case alternative key
		;; set stop point at word after case alternative keyleader
		(setq pos (point))))
	  (goto-char pos)
	  (setq donep t))
	 ;; Bogus find, continue
	 (t
	  (backward-char)))))
    ))

;; Defuns for calculating the current syntactic state:

(defun vhdl-get-library-unit (bod placeholder)
  "If there is an enclosing library unit at bod, with it's \"begin\"
keyword at placeholder, then return the library unit type."
  (let ((here (vhdl-point 'bol)))
    (if (save-excursion
	  (goto-char placeholder)
	  (vhdl-safe (vhdl-forward-sexp 1 bod))
	  (<= here (point)))
	(save-excursion
	  (goto-char bod)
	  (cond
	   ((looking-at "e") 'entity)
	   ((looking-at "a") 'architecture)
	   ((looking-at "c") 'configuration)
	   ((looking-at "p")
	    (save-excursion
	      (goto-char bod)
	      (forward-sexp)
	      (vhdl-forward-syntactic-ws here)
	      (if (looking-at "body\\b[^_]")
		  'package-body 'package))))))
    ))

(defun vhdl-get-block-state (&optional lim)
  "Finds and records all the closest opens.
lim is the furthest back we need to search (it should be the
previous libunit keyword)."
  (let ((here (point))
	(lim (or lim (point-min)))
	keyword sexp-start sexp-mid sexp-end
	preceding-sexp containing-sexp
	containing-begin containing-mid containing-paren)
    (save-excursion
      ;; Find the containing-paren, and use that as the limit
      (if (setq containing-paren
		(save-restriction
		  (narrow-to-region lim (point))
		  (vhdl-safe (scan-lists (point) -1 1))))
	  (setq lim containing-paren))
      ;; Look backwards for "begin" and "end" keywords.
      (while (and (> (point) lim)
		  (not containing-sexp))
	(setq keyword (vhdl-backward-to-block lim))
	(cond
	 ((eq keyword 'begin)
	  ;; Found a "begin" keyword
	  (setq sexp-start (point))
	  (setq sexp-mid (vhdl-corresponding-mid lim))
	  (setq sexp-end (vhdl-safe
			  (save-excursion
			    (vhdl-forward-sexp 1 lim) (point))))
	  (if (and sexp-end (<= sexp-end here))
	      ;; we want to record this sexp, but we only want to
	      ;; record the last-most of any of them before here
	      (or preceding-sexp
		  (setq preceding-sexp sexp-start))
	    ;; we're contained in this sexp so put sexp-start on
	    ;; front of list
	    (setq containing-sexp sexp-start)
	    (setq containing-mid sexp-mid)
	    (setq containing-begin t)))
	 ((eq keyword 'end)
	  ;; Found an "end" keyword
	  (forward-sexp)
	  (setq sexp-end (point))
	  (setq sexp-mid nil)
	  (setq sexp-start
		(or (vhdl-safe (vhdl-backward-sexp 1 lim) (point))
		    (progn (backward-sexp) (point))))
	  ;; we want to record this sexp, but we only want to
	  ;; record the last-most of any of them before here
	  (or preceding-sexp
	      (setq preceding-sexp sexp-start)))
	 )))
    ;; Check if the containing-paren should be the containing-sexp
    (if (and containing-paren
	     (or (null containing-sexp)
		 (< containing-sexp containing-paren)))
	(setq containing-sexp containing-paren
	      preceding-sexp nil
	      containing-begin nil
	      containing-mid nil))
    (vector containing-sexp preceding-sexp containing-begin containing-mid)
    ))


(defconst vhdl-s-c-a-re
  (concat vhdl-case-alternative-re "\\|" vhdl-case-header-key))

(defun vhdl-skip-case-alternative (&optional lim)
  "Skip forward over case/when bodies, with optional maximal
limit. If no next case alternative is found, nil is returned and point
is not moved."
  (let ((lim (or lim (point-max)))
	(here (point))
	donep foundp)
    (while (and (< (point) lim)
		(not donep))
      (if (and (re-search-forward vhdl-s-c-a-re lim 'move)
	       (save-match-data
		 (not (vhdl-in-literal)))
	       (/= (match-beginning 0) here))
	  (progn
	    (goto-char (match-beginning 0))
	    (cond
	     ((and (looking-at "case")
		   (re-search-forward "\\bis[^_]" lim t))
	      (backward-sexp)
	      (vhdl-forward-sexp))
	     (t
	      (setq donep t
		    foundp t))))))
    (if (not foundp)
	(goto-char here))
    foundp))

(defun vhdl-backward-skip-label (&optional lim)
  "Skip backward over a label, with optional maximal
limit. If label is not found, nil is returned and point
is not moved."
  (let ((lim (or lim (point-min)))
	placeholder)
    (if (save-excursion
	  (vhdl-backward-syntactic-ws lim)
	  (and (eq (preceding-char) ?:)
	       (progn
		 (backward-sexp)
		 (setq placeholder (point))
		 (looking-at vhdl-label-key))))
	(goto-char placeholder))
    ))

(defun vhdl-forward-skip-label (&optional lim)
  "Skip forward over a label, with optional maximal
limit.  If label is not found, nil is returned and point
is not moved."
  (let ((lim (or lim (point-max))))
    (if (looking-at vhdl-label-key)
	(progn
	  (goto-char (match-end 0))
	  (vhdl-forward-syntactic-ws lim)))
    ))

(defun vhdl-get-syntactic-context ()
  "Guess the syntactic description of the current line of VHDL code."
  (save-excursion
    (save-restriction
      (beginning-of-line)
      (let* ((indent-point (point))
	     (case-fold-search t)
	     vec literal containing-sexp preceding-sexp
	     containing-begin containing-mid containing-leader
	     char-before-ip char-after-ip begin-after-ip end-after-ip
	     placeholder lim library-unit
	    )

	;; Reset the syntactic context
	(setq vhdl-syntactic-context nil)

	(save-excursion
	  ;; Move to the start of the previous library unit, and
	  ;; record the position of the "begin" keyword.
	  (setq placeholder (vhdl-beginning-of-libunit))
	  ;; The position of the "libunit" keyword gives us a gross
	  ;; limit point.
	  (setq lim (point))
	  )

	;; If there is a previous library unit, and we are enclosed by
	;; it, then set the syntax accordingly.
	(and placeholder
	     (setq library-unit (vhdl-get-library-unit lim placeholder))
	     (vhdl-add-syntax library-unit lim))

	;; Find the surrounding state.
	(if (setq vec (vhdl-get-block-state lim))
	    (progn
	      (setq containing-sexp (aref vec 0))
	      (setq preceding-sexp (aref vec 1))
	      (setq containing-begin (aref vec 2))
	      (setq containing-mid (aref vec 3))
	      ))

	;; set the limit on the farthest back we need to search
	(setq lim (if containing-sexp
		      (save-excursion
			(goto-char containing-sexp)
			;; set containing-leader if required
			(if (looking-at vhdl-leader-re)
			    (setq containing-leader (vhdl-end-of-leader)))
			(vhdl-point 'bol))
		    (point-min)))

	;; cache char before and after indent point, and move point to
	;; the most likely position to perform the majority of tests
	(goto-char indent-point)
	(skip-chars-forward " \t")
	(setq literal (vhdl-in-literal lim))
	(setq char-after-ip (following-char))
	(setq begin-after-ip (and
			      (not literal)
			      (looking-at vhdl-begin-fwd-re)
			      (vhdl-begin-p)))
	(setq end-after-ip (and
			    (not literal)
			    (looking-at vhdl-end-fwd-re)
			    (vhdl-end-p)))
	(vhdl-backward-syntactic-ws lim)
	(setq char-before-ip (preceding-char))
	(goto-char indent-point)
	(skip-chars-forward " \t")

	;; now figure out syntactic qualities of the current line
	(cond
	 ;; CASE 1: in a string or comment.
	 ((memq literal '(string comment))
	  (vhdl-add-syntax literal (vhdl-point 'bopl)))
	 ;; CASE 2: Line is at top level.
	 ((null containing-sexp)
	  ;; Find the point to which indentation will be relative
	  (save-excursion
	    (if (null preceding-sexp)
		;; CASE 2X.1
		;; no preceding-sexp -> use the preceding statement
		(vhdl-beginning-of-statement-1 lim)
	      ;; CASE 2X.2
	      ;; if there is a preceding-sexp then indent relative to it
	      (goto-char preceding-sexp)
	      ;; if not at boi, then the block-opening keyword is
	      ;; probably following a label, so we need a different
	      ;; relpos
	      (if (/= (point) (vhdl-point 'boi))
		  ;; CASE 2X.3
		  (vhdl-beginning-of-statement-1 lim)))
	    ;; v-b-o-s could have left us at point-min
	    (and (bobp)
		 ;; CASE 2X.4
		 (vhdl-forward-syntactic-ws indent-point))
	    (setq placeholder (point)))
	  (cond
	   ;; CASE 2A : we are looking at a block-open
	   (begin-after-ip
	    (vhdl-add-syntax 'block-open placeholder))
	   ;; CASE 2B: we are looking at a block-close
	   (end-after-ip
	    (vhdl-add-syntax 'block-close placeholder))
	   ;; CASE 2C: we are looking at a top-level statement
	   ((progn
	      (vhdl-backward-syntactic-ws lim)
	      (or (bobp)
		  (= (preceding-char) ?\;)))
	    (vhdl-add-syntax 'statement placeholder))
	   ;; CASE 2D: we are looking at a top-level statement-cont
	   (t
	    (vhdl-beginning-of-statement-1 lim)
	    ;; v-b-o-s could have left us at point-min
	    (and (bobp)
		 ;; CASE 2D.1
		 (vhdl-forward-syntactic-ws indent-point))
	    (vhdl-add-syntax 'statement-cont (point)))
	   )) ; end CASE 2
	 ;; CASE 3: line is inside parentheses.  Most likely we are
	 ;; either in a subprogram argument (interface) list, or a
	 ;; continued expression containing parentheses.
	 ((null containing-begin)
	  (vhdl-backward-syntactic-ws containing-sexp)
	  (cond
	   ;; CASE 3A: we are looking at the arglist closing paren
	   ((eq char-after-ip ?\))
	    (goto-char containing-sexp)
	    (vhdl-add-syntax 'arglist-close (vhdl-point 'boi)))
	   ;; CASE 3B: we are looking at the first argument in an empty
	   ;; argument list.
	   ((eq char-before-ip ?\()
	    (goto-char containing-sexp)
	    (vhdl-add-syntax 'arglist-intro (vhdl-point 'boi)))
	   ;; CASE 3C: we are looking at an arglist continuation line,
	   ;; but the preceding argument is on the same line as the
	   ;; opening paren.  This case includes multi-line
	   ;; expression paren groupings.
	   ((and (save-excursion
		   (goto-char (1+ containing-sexp))
		   (skip-chars-forward " \t")
		   (not (eolp))
		   (not (looking-at "--")))
		 (save-excursion
		   (vhdl-beginning-of-statement-1 containing-sexp)
		   (skip-chars-backward " \t(")
		   (<= (point) containing-sexp)))
	    (goto-char containing-sexp)
	    (vhdl-add-syntax 'arglist-cont-nonempty (vhdl-point 'boi)))
	   ;; CASE 3D: we are looking at just a normal arglist
	   ;; continuation line
	   (t (vhdl-beginning-of-statement-1 containing-sexp)
	      (vhdl-forward-syntactic-ws indent-point)
	      (vhdl-add-syntax 'arglist-cont (vhdl-point 'boi)))
	   ))
	 ;; CASE 4: A block mid open
	 ((and begin-after-ip
	       (looking-at containing-mid))
	  (goto-char containing-sexp)
	  ;; If the \"begin\" keyword is a trailer, then find v-b-o-s
	  (if (looking-at vhdl-trailer-re)
	      ;; CASE 4.1
	      (progn (forward-sexp) (vhdl-beginning-of-statement-1 nil)))
	  (vhdl-backward-skip-label (vhdl-point 'boi))
	  (vhdl-add-syntax 'block-open (point)))
	 ;; CASE 5: block close brace
	 (end-after-ip
	  (goto-char containing-sexp)
	  ;; If the \"begin\" keyword is a trailer, then find v-b-o-s
	  (if (looking-at vhdl-trailer-re)
	      ;; CASE 5.1
	      (progn (forward-sexp) (vhdl-beginning-of-statement-1 nil)))
	  (vhdl-backward-skip-label (vhdl-point 'boi))
	  (vhdl-add-syntax 'block-close (point)))
	 ;; CASE 6: A continued statement
	 ((and (/= char-before-ip ?\;)
	       ;; check it's not a trailer begin keyword, or a begin
	       ;; keyword immediately following a label.
	       (not (and begin-after-ip
			 (or (looking-at vhdl-trailer-re)
			     (save-excursion
			       (vhdl-backward-skip-label containing-sexp)))))
	       ;; check it's not a statement keyword
	       (not (and (looking-at vhdl-statement-fwd-re)
			 (vhdl-statement-p)))
	       ;; see if the b-o-s is before the indent point
	       (> indent-point
		  (save-excursion
		    (vhdl-beginning-of-statement-1 containing-sexp)
		    ;; If we ended up after a leader, then this will
		    ;; move us forward to the start of the first
		    ;; statement.  Note that a containing sexp here is
		    ;; always a keyword, not a paren, so this will
		    ;; have no effect if we hit the containing-sexp.
		    (vhdl-forward-syntactic-ws indent-point)
		    (setq placeholder (point))))
	       ;; check it's not a block-intro
	       (/= placeholder containing-sexp)
	       ;; check it's not a case block-intro
	       (save-excursion
		 (goto-char placeholder)
		 (or (not (looking-at vhdl-case-alternative-re))
		     (> (match-end 0) indent-point))))
	  ;; Make placeholder skip a label, but only if it puts us
	  ;; before the indent point at the start of a line.
	  (let ((new placeholder))
	    (if (and (> indent-point
			(save-excursion
			  (goto-char placeholder)
			  (vhdl-forward-skip-label indent-point)
			  (setq new (point))))
		     (save-excursion
		       (goto-char new)
		       (eq new (progn (back-to-indentation) (point)))))
		(setq placeholder new)))
	  (vhdl-add-syntax 'statement-cont placeholder)
	  (if begin-after-ip
	      (vhdl-add-syntax 'block-open)))
	 ;; Statement. But what kind?
	 ;; CASE 7: A case alternative key
	 ((and (looking-at vhdl-case-alternative-re)
	       (vhdl-case-alternative-p containing-sexp))
	  ;; for a case alternative key, we set relpos to the first
	  ;; non-whitespace char on the line containing the "case"
	  ;; keyword.
	  (goto-char containing-sexp)
	  ;; If the \"begin\" keyword is a trailer, then find v-b-o-s
	  (if (looking-at vhdl-trailer-re)
	      (progn (forward-sexp) (vhdl-beginning-of-statement-1 nil)))
	  (vhdl-add-syntax 'case-alternative (vhdl-point 'boi)))
	 ;; CASE 8: statement catchall
	 (t
	  ;; we know its a statement, but we need to find out if it is
	  ;; the first statement in a block
	  (if containing-leader
	      (goto-char containing-leader)
	    (goto-char containing-sexp)
	    ;; Note that a containing sexp here is always a keyword,
	    ;; not a paren, so skip over the keyword.
	    (forward-sexp))
	  ;; move to the start of the first statement
	  (vhdl-forward-syntactic-ws indent-point)
	  (setq placeholder (point))
	  ;; we want to ignore case alternatives keys when skipping forward
	  (let (incase-p)
	    (while (looking-at vhdl-case-alternative-re)
	      (setq incase-p (point))
	      ;; we also want to skip over the body of the
	      ;; case/when statement if that doesn't put us at
	      ;; after the indent-point
	      (while (vhdl-skip-case-alternative indent-point))
	      ;; set up the match end
	      (looking-at vhdl-case-alternative-re)
	      (goto-char (match-end 0))
	      ;; move to the start of the first case alternative statement
	      (vhdl-forward-syntactic-ws indent-point)
	      (setq placeholder (point)))
	    (cond
	     ;; CASE 8A: we saw a case/when statement so we must be
	     ;; in a switch statement.  find out if we are at the
	     ;; statement just after a case alternative key
	     ((and incase-p
		   (= (point) indent-point))
	      ;; relpos is the "when" keyword
	      (vhdl-add-syntax 'statement-case-intro incase-p))
	     ;; CASE 8B: any old statement
	     ((< (point) indent-point)
	      ;; relpos is the first statement of the block
	      (vhdl-add-syntax 'statement placeholder)
	      (if begin-after-ip
		  (vhdl-add-syntax 'block-open)))
	     ;; CASE 8C: first statement in a block
	     (t
	      (goto-char containing-sexp)
	      ;; If the \"begin\" keyword is a trailer, then find v-b-o-s
	      (if (looking-at vhdl-trailer-re)
		  (progn (forward-sexp) (vhdl-beginning-of-statement-1 nil)))
	      (vhdl-backward-skip-label (vhdl-point 'boi))
	      (vhdl-add-syntax 'statement-block-intro (point))
	      (if begin-after-ip
		  (vhdl-add-syntax 'block-open)))
	     )))
	 )

	;; now we need to look at any modifiers
	(goto-char indent-point)
	(skip-chars-forward " \t")
	(if (looking-at "--")
	    (vhdl-add-syntax 'comment))
	;; return the syntax
	vhdl-syntactic-context))))

;; Standard indentation line-ups:

(defun vhdl-lineup-arglist (langelem)
  "Lineup the current arglist line with the arglist appearing just
after the containing paren which starts the arglist."
  (save-excursion
    (let* ((containing-sexp
	    (save-excursion
	      ;; arglist-cont-nonempty gives relpos ==
	      ;; to boi of containing-sexp paren. This
	      ;; is good when offset is +, but bad
	      ;; when it is vhdl-lineup-arglist, so we
	      ;; have to special case a kludge here.
	      (if (memq (car langelem) '(arglist-intro arglist-cont-nonempty))
		  (progn
		    (beginning-of-line)
		    (backward-up-list 1)
		    (skip-chars-forward " \t" (vhdl-point 'eol)))
		(goto-char (cdr langelem)))
	      (point)))
	   (cs-curcol (save-excursion
			(goto-char (cdr langelem))
			(current-column))))
      (if (save-excursion
	    (beginning-of-line)
	    (looking-at "[ \t]*)"))
	  (progn (goto-char (match-end 0))
		 (backward-sexp)
		 (forward-char)
		 (vhdl-forward-syntactic-ws)
		 (- (current-column) cs-curcol))
	(goto-char containing-sexp)
	(or (eolp)
	    (let ((eol (vhdl-point 'eol))
		  (here (progn
			  (forward-char)
			  (skip-chars-forward " \t")
			  (point))))
	      (vhdl-forward-syntactic-ws)
	      (if (< (point) eol)
		  (goto-char here))))
	(- (current-column) cs-curcol)
	))))

(defun vhdl-lineup-arglist-intro (langelem)
  "Lineup an arglist-intro line to just after the open paren."
  (save-excursion
    (let ((cs-curcol (save-excursion
		       (goto-char (cdr langelem))
		       (current-column)))
	  (ce-curcol (save-excursion
		       (beginning-of-line)
		       (backward-up-list 1)
		       (skip-chars-forward " \t" (vhdl-point 'eol))
		       (current-column))))
      (- ce-curcol cs-curcol -1))))

(defun vhdl-lineup-comment (langelem)
  "Support old behavior for comment indentation.  We look at
vhdl-comment-only-line-offset to decide how to indent comment
only-lines."
  (save-excursion
    (back-to-indentation)
    ;; at or to the right of comment-column
    (if (>= (current-column) comment-column)
	(vhdl-comment-indent)
      ;; otherwise, indent as specified by vhdl-comment-only-line-offset
      (if (not (bolp))
	  (or (car-safe vhdl-comment-only-line-offset)
	      vhdl-comment-only-line-offset)
	(or (cdr-safe vhdl-comment-only-line-offset)
	    (car-safe vhdl-comment-only-line-offset)
	    -1000                       ;jam it against the left side
	    )))))

(defun vhdl-lineup-statement-cont (langelem)
  "Line up statement-cont after the assignment operator."
  (save-excursion
    (let* ((relpos (cdr langelem))
	   (assignp (save-excursion
		     (goto-char (vhdl-point 'boi))
		     (and (re-search-forward "\\(<\\|:\\)="
					     (vhdl-point 'eol) t)
			  (- (point) (vhdl-point 'boi)))))
	   (curcol (progn
		     (goto-char relpos)
		     (current-column)))
	   foundp)
      (while (and (not foundp)
		  (< (point) (vhdl-point 'eol)))
	(re-search-forward "\\(<\\|:\\)=\\|(" (vhdl-point 'eol) 'move)
	(if (vhdl-in-literal (cdr langelem))
	    (forward-char)
	  (if (= (preceding-char) ?\()
	      ;; skip over any parenthesized expressions
	      (goto-char (min (vhdl-point 'eol)
			      (scan-lists (point) 1 1)))
	    ;; found an assignment operator (not at eol)
	    (setq foundp (not (looking-at "\\s-*$"))))))
      (if (not foundp)
	  ;; there's no assignment operator on the line
	  vhdl-basic-offset
	;; calculate indentation column after assign and ws, unless
	;; our line contains an assignment operator
	(if (not assignp)
	    (progn
	      (forward-char)
	      (skip-chars-forward " \t")
	      (setq assignp 0)))
	(- (current-column) assignp curcol))
      )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Progress reporting

(defvar vhdl-progress-info nil
  "Array variable for progress information: 0 begin, 1 end, 2 time.")

(defsubst vhdl-update-progress-info (string pos)
  "Update progress information."
  (when (and vhdl-progress-info (not noninteractive)
	     (< vhdl-progress-interval
		(- (nth 1 (current-time)) (aref vhdl-progress-info 2))))
    (message (concat string "... (%2d%s)")
	     (/ (* 100 (- pos (aref vhdl-progress-info 0)))
		(- (aref vhdl-progress-info 1)
		   (aref vhdl-progress-info 0))) "%")
    (aset vhdl-progress-info 2 (nth 1 (current-time)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Indentation commands

(defsubst vhdl-in-comment-p ()
  "Check if point is to right of beginning comment delimiter."
  (let ((position (point)))
    (save-excursion ; finds an unquoted comment
      (save-match-data
	(beginning-of-line)
	(re-search-forward "^\\([^\"]*\"[^\"]*\"\\)*[^\"]*--" position t)))))

(defsubst vhdl-in-string-p ()
  "Check if point is in a string."
  (let ((position (point)))
    (save-excursion ; preceeded by odd number of string delimiters?
      (save-match-data
	(beginning-of-line)
	(eq position (re-search-forward "^\\([^\"]*\"[^\"]*\"\\)*[^\"]*\"[^\"]*"
					position t))))))

(defsubst vhdl-in-comment-or-string-p ()
  "Check if point is in a comment or a string."
  (or (vhdl-in-comment-p)
       (vhdl-in-string-p)))

(defun vhdl-electric-tab (&optional prefix-arg)
  "If preceeding character is part of a word or a paren then hippie-expand,
else if right of non whitespace on line then tab-to-tab-stop,
else if last command was a tab or return then dedent one step or if a comment
toggle between normal indent and inline comment indent,
else indent `correctly'."
  (interactive "*P")
  (vhdl-prepare-search-2
   (cond
    ;; expand word
    ((= (char-syntax (preceding-char)) ?w)
     (let ((case-fold-search (not vhdl-word-completion-case-sensitive))
	   (case-replace nil)
	   (hippie-expand-only-buffers
	    (or (and (boundp 'hippie-expand-only-buffers)
		     hippie-expand-only-buffers)
		'(vhdl-mode))))
       (vhdl-expand-abbrev prefix-arg)))
    ;; expand parenthesis
    ((or (= (preceding-char) ?\() (= (preceding-char) ?\)))
     (let ((case-fold-search (not vhdl-word-completion-case-sensitive))
	   (case-replace nil))
       (vhdl-expand-paren prefix-arg)))
    ;; insert tab
    ((> (current-column) (current-indentation))
     (tab-to-tab-stop))
    ;; toggle comment indent
    ((and (looking-at "--")
	  (or (eq last-command 'vhdl-electric-tab)
	      (eq last-command 'vhdl-electric-return)))
     (cond ((= (current-indentation) 0) ; no indent
	    (indent-to 1)
	    (indent-according-to-mode))
	   ((< (current-indentation) comment-column) ; normal indent
	    (indent-to comment-column)
	    (indent-according-to-mode))
	   (t				; inline comment indent
	    (kill-line -0))))
    ;; dedent
    ((and (>= (current-indentation) vhdl-basic-offset)
	  (or (eq last-command 'vhdl-electric-tab)
	      (eq last-command 'vhdl-electric-return)))
     (backward-delete-char-untabify vhdl-basic-offset nil))
    ;; indent line
    (t (indent-according-to-mode)))
   (setq this-command 'vhdl-electric-tab)))

(defun vhdl-electric-return ()
  "newline-and-indent or indent-new-comment-line if in comment and preceding
character is a space."
  (interactive)
  (if (and (= (preceding-char) ? ) (vhdl-in-comment-p))
      (indent-new-comment-line)
    (newline-and-indent)))

(defun vhdl-indent-line ()
  "Indent the current line as VHDL code.  Returns the amount of
indentation change."
  (interactive)
  (let* ((syntax (and vhdl-indent-syntax-based (vhdl-get-syntactic-context)))
	 (pos (- (point-max) (point)))
	 (indent
	  (if syntax
	      ;; indent syntax-based
	      (if (and (eq (caar syntax) 'comment)
		       (>= (vhdl-get-offset (car syntax)) comment-column))
		  ;; special case: comments at or right of comment-column
		  (vhdl-get-offset (car syntax))
		(apply '+ (mapcar 'vhdl-get-offset syntax)))
	    ;; indent like previous nonblank line
	    (save-excursion (beginning-of-line)
			    (re-search-backward "^[^\n]" nil t)
			    (current-indentation))))
	 (shift-amt  (- indent (current-indentation))))
    (and vhdl-echo-syntactic-information-p
	 (message "syntax: %s, indent= %d" syntax indent))
    (unless (zerop shift-amt)
      (delete-region (vhdl-point 'bol) (vhdl-point 'boi))
      (beginning-of-line)
      (indent-to indent))
    (if (< (point) (vhdl-point 'boi))
	(back-to-indentation)
      ;; If initial point was within line's indentation, position after
      ;; the indentation.  Else stay at same point in text.
      (when (> (- (point-max) pos) (point))
	(goto-char (- (point-max) pos))))
    (run-hooks 'vhdl-special-indent-hook)
    (vhdl-update-progress-info "Indenting" (vhdl-current-line))
    shift-amt))

(defun vhdl-indent-region (beg end column)
  "Indent region as VHDL code.
Adds progress reporting to `indent-region'."
  (interactive "r\nP")
  (when vhdl-progress-interval
    (setq vhdl-progress-info (vector (count-lines (point-min) beg)
				     (count-lines (point-min) end) 0)))
  (indent-region beg end column)
  (when vhdl-progress-interval (message "Indenting...done"))
  (setq vhdl-progress-info nil))

(defun vhdl-indent-buffer ()
  "Indent whole buffer as VHDL code.
Calls `indent-region' for whole buffer and adds progress reporting."
  (interactive)
  (vhdl-indent-region (point-min) (point-max) nil))

(defun vhdl-indent-group ()
  "Indent group of lines between empty lines."
  (interactive)
  (let ((beg (save-excursion
	       (if (re-search-backward vhdl-align-group-separate nil t)
		   (point-marker)
		 (point-min-marker))))
	(end (save-excursion
	       (if (re-search-forward vhdl-align-group-separate nil t)
		   (point-marker)
		 (point-max-marker)))))
    (vhdl-indent-region beg end nil)))

(defun vhdl-indent-sexp (&optional endpos)
  "Indent each line of the list starting just after point.
If optional arg ENDPOS is given, indent each line, stopping when
ENDPOS is encountered."
  (interactive)
  (save-excursion
    (let ((beg (point))
	  (end (progn (vhdl-forward-sexp nil endpos) (point))))
      (indent-region beg end nil))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Miscellaneous commands

(defun vhdl-show-syntactic-information ()
  "Show syntactic information for current line."
  (interactive)
  (message "Syntactic analysis: %s" (vhdl-get-syntactic-context))
  (vhdl-keep-region-active))

;; Verification and regression functions:

(defun vhdl-regress-line (&optional arg)
  "Check syntactic information for current line."
  (interactive "P")
  (let ((expected (save-excursion
		    (end-of-line)
		    (when (search-backward " -- ((" (vhdl-point 'bol) t)
		      (forward-char 4)
		      (read (current-buffer)))))
	(actual (vhdl-get-syntactic-context))
	(expurgated))
    ;; remove the library unit symbols
    (mapcar
     (function
      (lambda (elt)
	(if (memq (car elt) '(entity configuration package
				     package-body architecture))
	    nil
	  (setq expurgated (append expurgated (list elt))))))
     actual)
    (if (and (not arg) expected (listp expected))
	(if (not (equal expected expurgated))
	    (error "Should be: %s, is: %s" expected expurgated))
      (save-excursion
	(beginning-of-line)
	(when (not (looking-at "^\\s-*\\(--.*\\)?$"))
	  (end-of-line)
	  (if (search-backward " -- ((" (vhdl-point 'bol) t)
	      (kill-line))
	  (insert " -- ")
	  (insert (format "%s" expurgated))))))
  (vhdl-keep-region-active))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Alignment, whitespace fixup, beautifying
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defconst vhdl-align-alist
  '(
    ;; after some keywords
    (vhdl-mode "^\\s-*\\(constant\\|quantity\\|signal\\|subtype\\|terminal\\|type\\|variable\\)[ \t]"
	       "^\\s-*\\(constant\\|quantity\\|signal\\|subtype\\|terminal\\|type\\|variable\\)\\([ \t]+\\)" 2)
    ;; before ':'
    (vhdl-mode ":[^=]" "\\([ \t]*\\):[^=]")
    ;; after direction specifications
    (vhdl-mode ":[ \t]*\\(in\\|out\\|inout\\|buffer\\|\\)\\>"
	       ":[ \t]*\\(in\\|out\\|inout\\|buffer\\|\\)\\([ \t]+\\)" 2)
    ;; before "==", ":=", "=>", and "<="
    (vhdl-mode "[<:=]=" "\\([ \t]*\\)[<:=]=" 1) ; since "<= ... =>" can occur
    (vhdl-mode "=>" "\\([ \t]*\\)=>" 1)
    (vhdl-mode "[<:=]=" "\\([ \t]*\\)[<:=]=" 1) ; since "=> ... <=" can occur
    ;; before some keywords
    (vhdl-mode "[ \t]after\\>" "[^ \t]\\([ \t]+\\)after\\>" 1)
    (vhdl-mode "[ \t]when\\>" "[^ \t]\\([ \t]+\\)when\\>" 1)
    (vhdl-mode "[ \t]else\\>" "[^ \t]\\([ \t]+\\)else\\>" 1)
    )
  "The format of this alist is (MODES [or MODE] REGEXP ALIGN-PATTERN SUBEXP).
It is searched in order.  If REGEXP is found anywhere in the first
line of a region to be aligned, ALIGN-PATTERN will be used for that
region.  ALIGN-PATTERN must include the whitespace to be expanded or
contracted.  It may also provide regexps for the text surrounding the
whitespace.  SUBEXP specifies which sub-expression of
ALIGN-PATTERN matches the white space to be expanded/contracted.")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Align code

(defvar vhdl-align-try-all-clauses t
  "If REGEXP is not found on the first line of the region that clause
is ignored.  If this variable is non-nil, then the clause is tried anyway.")

(defun vhdl-align-region-1 (begin end &optional spacing alignment-list indent)
  "Attempt to align a range of lines based on the content of the
lines.  The definition of `alignment-list' determines the matching
order and the manner in which the lines are aligned.  If ALIGNMENT-LIST
is not specified `vhdl-align-alist' is used.  If INDENT is non-nil,
indentation is done before aligning."
  (interactive "r\np")
  (setq alignment-list (or alignment-list vhdl-align-alist))
  (setq spacing (or spacing 1))
  (save-excursion
    (let (bol indent)
      (goto-char end)
      (setq end (point-marker))
      (goto-char begin)
      (setq bol (setq begin (progn (beginning-of-line) (point))))
;      (untabify bol end)
      (when indent
	(indent-region bol end nil))))
  (let ((copy (copy-alist alignment-list)))
    (vhdl-prepare-search-2
     (while copy
       (save-excursion
	 (goto-char begin)
	 (let (element
	       (eol (save-excursion (progn (end-of-line) (point)))))
	   (setq element (nth 0 copy))
	   (when (and (or (and (listp (car element))
			       (memq major-mode (car element)))
			  (eq major-mode (car element)))
		      (or vhdl-align-try-all-clauses
			  (re-search-forward (car (cdr element)) eol t)))
	     (vhdl-align-region-2 begin end (car (cdr (cdr element)))
				  (car (cdr (cdr (cdr element)))) spacing))
	   (setq copy (cdr copy))))))))

(defun vhdl-align-region-2 (begin end match &optional substr spacing)
  "Align a range of lines from BEGIN to END.  The regular expression
MATCH must match exactly one fields: the whitespace to be
contracted/expanded.  The alignment column will equal the
rightmost column of the widest whitespace block. SPACING is
the amount of extra spaces to add to the calculated maximum required.
SPACING defaults to 1 so that at least one space is inserted after
the token in MATCH."
  (setq spacing (or spacing 1))
  (setq substr (or substr 1))
  (save-excursion
    (let (distance (max 0) (lines 0) bol eol width)
      ;; Determine the greatest whitespace distance to the alignment
      ;; character
      (goto-char begin)
      (setq eol (progn (end-of-line) (point))
	    bol (setq begin (progn (beginning-of-line) (point))))
      (while (< bol end)
	(save-excursion
	  (when (and (re-search-forward match eol t)
		     (not (vhdl-in-comment-or-string-p)))
	    (setq distance (- (match-beginning substr) bol))
	    (when (> distance max)
	      (setq max distance))))
	(forward-line)
	(setq bol (point)
	      eol (save-excursion (end-of-line) (point)))
	(setq lines (1+ lines)))
      ;; Now insert enough maxs to push each assignment operator to
      ;; the same column.  We need to use 'lines' as a counter, since
      ;; the location of the mark may change
      (goto-char (setq bol begin))
      (setq eol (save-excursion (end-of-line) (point)))
      (while (> lines 0)
  	(when (and (re-search-forward match eol t)
		   (not (vhdl-in-comment-or-string-p)))
	  (setq width (- (match-end substr) (match-beginning substr)))
	  (setq distance (- (match-beginning substr) bol))
	  (goto-char (match-beginning substr))
	  (delete-char width)
	  (insert-char ?  (+ (- max distance) spacing)))
	(beginning-of-line)
	(forward-line)
	(setq bol (point)
	      eol (save-excursion (end-of-line) (point)))
	(setq lines (1- lines))))))

(defun vhdl-align-region-groups (beg end &optional spacing
				     no-message no-comments)
  "Align region, treat groups of lines separately."
  (interactive "r\nP")
  (save-excursion
    (let (pos)
      (goto-char beg)
      (beginning-of-line)
      (setq beg (point))
      (goto-char end)
      (setq end (point-marker))
      (untabify beg end)
      (unless no-message
	(when vhdl-progress-interval
	  (setq vhdl-progress-info (vector (count-lines (point-min) beg)
					   (count-lines (point-min) end) 0))))
      (vhdl-fixup-whitespace-region beg end t)
      (goto-char beg)
      (if (not vhdl-align-groups)
	  ;; align entire region
	  (progn (vhdl-align-region-1 beg end spacing)
		 (unless no-comments
		   (vhdl-align-inline-comment-region-1 beg end)))
	;; align groups
	(while (and (< beg end)
		    (re-search-forward vhdl-align-group-separate end t))
	  (setq pos (point-marker))
	  (vhdl-align-region-1 beg pos spacing)
	  (unless no-comments (vhdl-align-inline-comment-region-1 beg pos))
	  (vhdl-update-progress-info "Aligning" (vhdl-current-line))
	  (setq beg (1+ pos))
	  (goto-char beg))
	;; align last group
	(when (< beg end)
	  (vhdl-align-region-1 beg end spacing)
	  (unless no-comments (vhdl-align-inline-comment-region-1 beg end))
	  (vhdl-update-progress-info "Aligning" (vhdl-current-line))))
      (unless no-message
	(when vhdl-progress-interval (message "Aligning...done"))
	(setq vhdl-progress-info nil)))))

(defun vhdl-align-region (beg end &optional spacing)
  "Align region, treat blocks with same indent and argument lists separately."
  (interactive "r\nP")
  (if (not vhdl-align-same-indent)
      ;; align entire region
      (vhdl-align-region-groups beg end spacing)
    ;; align blocks with same indent and argument lists
    (save-excursion
      (let ((cur-beg beg)
	    indent cur-end)
	(when vhdl-progress-interval
	  (setq vhdl-progress-info (vector (count-lines (point-min) beg)
					   (count-lines (point-min) end) 0)))
	(goto-char end)
	(setq end (point-marker))
	(goto-char cur-beg)
	(while (< (point) end)
	  ;; is argument list opening?
	  (if (setq cur-beg (nth 1 (save-excursion (parse-partial-sexp
						(point) (vhdl-point 'eol)))))
	      ;; determine region for argument list
	      (progn (goto-char cur-beg)
		     (forward-sexp)
		     (setq cur-end (point))
		     (beginning-of-line 2))
	    ;; determine region with same indent
	    (setq indent (current-indentation))
	    (setq cur-beg (point))
	    (setq cur-end (vhdl-point 'bonl))
	    (beginning-of-line 2)
	    (while (and (< (point) end)
			(or (looking-at "^\\s-*\\(--.*\\)?$")
			    (= (current-indentation) indent))
			(<= (save-excursion
			      (nth 0 (parse-partial-sexp
				      (point) (vhdl-point 'eol)))) 0))
	      (unless (looking-at "^\\s-*$")
		(setq cur-end (vhdl-point 'bonl)))
	      (beginning-of-line 2)))
	  ;; align region
	  (vhdl-align-region-groups cur-beg cur-end spacing t t))
	(vhdl-align-inline-comment-region beg end spacing noninteractive)
	(when vhdl-progress-interval (message "Aligning...done"))
	(setq vhdl-progress-info nil)))))

(defun vhdl-align-group (&optional spacing)
  "Align group of lines between empty lines."
  (interactive)
  (let ((beg (save-excursion
	       (if (re-search-backward vhdl-align-group-separate nil t)
		   (point-marker)
		 (point-min-marker))))
	(end (save-excursion
	       (if (re-search-forward vhdl-align-group-separate nil t)
		   (point-marker)
		 (point-max-marker)))))
    (vhdl-align-region beg end spacing)))

(defun vhdl-align-same-indent (&optional spacing)
  "Align block of lines with same indent."
  (interactive)
  (let ((indent (current-indentation))
	beg end)
    ;; search for first line with same indent
    (save-excursion
      (while (and (not (bobp))
		  (or (looking-at "^\\s-*\\(--.*\\)?$")
		      (= (current-indentation) indent)))
	(setq beg (point))
	(beginning-of-line -0)))
    ;; search for last line with same indent
    (save-excursion
      (while (and (not (eobp))
		  (or (looking-at "^\\s-*\\(--.*\\)?$")
		      (= (current-indentation) indent)))
	(beginning-of-line 2)
	(setq end (point))))
    (vhdl-align-region-groups beg end spacing)))

(defun vhdl-align-list (&optional spacing)
  "Align the lines of a list surrounded by a balanced group of parentheses."
  (interactive)
  (let (beg end)
    (save-excursion
      ;; search for beginning of balanced group of parentheses
      (setq beg (re-search-backward "[()]" nil t))
      (while (looking-at ")")
	(forward-char) (backward-sexp)
	(setq beg (re-search-backward "[()]" nil t)))
      ;; search for end of balanced group of parentheses
      (when beg
	(forward-list)
	(setq end (point))))
    (if beg
	(vhdl-align-region-groups beg end spacing)
      (error "Not within a list enclosed by a pair of parentheses"))))

(defun vhdl-align-declarations (&optional spacing)
  "Align the lines within the declarative part of a design unit."
  (interactive)
  (let (beg end)
    (vhdl-prepare-search-2
     (save-excursion
       ;; search for declarative part
       (when (and (re-search-backward "^\\(architecture\\|begin\\|configuration\\|end\\|entity\\|package\\)\\>" nil t)
		  (not (member (upcase (match-string 1)) '("BEGIN" "END"))))
	 (setq beg (point))
	 (re-search-forward "^\\(begin\\|end\\)\\>" nil t)
	 (setq end (point)))))
    (if beg
	(vhdl-align-region-groups beg end spacing)
      (error "Not within the declarative part of a design unit"))))

(defun vhdl-align-buffer ()
  "Align buffer."
  (interactive)
  (vhdl-align-region (point-min) (point-max)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Align inline comments

(defun vhdl-align-inline-comment-region-1 (beg end &optional spacing)
  "Align inline comments in region."
  (save-excursion
    (let ((start-max comment-column)
	  (length-max 0)
	  comment-list start-list tmp-list start length
	  cur-start prev-start no-code)
      (setq spacing (or spacing 2))
      (vhdl-prepare-search-2
       (goto-char beg)
       ;; search for comment start positions and lengths
       (while (< (point) end)
	 (when (and (not (looking-at "^\\s-*\\(begin\\|end\\)\\>"))
		    (looking-at "^\\(.*[^ \t\n-]+\\)\\s-*\\(--.*\\)$")
		    (not (save-excursion (goto-char (match-beginning 2))
					 (vhdl-in-literal))))
	   (setq start (+ (- (match-end 1) (match-beginning 1)) spacing))
	   (setq length (- (match-end 2) (match-beginning 2)))
	   (setq start-max (max start start-max))
	   (setq length-max (max length length-max))
	   (setq comment-list (cons (cons start length) comment-list)))
	 (beginning-of-line 2))
       (setq comment-list
	     (sort comment-list (function (lambda (a b) (> (car a) (car b))))))
       ;; reduce start positions
       (setq start-list (list (caar comment-list)))
       (setq comment-list (cdr comment-list))
       (while comment-list
	 (unless (or (= (caar comment-list) (car start-list))
		     (<= (+ (car start-list) (cdar comment-list))
			    end-comment-column))
	   (setq start-list (cons (caar comment-list) start-list)))
	 (setq comment-list (cdr comment-list)))
       ;; align lines as nicely as possible
       (goto-char beg)
       (while (< (point) end)
	 (setq cur-start nil)
	 (when (and (not (looking-at "^\\s-*\\(begin\\|end\\)\\>"))
		    (or (and (looking-at "^\\(.*[^ \t\n-]+\\)\\(\\s-*\\)\\(--.*\\)$")
			     (not (save-excursion
				    (goto-char (match-beginning 3))
				    (vhdl-in-literal))))
			(and (looking-at "^\\(\\)\\(\\s-*\\)\\(--.*\\)$")
			     (>= (- (match-end 2) (match-beginning 2))
				 comment-column))))
	   (setq start (+ (- (match-end 1) (match-beginning 1)) spacing))
	   (setq length (- (match-end 3) (match-beginning 3)))
	   (setq no-code (= (match-beginning 1) (match-end 1)))
	   ;; insert minimum whitespace
	   (goto-char (match-end 2))
	   (delete-region (match-beginning 2) (match-end 2))
	   (insert-char ?\  spacing)
	   (setq tmp-list start-list)
	   ;; insert additional whitespace to align
	   (setq cur-start
		 (cond
		  ;; align comment-only line to inline comment of previous line
		  ((and no-code prev-start
			(<= length (- end-comment-column prev-start)))
		   prev-start)
		  ;; align all comments at `start-max' if this is possible
		  ((<= (+ start-max length-max) end-comment-column)
		   start-max)
		  ;; align at `comment-column' if possible
		  ((and (<= start comment-column)
			(<= length (- end-comment-column comment-column)))
		   comment-column)
		  ;; align at left-most possible start position otherwise
		  (t
		   (while (and tmp-list (< (car tmp-list) start))
		     (setq tmp-list (cdr tmp-list)))
		   (car tmp-list))))
	   (indent-to cur-start))
	 (setq prev-start cur-start)
	 (beginning-of-line 2))))))

(defun vhdl-align-inline-comment-region (beg end &optional spacing no-message)
  "Align inline comments within a region.  Groups of code lines separated by
empty lines are aligned individually, if `vhdl-align-groups' is non-nil."
  (interactive "r\nP")
  (save-excursion
    (let (pos)
      (goto-char beg)
      (beginning-of-line)
      (setq beg (point))
      (goto-char end)
      (setq end (point-marker))
      (untabify beg end)
      (unless no-message (message "Aligning inline comments..."))
      (goto-char beg)
      (if (not vhdl-align-groups)
	  ;; align entire region
	  (vhdl-align-inline-comment-region-1 beg end spacing)
	;; align groups
	(while (and (< beg end)
		    (re-search-forward vhdl-align-group-separate end t))
	  (setq pos (point-marker))
	  (vhdl-align-inline-comment-region-1 beg pos spacing)
	  (setq beg (1+ pos))
	  (goto-char beg))
	;; align last group
	(when (< beg end)
	  (vhdl-align-inline-comment-region-1 beg end spacing)))
      (unless no-message (message "Aligning inline comments...done")))))

(defun vhdl-align-inline-comment-group (&optional spacing)
  "Align inline comments within a group of lines between empty lines."
  (interactive)
  (save-excursion
    (let ((start (point))
	  beg end)
      (setq end (if (re-search-forward vhdl-align-group-separate nil t)
		    (point-marker) (point-max)))
      (goto-char start)
      (setq beg (if (re-search-backward vhdl-align-group-separate nil t)
		    (point) (point-min)))
      (untabify beg end)
      (message "Aligning inline comments...")
      (vhdl-align-inline-comment-region-1 beg end)
      (message "Aligning inline comments...done"))))

(defun vhdl-align-inline-comment-buffer ()
  "Align inline comments within buffer.  Groups of code lines separated by
empty lines are aligned individually, if `vhdl-align-groups' is non-nil."
  (interactive)
  (vhdl-align-inline-comment-region (point-min) (point-max)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fixup whitespace

(defun vhdl-fixup-whitespace-region (beg end &optional no-message)
  "Fixup whitespace in region.  Surround operator symbols by one space,
eliminate multiple spaces (except at beginning of line), eliminate spaces at
end of line, do nothing in comments and strings."
  (interactive "r")
  (unless no-message (message "Fixing up whitespace..."))
  (save-excursion
    (goto-char end)
    (setq end (point-marker))
    ;; have no space before and one space after `,' and ';'
    (goto-char beg)
    (while (re-search-forward "\\(--\\)\\|\\(\"\\)\\|\\(\\s-*\\([,;]\\)\\)" end t)
      (cond ((match-string 1) (re-search-forward ".*\n" end t))
	    ((match-string 2) (re-search-forward ".*[\"\n]" end t))
	    (t (replace-match "\\4 " nil nil nil 3))))
    ;; surround operator symbols by one space
    (goto-char beg)
    (while (re-search-forward "\\(--.*\n\\|\".*[\"\n]\\)\\|\\(\\([^/:<>=]\\)\\(:\\|=\\|<\\|>\\|:=\\|<=\\|>=\\|=>\\|/=\\)\\([^=>]\\|$\\)\\)" end t)
      (cond ((match-string 1) (goto-char (match-end 1)))
	    (t (replace-match "\\3 \\4 \\5")
	       (goto-char (match-end 4)))))
    ;; eliminate multiple spaces and spaces at end of line
    (goto-char beg)
    (while (or (and (looking-at "--.*\n") (re-search-forward "--.*\n" end t))
	       (and (looking-at "\"") (re-search-forward "\".*[\"\n]" end t))
	       (and (looking-at "\\s-+$") (re-search-forward "\\s-+$" end t)
		    (progn (replace-match "" nil nil) t))
	       (and (looking-at "\\s-+;") (re-search-forward "\\s-+;" end t)
		    (progn (replace-match ";" nil nil) t))
	       (and (looking-at "^\\s-+") (re-search-forward "^\\s-+" end t))
	       (and (looking-at "\\s-+--") (re-search-forward "\\s-+" end t)
		    (progn (replace-match "  " nil nil) t))
	       (and (looking-at "\\s-+") (re-search-forward "\\s-+" end t)
		    (progn (replace-match " " nil nil) t))
	       (re-search-forward "[^ \t-]+" end t))))
  (unless no-message (message "Fixing up whitespace...done")))

(defun vhdl-fixup-whitespace-buffer ()
  "Fixup whitespace in buffer.  Surround operator symbols by one space,
eliminate multiple spaces (except at beginning of line), eliminate spaces at
end of line, do nothing in comments."
  (interactive)
  (vhdl-fixup-whitespace-region (point-min) (point-max)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Beautify

(defun vhdl-beautify-region (beg end)
  "Beautify region by applying indentation, whitespace fixup, alignment, and
case fixing to a region.  Calls functions `vhdl-indent-buffer',
`vhdl-align-buffer' (option `vhdl-align-groups' set to non-nil), and
`vhdl-fix-case-buffer'."
  (interactive "r")
  (setq end (save-excursion (goto-char end) (point-marker)))
  (vhdl-indent-region beg end nil)
  (let ((vhdl-align-groups t))
    (vhdl-align-region beg end))
  (vhdl-fix-case-region beg end))

(defun vhdl-beautify-buffer ()
  "Beautify buffer by applying indentation, whitespace fixup, alignment, and
case fixing to entire buffer.  Calls `vhdl-beautify-region' for the entire
buffer."
  (interactive)
  (vhdl-beautify-region (point-min) (point-max))
  (when noninteractive (save-buffer)))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code updating/fixing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sensitivity list update

;; Strategy:
;; - no sensitivity list is generated for processes with wait statements
;; - otherwise, do the following:
;;   1. scan for all local signals (ports, signals declared in arch./blocks)
;;   2. scan for all signals already in the sensitivity list (in order to catch
;;      manually entered global signals)
;;   3. signals from 1. and 2. form the list of visible signals
;;   4. search for if/elsif conditions containing an event (sequential code)
;;   5. scan for strings that are within syntactical regions where signals are
;;      read but not within sequential code, and that correspond to visible
;;      signals
;;   6. replace sensitivity list by list of signals from 5.

(defun vhdl-update-sensitivity-list-process ()
  "Update sensitivity list of current process."
  (interactive)
  (save-excursion
    (vhdl-prepare-search-2
     (end-of-line)
     ;; look whether in process
     (if (not (and (re-search-backward "^\\s-*\\(\\w+[ \t\n]*:[ \t\n]*\\)?\\(process\\|end\\s-+process\\)\\>" nil t)
		   (equal (upcase (match-string 2)) "PROCESS")
		   (save-excursion (re-search-forward "^\\s-*end\\s-+process\\>" nil t))))
	 (error "Not within a process")
       (message "Updating sensitivity list...")
       (vhdl-update-sensitivity-list)
       (message "Updating sensitivity list...done")))))

(defun vhdl-update-sensitivity-list-buffer ()
  "Update sensitivity list of all processes in current buffer."
  (interactive)
  (save-excursion
    (vhdl-prepare-search-2
     (goto-char (point-min))
     (message "Updating sensitivity lists...")
     (while (re-search-forward "^\\s-*\\(\\w+[ \t\n]*:[ \t\n]*\\)?process\\>" nil t)
       (goto-char (match-beginning 0))
       (condition-case nil (vhdl-update-sensitivity-list) (error)))
     (message "Updating sensitivity lists...done"))))

(defun vhdl-update-sensitivity-list ()
  "Update sensitivity list."
    (let ((proc-beg (point))
	  (proc-end (re-search-forward "^\\s-*end\\s-+process\\>" nil t))
	  (proc-mid (re-search-backward "^\\s-*begin\\>" nil t))
	  seq-region-list)
      (cond
       ;; search for wait statement (no sensitivity list allowed)
       ((progn (goto-char proc-mid)
	       (vhdl-re-search-forward "\\<wait\\>" proc-end t))
	(error "Process with wait statement, sensitivity list not generated"))
       ;; combinational process (update sensitivity list)
       (t
	(let
	    ;; scan for visible signals
	    ((visible-list (vhdl-get-visible-signals))
	     ;; define syntactic regions where signals are read
	     (scan-regions-list
	      '(;; right-hand side of signal/variable assignment
		;; (special case: "<=" is relational operator in a condition)
		((re-search-forward "[<:]=" proc-end t)
		 (re-search-forward ";\\|\\<\\(then\\|loop\\|report\\|severity\\|is\\)\\>" proc-end t))
		;; if condition
		((re-search-forward "^\\s-*if\\>" proc-end t)
		 (re-search-forward "\\<then\\>" proc-end t))
		;; elsif condition
		((re-search-forward "\\<elsif\\>" proc-end t)
		 (re-search-forward "\\<then\\>" proc-end t))
		;; while loop condition
		((re-search-forward "^\\s-*while\\>" proc-end t)
		 (re-search-forward "\\<loop\\>" proc-end t))
		;; exit/next condition
		((re-search-forward "\\<\\(exit\\|next\\)\\s-+\\w+\\s-+when\\>" proc-end t)
		 (re-search-forward ";" proc-end t))
		;; assert condition
		((re-search-forward "\\<assert\\>" proc-end t)
		 (re-search-forward "\\(\\<report\\>\\|\\<severity\\>\\|;\\)" proc-end t))
		;; case expression
		((re-search-forward "^\\s-*case\\>" proc-end t)
		 (re-search-forward "\\<is\\>" proc-end t))
		;; parameter list of procedure call
		((re-search-forward "^\\s-*\\w+[ \t\n]*(" proc-end t)
		 (progn (backward-char) (forward-sexp) (point)))))
	     name read-list sens-list signal-list
	     sens-beg sens-end beg end margin)
	  ;; scan for signals in old sensitivity list
	  (goto-char proc-beg)
	  (re-search-forward "\\<process\\>" proc-mid t)
	  (if (not (looking-at "[ \t\n]*("))
	      (setq sens-beg (point))
	    (setq sens-beg (re-search-forward "\\([ \t\n]*\\)([ \t\n]*" nil t))
	    (goto-char (match-end 1))
	    (forward-sexp)
	    (setq sens-end (1- (point)))
	    (goto-char sens-beg)
	    (while (and (re-search-forward "\\(\\w+\\)" sens-end t)
			(setq sens-list (cons (match-string 0) sens-list))
			(re-search-forward "\\s-*,\\s-*" sens-end t))))
	  (setq signal-list (append visible-list sens-list))
	  ;; search for sequential parts
	  (goto-char proc-mid)
	  (while (setq beg (re-search-forward "^\\s-*\\(els\\)?if\\>" proc-end t))
	    (setq end (re-search-forward "\\<then\\>" proc-end t))
	    (when (re-search-backward "\\('event\\|\\<\\(falling\\|rising\\)_edge\\)\\>" beg t)
	      (goto-char end)
	      (backward-word 1)
	      (vhdl-forward-sexp)
	      (setq seq-region-list (cons (cons end (point)) seq-region-list))
	      (beginning-of-line)))
	  ;; scan for signals read in process
	  (while scan-regions-list
	    (goto-char proc-mid)
	    (while (and (setq beg (eval (nth 0 (car scan-regions-list))))
			(setq end (eval (nth 1 (car scan-regions-list)))))
	      (goto-char beg)
	      (unless (or (vhdl-in-literal)
			  (and seq-region-list
			       (let ((tmp-list seq-region-list))
				 (while (and tmp-list
					     (< (point) (caar tmp-list)))
				   (setq tmp-list (cdr tmp-list)))
				 (and tmp-list (< (point) (cdar tmp-list))))))
		(while (re-search-forward "\\([a-zA-Z]\\w*\\)" end t)
		  (setq name (match-string 1))
		  (when (member name signal-list)
		    (add-to-list 'read-list name)))))
	    (setq scan-regions-list (cdr scan-regions-list)))
	  ;; update sensitivity list
	  (goto-char sens-beg)
	  (if sens-end
	      (delete-region sens-beg sens-end)
	    (when read-list
	      (insert " ()") (backward-char)))
	  (setq read-list (sort read-list 'string<))
	  (when read-list
	    (setq margin (current-column))
	    (insert (car read-list))
	    (setq read-list (cdr read-list))
	    (while read-list
	      (insert ",")
	      (if (<= (+ (current-column) (length (car read-list)) 2)
		      end-comment-column)
		  (insert " ")
		(insert "\n") (indent-to margin))
	      (insert (car read-list))
	      (setq read-list (cdr read-list)))))))))

(defun vhdl-get-visible-signals ()
  "Get all signals visible in the current block."
  (save-excursion
    (let (beg end signal-list entity-name file-name)
      ;; search for signals declared in surrounding block declarative parts
      (save-excursion
	(while (and (progn (while (and (setq beg (re-search-backward "^\\s-*\\(\\w+\\s-*:\\s-*block\\|\\(end\\)\\s-+block\\)\\>" nil t))
				       (match-string 2))
			     (goto-char (match-end 2))
			     (vhdl-backward-sexp)
			     (re-search-backward "^\\s-*\\w+\\s-*:\\s-*block\\>" nil t))
			   beg)
		    (setq end (re-search-forward "^\\s-*begin\\>" nil t)))
	  ;; scan for all declared signal names
	  (goto-char beg)
	  (while (re-search-forward "^\\s-*signal\\>" end t)
	    (while (and (not (looking-at "[ \t\n]*:"))
			(re-search-forward "[ \t\n,]+\\(\\w+\\)" end t))
	      (setq signal-list (cons (match-string 1) signal-list))))
	  (goto-char beg)))
      ;; search for signals declared in architecture declarative part
      (if (not (and (setq beg (re-search-backward "^\\(architecture\\s-+\\w+\\s-+of\\s-+\\(\\w+\\)\\|end\\)\\>" nil t))
		    (not (equal "END" (upcase (match-string 1))))
		    (setq entity-name (match-string 2))
		    (setq end (re-search-forward "^begin\\>" nil t))))
	  (error "No architecture declarative part found")
	;; scan for all declared signal names
	(goto-char beg)
	(while (re-search-forward "^\\s-*signal\\>" end t)
	  (while (and (not (looking-at "[ \t\n]*:"))
		      (re-search-forward "[ \t\n,]+\\(\\w+\\)" end t))
	    (setq signal-list (cons (match-string 1) signal-list)))))
      ;; search for signals declared in entity port clause
      (goto-char (point-min))
      (when (not (re-search-forward (concat "^entity\\s-+" entity-name "\\>") nil t))
	(setq file-name
	      (concat (vhdl-replace-string vhdl-entity-file-name entity-name)
		      "." (file-name-extension (buffer-file-name)))))
      (vhdl-visit-file
       file-name
       (vhdl-prepare-search-2
	(goto-char (point-min))
	(if (not (re-search-forward (concat "^entity\\s-+" entity-name "\\>") nil t))
	    (progn
	      (message "  --> see option `vhdl-entity-file-name'")
	      (error "Entity \"%s\" not found (see \"%s\" buffer)" entity-name
		     (if vhdl-xemacs " *Message-log*" "*Messages*")))
	  (when (setq beg (re-search-forward
			   "^\\s-*port[ \t\n]*("
			   (save-excursion
			     (re-search-forward "^end\\>" nil t)) t))
	    (setq end (save-excursion
			(backward-char) (forward-sexp) (point)))
	    (vhdl-forward-syntactic-ws)
	    (while (< (point) end)
	      (while (and (not (looking-at "[ \t\n]*:"))
			  (re-search-forward "[ \t\n,]*\\(\\w+\\)" end t))
		(setq signal-list (cons (match-string 1) signal-list)))
	      (re-search-forward ";" end 1)
	      (vhdl-forward-syntactic-ws))))))
      signal-list)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generic/port clause fixing

(defun vhdl-fix-clause ()
  "Fix closing parenthesis within generic/port clause."
  (interactive)
  (save-excursion
    (vhdl-prepare-search-2
     (let ((pos (point))
	   beg end)
       (if (not (re-search-backward "^\\s-*\\(generic\\|port\\)[ \t\n]*(" nil t))
	   (error "Not within a generic/port clause")
	 ;; search for end of clause
	 (goto-char (match-end 0))
	 (setq beg (1- (point)))
	 (vhdl-forward-syntactic-ws)
	 (while (looking-at "\\w+\\([ \t\n]*,[ \t\n]*\\w+\\)*[ \t\n]*:[ \t\n]*\\w+[^;]*;")
	   (goto-char (1- (match-end 0)))
	   (setq end (point-marker))
	   (forward-char)
	   (vhdl-forward-syntactic-ws))
	 (goto-char end)
	 (when (> pos (save-excursion (end-of-line) (point)))
	   (error "Not within a generic/port clause"))
	 ;; delete closing parenthesis on separate line (not supported style)
	 (when (save-excursion (beginning-of-line) (looking-at "^\\s-*);"))
	   (vhdl-line-kill)
	   (vhdl-backward-syntactic-ws)
	   (setq end (point-marker))
	   (insert ";"))
	 ;; delete superfluous parentheses
	 (while (progn (goto-char beg)
		       (condition-case () (forward-sexp)
			 (error (goto-char (point-max))))
		       (< (point) end))
	   (delete-backward-char 1))
	 ;; add closing parenthesis
	 (when (> (point) end)
	   (goto-char end)
	   (insert ")")))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Miscellaneous

(defun vhdl-remove-trailing-spaces ()
  "Remove trailing spaces in the whole buffer."
  (interactive)
  (save-match-data
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward "[ \t]+$" (point-max) t)
	(unless (vhdl-in-literal)
	  (replace-match "" nil nil))))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Electrification
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defconst vhdl-template-prompt-syntax "[^ =<>][^<>@.\n]*[^ =<>]"
  "Syntax of prompt inserted by template generators.")

(defvar vhdl-template-invoked-by-hook nil
  "Indicates whether a template has been invoked by a hook or by key or menu.
Used for undoing after template abortion.")

;; correct different behavior of function `unread-command-events' in XEmacs
(defun vhdl-character-to-event (arg))
(defalias 'vhdl-character-to-event
  (if vhdl-xemacs 'character-to-event 'identity))

(defsubst vhdl-work-library ()
  "Return the working library name of the current project or \"work\" if no
project is defined."
  (or (nth 6 (aget vhdl-project-alist vhdl-project)) "work"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;  Enabling/disabling

(defun vhdl-mode-line-update ()
  "Update the modeline string for VHDL major mode."
  (setq mode-name (concat "VHDL"
			  (and (or vhdl-electric-mode vhdl-stutter-mode) "/")
			  (and vhdl-electric-mode "e")
			  (and vhdl-stutter-mode "s")))
  (force-mode-line-update t))

(defun vhdl-electric-mode (arg)
  "Toggle VHDL electric mode.
Turn on if ARG positive, turn off if ARG negative, toggle if ARG zero or nil."
  (interactive "P")
  (setq vhdl-electric-mode
	(cond ((or (not arg) (zerop arg)) (not vhdl-electric-mode))
	      ((> arg 0) t) (t nil)))
  (vhdl-mode-line-update))

(defun vhdl-stutter-mode (arg)
  "Toggle VHDL stuttering mode.
Turn on if ARG positive, turn off if ARG negative, toggle if ARG zero or nil."
  (interactive "P")
  (setq vhdl-stutter-mode
	(cond ((or (not arg) (zerop arg)) (not vhdl-stutter-mode))
	      ((> arg 0) t) (t nil)))
  (vhdl-mode-line-update))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Stuttering

(defun vhdl-electric-dash (count)
  "-- starts a comment, --- draws a horizontal line,
---- starts a display comment"
  (interactive "p")
  (if (and vhdl-stutter-mode (not (vhdl-in-literal)))
      (cond
       ((and abbrev-start-location (= abbrev-start-location (point)))
	(setq abbrev-start-location nil)
	(goto-char last-abbrev-location)
	(beginning-of-line nil)
	(vhdl-comment-display))
       ((/= (preceding-char) ?-)	; standard dash (minus)
	(self-insert-command count))
       (t (self-insert-command count)
	  (message "Enter '-' for horiz. line, 'CR' for commenting-out code, else enter comment")
	  (let ((next-input (read-char)))
	    (if (= next-input ?-)	; triple dash
		(progn
		  (vhdl-comment-display-line)
		  (message
		   "Enter '-' for display comment, else continue coding")
		  (let ((next-input (read-char)))
		    (if (= next-input ?-) ; four dashes
			(vhdl-comment-display t)
		      (setq unread-command-events ; pushback the char
			    (list (vhdl-character-to-event next-input))))))
	      (setq unread-command-events ; pushback the char
		    (list (vhdl-character-to-event next-input)))
	      (vhdl-comment-insert)))))
    (self-insert-command count)))

(defun vhdl-electric-open-bracket (count) "'[' --> '(', '([' --> '['"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (if (= (preceding-char) ?\()
	  (progn (delete-char -1) (insert-char ?\[ 1))
	(insert-char ?\( 1))
    (self-insert-command count)))

(defun vhdl-electric-close-bracket (count) "']' --> ')', ')]' --> ']'"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (progn
	(if (= (preceding-char) ?\))
	    (progn (delete-char -1) (insert-char ?\] 1))
	  (insert-char ?\) 1))
	(blink-matching-open))
    (self-insert-command count)))

(defun vhdl-electric-quote (count) "'' --> \""
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (if (= (preceding-char) last-input-char)
	  (progn (delete-backward-char 1) (insert-char ?\" 1))
	(insert-char ?\' 1))
    (self-insert-command count)))

(defun vhdl-electric-semicolon (count) "';;' --> ' : ', ': ;' --> ' := '"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (cond ((= (preceding-char) last-input-char)
	     (progn (delete-char -1)
		    (when (not (eq (preceding-char) ? )) (insert " "))
		    (insert ": ")
		    (setq this-command 'vhdl-electric-colon)))
	    ((and
	      (eq last-command 'vhdl-electric-colon) (= (preceding-char) ? ))
	     (progn (delete-char -1) (insert "= ")))
	    (t (insert-char ?\; 1)))
    (self-insert-command count)))

(defun vhdl-electric-comma (count) "',,' --> ' <= '"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (cond ((= (preceding-char) last-input-char)
	     (progn (delete-char -1)
		    (when (not (eq (preceding-char) ? )) (insert " "))
		    (insert "<= ")))
	    (t (insert-char ?\, 1)))
    (self-insert-command count)))

(defun vhdl-electric-period (count) "'..' --> ' => '"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (cond ((= (preceding-char) last-input-char)
	     (progn (delete-char -1)
		    (when (not (eq (preceding-char) ? )) (insert " "))
		    (insert "=> ")))
	    (t (insert-char ?\. 1)))
    (self-insert-command count)))

(defun vhdl-electric-equal (count) "'==' --> ' == '"
  (interactive "p")
  (if (and vhdl-stutter-mode (= count 1) (not (vhdl-in-literal)))
      (cond ((= (preceding-char) last-input-char)
	     (progn (delete-char -1)
		    (when (not (eq (preceding-char) ? )) (insert " "))
		    (insert "== ")))
	    (t (insert-char ?\= 1)))
    (self-insert-command count)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;  VHDL templates

(defun vhdl-template-paired-parens ()
  "Insert a pair of round parentheses, placing point between them."
  (interactive)
  (insert "()")
  (backward-char))

(defun vhdl-template-alias ()
  "Insert alias declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "ALIAS ")
    (when (vhdl-template-field "name" nil t start (point))
      (insert " : ")
      (unless (vhdl-template-field
	       (concat "[type" (and (vhdl-standard-p 'ams) " or nature") "]")
	       nil t)
	(delete-backward-char 3))
      (vhdl-insert-keyword " IS ")
      (vhdl-template-field "name" ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-architecture ()
  "Insert architecture."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	arch-name)
    (vhdl-insert-keyword "ARCHITECTURE ")
    (when (setq arch-name
		(vhdl-template-field "name" nil t start (point)))
      (vhdl-insert-keyword " OF ")
      (if (save-excursion
	    (vhdl-prepare-search-1
	     (re-search-backward "\\<entity \\(\\w+\\) is\\>" nil t)))
	  (insert (match-string 1))
	(vhdl-template-field "entity name"))
      (vhdl-insert-keyword " IS")
      (vhdl-template-begin-end
       (unless (vhdl-standard-p '87) "ARCHITECTURE") arch-name margin
       (memq vhdl-insert-empty-lines '(unit all))))))

(defun vhdl-template-array (kind &optional secondary)
  "Insert array type definition."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "ARRAY (")
    (when (or (vhdl-template-field "range" nil (not secondary) start (point))
	      secondary)
      (vhdl-insert-keyword ") OF ")
      (vhdl-template-field (if (eq kind 'type) "type" "nature"))
      (vhdl-insert-keyword ";"))))

(defun vhdl-template-assert ()
  "Insert an assertion statement."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "ASSERT ")
    (when vhdl-conditions-in-parenthesis (insert "("))
    (when (vhdl-template-field "condition (negated)" nil t start (point))
      (when vhdl-conditions-in-parenthesis (insert ")"))
      (setq start (point))
      (vhdl-insert-keyword " REPORT ")
      (unless (vhdl-template-field "string expression" nil nil nil nil t)
	(delete-region start (point)))
      (setq start (point))
      (vhdl-insert-keyword " SEVERITY ")
      (unless (vhdl-template-field "[NOTE | WARNING | ERROR | FAILURE]" nil t)
	(delete-region start (point)))
      (insert ";"))))

(defun vhdl-template-attribute ()
  "Insert an attribute declaration or specification."
  (interactive)
  (if (eq (vhdl-decision-query
	   "attribute" "(d)eclaration or (s)pecification?" t) ?s)
      (vhdl-template-attribute-spec)
    (vhdl-template-attribute-decl)))

(defun vhdl-template-attribute-decl ()
  "Insert an attribute declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "ATTRIBUTE ")
    (when (vhdl-template-field "name" " : " t start (point))
      (vhdl-template-field "type" ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-attribute-spec ()
  "Insert an attribute specification."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "ATTRIBUTE ")
    (when (vhdl-template-field "name" nil t start (point))
      (vhdl-insert-keyword " OF ")
      (vhdl-template-field "entity names | OTHERS | ALL" " : ")
      (vhdl-template-field "entity class")
      (vhdl-insert-keyword " IS ")
      (vhdl-template-field "expression" ";"))))

(defun vhdl-template-block ()
  "Insert a block."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label)
    (vhdl-insert-keyword ": BLOCK ")
    (goto-char start)
    (when (setq label (vhdl-template-field "label" nil t start (+ (point) 8)))
      (forward-word 1)
      (forward-char 1)
      (insert "(")
      (if (vhdl-template-field "[guard expression]" nil t)
	  (insert ")")
	(delete-char -2))
      (unless (vhdl-standard-p '87) (vhdl-insert-keyword " IS"))
      (vhdl-template-begin-end "BLOCK" label margin)
      (vhdl-comment-block))))

(defun vhdl-template-block-configuration ()
  "Insert a block configuration statement."
  (interactive)
  (let ((margin (current-indentation))
	(start (point)))
    (vhdl-insert-keyword "FOR ")
    (when (vhdl-template-field "block name" nil t start (point))
      (vhdl-insert-keyword "\n\n")
      (indent-to margin)
      (vhdl-insert-keyword "END FOR;")
      (end-of-line 0)
      (indent-to (+ margin vhdl-basic-offset)))))

(defun vhdl-template-break ()
  "Insert a break statement."
  (interactive)
  (let (position)
    (vhdl-insert-keyword "BREAK")
    (setq position (point))
    (insert " ")
    (while (or
	    (progn (vhdl-insert-keyword "FOR ")
		   (if (vhdl-template-field "[quantity name]" " USE " t)
		       (progn (vhdl-template-field "quantity name" " => ") t)
		     (kill-word -1) nil))
	    (vhdl-template-field "[quantity name]" " => " t))
      (vhdl-template-field "expression")
      (setq position (point))
      (insert ", "))
    (delete-region position (point))
    (unless (vhdl-sequential-statement-p)
      (vhdl-insert-keyword " ON ")
      (if (vhdl-template-field "[sensitivity list]" nil t)
	  (setq position (point))
	(delete-region position (point))))
    (vhdl-insert-keyword " WHEN ")
    (when vhdl-conditions-in-parenthesis (insert "("))
    (if (vhdl-template-field "[condition]" nil t)
	(when vhdl-conditions-in-parenthesis (insert ")"))
      (delete-region position (point)))
    (insert ";")))

(defun vhdl-template-case (&optional kind)
  "Insert a case statement."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label)
    (unless kind (setq kind (if (vhdl-sequential-statement-p) 'is 'use)))
    (if (or (not (eq vhdl-optional-labels 'all)) (vhdl-standard-p '87))
	(vhdl-insert-keyword "CASE ")
      (vhdl-insert-keyword ": CASE ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (when (vhdl-template-field "expression" nil t start (point))
      (vhdl-insert-keyword (concat " " (if (eq kind 'is) "IS" "USE") "\n\n"))
      (indent-to margin)
      (vhdl-insert-keyword "END CASE")
      (when label (insert " " label))
      (insert ";")
      (forward-line -1)
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-insert-keyword "WHEN ")
      (let ((position (point)))
	(insert " => ;\n")
	(indent-to (+ margin vhdl-basic-offset))
	(vhdl-insert-keyword "WHEN OTHERS => null;")
	(goto-char position)))))

(defun vhdl-template-case-is ()
  "Insert a sequential case statement."
  (interactive)
  (vhdl-template-case 'is))

(defun vhdl-template-case-use ()
  "Insert a simultaneous case statement."
  (interactive)
  (vhdl-template-case 'use))

(defun vhdl-template-component ()
  "Insert a component declaration."
  (interactive)
  (vhdl-template-component-decl))

(defun vhdl-template-component-conf ()
  "Insert a component configuration (uses `vhdl-template-configuration-spec'
since these are almost equivalent)."
  (interactive)
  (let ((margin (current-indentation))
	(result (vhdl-template-configuration-spec t)))
    (when result
      (insert "\n")
      (indent-to margin)
      (vhdl-insert-keyword "END FOR;")
      (when (eq result 'no-use)
	(end-of-line -0)))))

(defun vhdl-template-component-decl ()
  "Insert a component declaration."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name end-column)
    (vhdl-insert-keyword "COMPONENT ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (unless (vhdl-standard-p '87) (vhdl-insert-keyword " IS"))
      (insert "\n\n")
      (indent-to margin)
      (vhdl-insert-keyword "END COMPONENT")
      (unless (vhdl-standard-p '87) (insert " " name))
      (insert ";")
      (setq end-column (current-column))
      (end-of-line -0)
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-template-generic-list t t)
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-template-port-list t)
      (beginning-of-line 2)
      (forward-char end-column))))

(defun vhdl-template-component-inst ()
  "Insert a component instantiation statement."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	unit position)
    (when (vhdl-template-field "instance label" nil t start (point))
      (insert ": ")
      (if (vhdl-standard-p '87)
	  (vhdl-template-field "component name")
	;; direct instantiation
	(setq unit (vhdl-template-field
		    "[COMPONENT | ENTITY | CONFIGURATION]" " " t))
	(setq unit (upcase (or unit "")))
	(cond ((equal unit "ENTITY")
	       (vhdl-template-field "library name" "." nil nil nil nil
				    (vhdl-work-library))
	       (vhdl-template-field "entity name" "(")
	       (if (vhdl-template-field "[architecture name]" nil t)
		   (insert ")")
		 (delete-char -1)))
	      ((equal unit "CONFIGURATION")
	       (vhdl-template-field "library name" "." nil nil nil nil
				    (vhdl-work-library))
	       (vhdl-template-field "configuration name"))
	      (t (vhdl-template-field "component name"))))
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (setq position (point))
      (vhdl-insert-keyword "GENERIC ")
      (when (vhdl-template-map position t t)
	(insert "\n")
	(indent-to (+ margin vhdl-basic-offset)))
      (setq position (point))
      (vhdl-insert-keyword "PORT ")
      (unless (vhdl-template-map position t t)
	(kill-line -0)
	(delete-char -1))
      (insert ";"))))

(defun vhdl-template-conditional-signal-asst ()
  "Insert a conditional signal assignment."
  (interactive)
  (when (vhdl-template-field "target signal")
    (insert " <= ")
;    (if (not (equal (vhdl-template-field "[GUARDED] [TRANSPORT]") ""))
;       (insert " "))
    (let ((margin (current-column))
	  (start (point))
	  position)
      (vhdl-template-field "waveform")
      (setq position (point))
      (vhdl-insert-keyword " WHEN ")
      (when vhdl-conditions-in-parenthesis (insert "("))
      (while (and (vhdl-template-field "[condition]" nil t)
		  (progn
		    (when vhdl-conditions-in-parenthesis (insert ")"))
		    (setq position (point))
		    (vhdl-insert-keyword " ELSE")
		    (insert "\n")
		    (indent-to margin)
		    (vhdl-template-field "[waveform]" nil t)))
	(setq position (point))
	(vhdl-insert-keyword " WHEN ")
	(when vhdl-conditions-in-parenthesis (insert "(")))
      (delete-region position (point))
      (insert ";")
      (when vhdl-auto-align (vhdl-align-region-groups start (point) 1)))))

(defun vhdl-template-configuration ()
  "Insert a configuration specification if within an architecture,
a block or component configuration if within a configuration declaration,
a configuration declaration if not within a design unit."
  (interactive)
  (vhdl-prepare-search-1
   (cond
    ((and (save-excursion		; architecture body
	    (re-search-backward "^\\(architecture\\|end\\)\\>" nil t))
	  (equal "ARCHITECTURE" (upcase (match-string 1))))
     (vhdl-template-configuration-spec))
    ((and (save-excursion		; configuration declaration
	    (re-search-backward "^\\(configuration\\|end\\)\\>" nil t))
	  (equal "CONFIGURATION" (upcase (match-string 1))))
     (if (eq (vhdl-decision-query
	      "configuration" "(b)lock or (c)omponent configuration?" t) ?c)
	 (vhdl-template-component-conf)
       (vhdl-template-block-configuration)))
    (t (vhdl-template-configuration-decl))))) ; otherwise

(defun vhdl-template-configuration-spec (&optional optional-use)
  "Insert a configuration specification."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	aspect position)
    (vhdl-insert-keyword "FOR ")
    (when (vhdl-template-field "instance names | OTHERS | ALL" " : "
			       t start (point))
      (vhdl-template-field "component name" "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (setq start (point))
      (vhdl-insert-keyword "USE ")
      (if (and optional-use
	       (not (setq aspect (vhdl-template-field
				  "[ENTITY | CONFIGURATION | OPEN]" " " t))))
	  (progn (delete-region start (point)) 'no-use)
	(unless optional-use
	  (setq aspect (vhdl-template-field
			"ENTITY | CONFIGURATION | OPEN" " ")))
	(setq aspect (upcase (or aspect "")))
	(cond ((equal aspect "ENTITY")
	       (vhdl-template-field "library name" "." nil nil nil nil
				    (vhdl-work-library))
	       (vhdl-template-field "entity name" "(")
	       (if (vhdl-template-field "[architecture name]" nil t)
		   (insert ")")
		 (delete-char -1))
	       (insert "\n")
	       (indent-to (+ margin (* 2 vhdl-basic-offset)))
	       (setq position (point))
	       (vhdl-insert-keyword "GENERIC ")
	       (when (vhdl-template-map position t t)
		 (insert "\n")
		 (indent-to (+ margin (* 2 vhdl-basic-offset))))
	       (setq position (point))
	       (vhdl-insert-keyword "PORT ")
	       (unless (vhdl-template-map position t t)
		 (kill-line -0)
		 (delete-char -1))
	       (insert ";")
	       t)
	      ((equal aspect "CONFIGURATION")
	       (vhdl-template-field "library name" "." nil nil nil nil
				    (vhdl-work-library))
	       (vhdl-template-field "configuration name" ";"))
	      (t (delete-backward-char 1) (insert ";") t))))))


(defun vhdl-template-configuration-decl ()
  "Insert a configuration declaration."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	entity-exists string name position)
    (vhdl-insert-keyword "CONFIGURATION ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-insert-keyword " OF ")
      (save-excursion
	(vhdl-prepare-search-1
	 (setq entity-exists (re-search-backward
			      "\\<entity \\(\\w*\\) is\\>" nil t))
	 (setq string (match-string 1))))
      (if (and entity-exists (not (equal string "")))
	  (insert string)
	(vhdl-template-field "entity name"))
      (vhdl-insert-keyword " IS\n")
      (when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n"))
      (indent-to (+ margin vhdl-basic-offset))
      (setq position (point))
      (insert "\n")
      (when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n"))
      (indent-to margin)
      (vhdl-insert-keyword "END ")
      (unless (vhdl-standard-p '87)
	(vhdl-insert-keyword "CONFIGURATION "))
      (insert name ";")
      (goto-char position))))

(defun vhdl-template-constant ()
  "Insert a constant declaration."
  (interactive)
  (let ((start (point))
	(in-arglist (vhdl-in-argument-list-p)))
    (vhdl-insert-keyword "CONSTANT ")
    (when (vhdl-template-field "name" nil t start (point))
      (insert " : ")
      (when in-arglist (vhdl-insert-keyword "IN "))
      (vhdl-template-field "type")
      (if in-arglist
	  (progn (insert ";")
		 (vhdl-comment-insert-inline))
	(let ((position (point)))
	  (insert " := ")
	  (unless (vhdl-template-field "[initialization]" nil t)
	    (delete-region position (point)))
	  (insert ";")
	  (vhdl-comment-insert-inline))))))

(defun vhdl-template-default ()
  "Insert nothing."
  (interactive)
  (insert " ")
  (unexpand-abbrev)
  (backward-word 1)
  (vhdl-case-word 1)
  (forward-char 1))

(defun vhdl-template-default-indent ()
  "Insert nothing and indent."
  (interactive)
  (insert " ")
  (unexpand-abbrev)
  (backward-word 1)
  (vhdl-case-word 1)
  (forward-char 1)
  (indent-according-to-mode))

(defun vhdl-template-disconnect ()
  "Insert a disconnect statement."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "DISCONNECT ")
    (when (vhdl-template-field "signal names | OTHERS | ALL"
			       " : " t start (point))
      (vhdl-template-field "type")
      (vhdl-insert-keyword " AFTER ")
      (vhdl-template-field "time expression" ";"))))

(defun vhdl-template-else ()
  "Insert an else statement."
  (interactive)
  (let (margin)
    (vhdl-prepare-search-1
     (vhdl-insert-keyword "ELSE")
     (if (save-excursion
	   (re-search-backward "\\(\\<when\\>\\|;\\)" nil t)
	   (equal "WHEN" (upcase (match-string 1))))
	 (insert " ")
       (indent-according-to-mode)
       (setq margin (current-indentation))
       (insert "\n")
       (indent-to (+ margin vhdl-basic-offset))))))

(defun vhdl-template-elsif ()
  "Insert an elsif statement."
  (interactive)
  (let ((start (point))
	margin)
    (vhdl-insert-keyword "ELSIF ")
    (when (or (vhdl-sequential-statement-p) (vhdl-standard-p 'ams))
      (when vhdl-conditions-in-parenthesis (insert "("))
      (when (vhdl-template-field "condition" nil t start (point))
	(when vhdl-conditions-in-parenthesis (insert ")"))
	(indent-according-to-mode)
	(setq margin (current-indentation))
	(vhdl-insert-keyword
	 (concat " " (if (vhdl-sequential-statement-p) "THEN" "USE") "\n"))
	(indent-to (+ margin vhdl-basic-offset))))))

(defun vhdl-template-entity ()
  "Insert an entity."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name end-column)
    (vhdl-insert-keyword "ENTITY ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-insert-keyword " IS\n\n")
      (indent-to margin)
      (vhdl-insert-keyword "END ")
      (unless (vhdl-standard-p '87) (vhdl-insert-keyword "ENTITY "))
      (insert name ";")
      (setq end-column (current-column))
      (end-of-line -0)
      (indent-to (+ margin vhdl-basic-offset))
      (when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n"))
      (indent-to (+ margin vhdl-basic-offset))
      (when (vhdl-template-generic-list t)
	(when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n")))
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (when (vhdl-template-port-list t)
	(when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n")))
      (beginning-of-line 2)
      (forward-char end-column))))

(defun vhdl-template-exit ()
  "Insert an exit statement."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "EXIT ")
    (unless (vhdl-template-field "[loop label]" nil t)
      (delete-char -1))
    (let ((position (point)))
      (vhdl-insert-keyword " WHEN ")
      (when vhdl-conditions-in-parenthesis (insert "("))
      (if (vhdl-template-field "[condition]" nil t)
	  (when vhdl-conditions-in-parenthesis (insert ")"))
	(delete-region position (point))))
    (insert ";")))

(defun vhdl-template-file ()
  "Insert a file declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "FILE ")
    (when (vhdl-template-field "name" nil t start (point))
      (insert " : ")
      (vhdl-template-field "type")
      (unless (vhdl-standard-p '87)
	(vhdl-insert-keyword " OPEN ")
	(unless (vhdl-template-field "[READ_MODE | WRITE_MODE | APPEND_MODE]"
				     nil t)
	  (delete-backward-char 6)))
      (vhdl-insert-keyword " IS ")
      (when (vhdl-standard-p '87)
	(vhdl-template-field "[IN | OUT]" " " t))
      (vhdl-template-field "filename-string" nil nil nil nil t)
      (insert ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-for ()
  "Insert a block or component configuration if within a configuration
declaration, a configuration specification if within an architecture
declarative part (and not within a subprogram), a for-loop if within a
sequential statement part (subprogram or process), and a for-generate
otherwise."
  (interactive)
  (vhdl-prepare-search-1
   (cond
    ((vhdl-sequential-statement-p)	; sequential statement
     (vhdl-template-for-loop))
    ((and (save-excursion		; configuration declaration
	    (re-search-backward "^\\(configuration\\|end\\)\\>" nil t))
	  (equal "CONFIGURATION" (upcase (match-string 1))))
     (if (eq (vhdl-decision-query
	      "for" "(b)lock or (c)omponent configuration?" t) ?c)
	 (vhdl-template-component-conf)
       (vhdl-template-block-configuration)))
    ((and (save-excursion
	    (re-search-backward		; architecture declarative part
	     "^\\(architecture\\|entity\\|begin\\|end\\)\\>" nil t))
	  (equal "ARCHITECTURE" (upcase (match-string 1))))
     (vhdl-template-configuration-spec))
    (t (vhdl-template-for-generate))))) ; concurrent statement

(defun vhdl-template-for-generate ()
  "Insert a for-generate."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label position)
    (vhdl-insert-keyword ": FOR ")
    (setq position (point-marker))
    (goto-char start)
    (when (setq label (vhdl-template-field "label" nil t start position))
      (goto-char position)
      (vhdl-template-field "loop variable")
      (vhdl-insert-keyword " IN ")
      (vhdl-template-field "range")
      (vhdl-template-generate-body margin label))))

(defun vhdl-template-for-loop ()
  "Insert a for loop."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label index)
    (if (not (eq vhdl-optional-labels 'all))
	(vhdl-insert-keyword "FOR ")
      (vhdl-insert-keyword ": FOR ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (when (setq index (vhdl-template-field "loop variable"
					   nil t start (point)))
      (vhdl-insert-keyword " IN ")
      (vhdl-template-field "range")
      (vhdl-insert-keyword " LOOP\n\n")
      (indent-to margin)
      (vhdl-insert-keyword "END LOOP")
      (if label
	  (insert " " label ";")
	(insert ";")
	(when vhdl-self-insert-comments (insert "  -- " index)))
      (forward-line -1)
      (indent-to (+ margin vhdl-basic-offset)))))

(defun vhdl-template-function (&optional kind)
  "Insert a function declaration or body."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name)
    (vhdl-insert-keyword "FUNCTION ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-template-argument-list t)
      (when vhdl-auto-align (vhdl-align-region-groups start (point) 1))
      (end-of-line)
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-insert-keyword "RETURN ")
      (vhdl-template-field "type")
      (if (if kind (eq kind 'body)
	    (eq (vhdl-decision-query nil "(d)eclaration or (b)ody?") ?b))
	  (progn (vhdl-insert-keyword " IS")
		 (vhdl-template-begin-end
		  (unless (vhdl-standard-p '87) "FUNCTION") name margin)
		 (vhdl-comment-block))
	(insert ";")))))

(defun vhdl-template-function-decl ()
  "Insert a function declaration."
  (interactive)
  (vhdl-template-function 'decl))

(defun vhdl-template-function-body ()
  "Insert a function declaration."
  (interactive)
  (vhdl-template-function 'body))

(defun vhdl-template-generate ()
  "Insert a generation scheme."
  (interactive)
  (if (eq (vhdl-decision-query nil "(f)or or (i)f?" t) ?i)
      (vhdl-template-if-generate)
    (vhdl-template-for-generate)))

(defun vhdl-template-generic ()
  "Insert generic declaration, or generic map in instantiation statements."
  (interactive)
  (let ((start (point)))
    (vhdl-prepare-search-1
     (cond
      ((and (save-excursion		; entity declaration
	      (re-search-backward "^\\(entity\\|end\\)\\>" nil t))
	    (equal "ENTITY" (upcase (match-string 1))))
       (vhdl-template-generic-list nil))
      ((or (save-excursion
	     (or (beginning-of-line)
		 (looking-at "^\\s-*\\w+\\s-*:\\s-*\\w+")))
	   (equal 'statement-cont (caar (vhdl-get-syntactic-context))))
       (vhdl-insert-keyword "GENERIC ")
       (vhdl-template-map start))
      (t (vhdl-template-generic-list nil t))))))

(defun vhdl-template-group ()
  "Insert group or group template declaration."
  (interactive)
  (let ((start (point)))
    (if (eq (vhdl-decision-query
	     "group" "(d)eclaration or (t)emplate declaration?" t) ?t)
	(vhdl-template-group-template)
      (vhdl-template-group-decl))))

(defun vhdl-template-group-decl ()
  "Insert group declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "GROUP ")
    (when (vhdl-template-field "name" " : " t start (point))
      (vhdl-template-field "template name" " (")
      (vhdl-template-field "constituent list" ");")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-group-template ()
  "Insert group template declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "GROUP ")
    (when (vhdl-template-field "template name" nil t start (point))
      (vhdl-insert-keyword " IS (")
      (vhdl-template-field "entity class list" ");")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-if ()
  "Insert a sequential if statement or an if-generate statement."
  (interactive)
  (if (vhdl-sequential-statement-p)
      (vhdl-template-if-then)
    (if (and (vhdl-standard-p 'ams)
	     (eq (vhdl-decision-query "if" "(g)enerate or (u)se?" t) ?u))
	(vhdl-template-if-use)
      (vhdl-template-if-generate))))

(defun vhdl-template-if-generate ()
  "Insert an if-generate."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label position)
    (vhdl-insert-keyword ": IF ")
    (setq position (point-marker))
    (goto-char start)
    (when (setq label (vhdl-template-field "label" nil t start position))
      (goto-char position)
      (when vhdl-conditions-in-parenthesis (insert "("))
      (vhdl-template-field "condition")
      (when vhdl-conditions-in-parenthesis (insert ")"))
      (vhdl-template-generate-body margin label))))

(defun vhdl-template-if-then-use (kind)
  "Insert a sequential if statement."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label)
    (if (or (not (eq vhdl-optional-labels 'all)) (vhdl-standard-p '87))
	(vhdl-insert-keyword "IF ")
      (vhdl-insert-keyword ": IF ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (when vhdl-conditions-in-parenthesis (insert "("))
    (when (vhdl-template-field "condition" nil t start (point))
      (when vhdl-conditions-in-parenthesis (insert ")"))
      (vhdl-insert-keyword
       (concat " " (if (eq kind 'then) "THEN" "USE") "\n\n"))
      (indent-to margin)
      (vhdl-insert-keyword "END IF")
      (when label (insert " " label))
      (insert ";")
      (forward-line -1)
      (indent-to (+ margin vhdl-basic-offset)))))

(defun vhdl-template-if-then ()
  "Insert a sequential if statement."
  (interactive)
  (vhdl-template-if-then-use 'then))

(defun vhdl-template-if-use ()
  "Insert a simultaneous if statement."
  (interactive)
  (vhdl-template-if-then-use 'use))

(defun vhdl-template-instance ()
  "Insert a component instantiation statement."
  (interactive)
  (vhdl-template-component-inst))

(defun vhdl-template-library ()
  "Insert a library specification."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name end-pos)
    (vhdl-insert-keyword "LIBRARY ")
    (when (setq name (vhdl-template-field "names" nil t start (point)))
      (insert ";")
      (unless (string-match "," name)
	(setq end-pos (point))
	(insert "\n")
	(indent-to margin)
	(vhdl-insert-keyword "USE ")
	(insert name)
	(vhdl-insert-keyword "..ALL;")
	(backward-char 5)
	(if (vhdl-template-field "package name")
	    (forward-char 5)
	  (delete-region end-pos (+ (point) 5)))))))

(defun vhdl-template-limit ()
  "Insert a limit."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "LIMIT ")
    (when (vhdl-template-field "quantity names | OTHERS | ALL" " : "
			       t start (point))
      (vhdl-template-field "type")
      (vhdl-insert-keyword " WITH ")
      (vhdl-template-field "real expression" ";"))))

(defun vhdl-template-loop ()
  "Insert a loop."
  (interactive)
  (let ((char (vhdl-decision-query nil "(w)hile, (f)or, or (b)are?" t)))
    (cond ((eq char ?w)
	   (vhdl-template-while-loop))
	  ((eq char ?f)
	   (vhdl-template-for-loop))
	  (t (vhdl-template-bare-loop)))))

(defun vhdl-template-bare-loop ()
  "Insert a loop."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label)
    (if (not (eq vhdl-optional-labels 'all))
	(vhdl-insert-keyword "LOOP ")
      (vhdl-insert-keyword ": LOOP ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (delete-char 1))
    (insert "\n\n")
    (indent-to margin)
    (vhdl-insert-keyword "END LOOP")
    (insert (if label (concat " " label ";") ";"))
    (forward-line -1)
    (indent-to (+ margin vhdl-basic-offset))))

(defun vhdl-template-map (&optional start optional secondary)
  "Insert a map specification with association list."
  (interactive)
  (let ((start (or start (point)))
	margin end-pos)
    (vhdl-insert-keyword "MAP (")
    (if (not vhdl-association-list-with-formals)
	(if (vhdl-template-field
	     (concat (and optional "[") "association list" (and optional "]"))
	     ")" (or (not secondary) optional)
	     (and (not secondary) start) (point))
	    t
	  (if (and optional secondary) (delete-region start (point)))
	  nil)
      (if vhdl-argument-list-indent
	  (setq margin (current-column))
	(setq margin (+ (current-indentation) vhdl-basic-offset))
	(insert "\n")
	(indent-to margin))
      (if (vhdl-template-field
	   (concat (and optional "[") "formal" (and optional "]"))
	   " => " (or (not secondary) optional)
	   (and (not secondary) start) (point))
	  (progn
	    (vhdl-template-field "actual" ",")
	    (setq end-pos (point))
	    (insert "\n")
	    (indent-to margin)
	    (while (vhdl-template-field "[formal]" " => " t)
	      (vhdl-template-field "actual" ",")
	      (setq end-pos (point))
	      (insert "\n")
	      (indent-to margin))
	    (delete-region end-pos (point))
	    (delete-backward-char 1)
	    (insert ")")
	    (when vhdl-auto-align (vhdl-align-region-groups start (point) 1))
	    t)
	(when (and optional secondary) (delete-region start (point)))
	nil))))

(defun vhdl-template-modify (&optional noerror)
  "Actualize modification date."
  (interactive)
  (vhdl-prepare-search-2
   (save-excursion
     (goto-char (point-min))
     (if (re-search-forward vhdl-modify-date-prefix-string nil t)
	 (progn (delete-region (point) (progn (end-of-line) (point)))
		(vhdl-template-insert-date))
       (unless noerror
	 (error (concat "Modification date prefix string \""
			vhdl-modify-date-prefix-string "\" not found")))))))

(defun vhdl-template-modify-noerror ()
  "Call `vhdl-template-modify' with NOERROR non-nil."
  (vhdl-template-modify t))

(defun vhdl-template-nature ()
  "Insert a nature declaration."
  (interactive)
  (let ((start (point))
	name mid-pos end-pos)
    (vhdl-insert-keyword "NATURE ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-insert-keyword " IS ")
      (let ((definition
	      (upcase
	       (or (vhdl-template-field
		    "across type | ARRAY | RECORD")
		   ""))))
	(cond ((equal definition "")
	       (insert ";"))
	      ((equal definition "ARRAY")
	       (kill-word -1)
	       (vhdl-template-array 'nature t))
	      ((equal definition "RECORD")
	       (setq mid-pos (point-marker))
	       (kill-word -1)
	       (vhdl-template-record 'nature name t))
	      (t
	       (vhdl-insert-keyword " ACROSS ")
	       (vhdl-template-field "through type")
	       (vhdl-insert-keyword " THROUGH ")
	       (vhdl-template-field "reference name")
	       (vhdl-insert-keyword " REFERENCE;")))
	(when mid-pos
	  (setq end-pos (point-marker))
	  (goto-char mid-pos)
	  (end-of-line))
	(vhdl-comment-insert-inline)
	(when end-pos (goto-char end-pos))))))

(defun vhdl-template-next ()
  "Insert a next statement."
  (interactive)
  (vhdl-insert-keyword "NEXT ")
  (unless (vhdl-template-field "[loop label]" nil t)
    (delete-char -1))
  (let ((position (point)))
    (vhdl-insert-keyword " WHEN ")
    (when vhdl-conditions-in-parenthesis (insert "("))
    (if (vhdl-template-field "[condition]" nil t)
	(when vhdl-conditions-in-parenthesis (insert ")"))
      (delete-region position (point)))
    (insert ";")))

(defun vhdl-template-others ()
  "Insert an others aggregate."
  (interactive)
  (let ((start (point)))
    (if (or (= (preceding-char) ?\() (not vhdl-template-invoked-by-hook))
	(progn (when (not vhdl-template-invoked-by-hook) (insert "("))
	       (vhdl-insert-keyword "OTHERS => '")
	       (when (vhdl-template-field "value" nil t start (point))
		 (insert "')")))
      (vhdl-insert-keyword "OTHERS "))))

(defun vhdl-template-package (&optional kind)
  "Insert a package specification or body."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name body position)
    (vhdl-insert-keyword "PACKAGE ")
    (setq body (if kind (eq kind 'body)
		 (eq (vhdl-decision-query nil "(d)eclaration or (b)ody?") ?b)))
    (when body
      (vhdl-insert-keyword "BODY ")
      (when (save-excursion
	      (vhdl-prepare-search-1
	       (re-search-backward "\\<package \\(\\w+\\) is\\>" nil t)))
	(insert (setq name (match-string 1)))))
    (when (or name
	      (setq name (vhdl-template-field "name" nil t start (point))))
      (vhdl-insert-keyword " IS\n")
      (when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n"))
      (indent-to (+ margin vhdl-basic-offset))
      (setq position (point))
      (insert "\n")
      (when (memq vhdl-insert-empty-lines '(unit all)) (insert "\n"))
      (indent-to margin)
      (vhdl-insert-keyword "END ")
      (unless (vhdl-standard-p '87)
	(vhdl-insert-keyword (concat "PACKAGE " (and body "BODY "))))
      (insert (or name "") ";")
      (goto-char position))))

(defun vhdl-template-package-decl ()
  "Insert a package specification."
  (interactive)
  (vhdl-template-package 'decl))

(defun vhdl-template-package-body ()
  "Insert a package body."
  (interactive)
  (vhdl-template-package 'body))

(defun vhdl-template-port ()
  "Insert a port declaration, or port map in instantiation statements."
  (interactive)
  (let ((start (point)))
    (vhdl-prepare-search-1
     (cond
      ((and (save-excursion		; entity declaration
	      (re-search-backward "^\\(entity\\|end\\)\\>" nil t))
	    (equal "ENTITY" (upcase (match-string 1))))
       (vhdl-template-port-list nil))
      ((or (save-excursion
	     (or (beginning-of-line)
		 (looking-at "^\\s-*\\w+\\s-*:\\s-*\\w+")))
	   (equal 'statement-cont (caar (vhdl-get-syntactic-context))))
       (vhdl-insert-keyword "PORT ")
       (vhdl-template-map start))
      (t (vhdl-template-port-list nil))))))

(defun vhdl-template-procedural ()
  "Insert a procedural."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	(case-fold-search t)
	label)
    (vhdl-insert-keyword "PROCEDURAL ")
    (when (memq vhdl-optional-labels '(process all))
      (goto-char start)
      (insert ": ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (unless (vhdl-standard-p '87) (vhdl-insert-keyword "IS"))
    (vhdl-template-begin-end "PROCEDURAL" label margin)
    (vhdl-comment-block)))

(defun vhdl-template-procedure (&optional kind)
  "Insert a procedure declaration or body."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	name)
    (vhdl-insert-keyword "PROCEDURE ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-template-argument-list)
      (if (if kind (eq kind 'body)
	    (eq (vhdl-decision-query nil "(d)eclaration or (b)ody?") ?b))
	  (progn (vhdl-insert-keyword " IS")
		 (when vhdl-auto-align
		   (vhdl-align-region-groups start (point) 1))
		 (end-of-line)
		 (vhdl-template-begin-end
		  (unless (vhdl-standard-p '87) "PROCEDURE")
		  name margin)
		 (vhdl-comment-block))
	(insert ";")
	(when vhdl-auto-align (vhdl-align-region-groups start (point) 1))
	(end-of-line)))))

(defun vhdl-template-procedure-decl ()
  "Insert a procedure declaration."
  (interactive)
  (vhdl-template-procedure 'decl))

(defun vhdl-template-procedure-body ()
  "Insert a procedure body."
  (interactive)
  (vhdl-template-procedure 'body))

(defun vhdl-template-process (&optional kind)
  "Insert a process."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	label seq input-signals clock reset final-pos)
    (setq seq (if kind (eq kind 'seq)
		(eq (vhdl-decision-query
		     "process" "(c)ombinational or (s)equential?" t) ?s)))
    (vhdl-insert-keyword "PROCESS ")
    (when (memq vhdl-optional-labels '(process all))
      (goto-char start)
      (insert ": ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (insert "(")
    (if (not seq)
	(unless (setq input-signals
		      (vhdl-template-field "[sensitivity list]" ")" t))
	  (setq input-signals "")
	  (delete-char -2))
      (setq clock (or (and (not (equal "" vhdl-clock-name))
			   (progn (insert vhdl-clock-name) vhdl-clock-name))
		      (vhdl-template-field "clock name") "<clock>"))
      (when (eq vhdl-reset-kind 'async)
	(insert ", ")
	(setq reset (or (and (not (equal "" vhdl-reset-name))
			     (progn (insert vhdl-reset-name) vhdl-reset-name))
			(vhdl-template-field "reset name") "<reset>")))
      (insert ")"))
    (unless (vhdl-standard-p '87) (vhdl-insert-keyword " IS"))
    (vhdl-template-begin-end "PROCESS" label margin)
    (when seq (setq reset (vhdl-template-seq-process clock reset)))
    (when vhdl-prompt-for-comments
      (setq final-pos (point-marker))
      (vhdl-prepare-search-2
       (when (and (re-search-backward "\\<begin\\>" nil t)
		  (re-search-backward "\\<process\\>" nil t))
	 (end-of-line -0)
	 (if (bobp)
	     (progn (insert "\n") (forward-line -1))
	   (insert "\n"))
	 (indent-to margin)
	 (insert "-- purpose: ")
	 (if (not (vhdl-template-field "[description]" nil t))
	     (vhdl-line-kill-entire)
	   (insert "\n")
	   (indent-to margin)
	   (insert "-- type   : ")
	   (insert (if seq "sequential" "combinational") "\n")
	   (indent-to margin)
	   (insert "-- inputs : ")
	   (if (not seq)
	       (insert input-signals)
	     (insert clock ", ")
	     (when reset (insert reset ", "))
	     (unless (vhdl-template-field "[signal names]" nil t)
	       (delete-char -2)))
	   (insert "\n")
	   (indent-to margin)
	   (insert "-- outputs: ")
	   (vhdl-template-field "[signal names]" nil t))))
      (goto-char final-pos))))

(defun vhdl-template-process-comb ()
  "Insert a combinational process."
  (interactive)
  (vhdl-template-process 'comb))

(defun vhdl-template-process-seq ()
  "Insert a sequential process."
  (interactive)
  (vhdl-template-process 'seq))

(defun vhdl-template-quantity ()
  "Insert a quantity declaration."
  (interactive)
  (if (vhdl-in-argument-list-p)
      (let ((start (point)))
	(vhdl-insert-keyword "QUANTITY ")
	(when (vhdl-template-field "names" nil t start (point))
	  (insert " : ")
	  (vhdl-template-field "[IN | OUT]" " " t)
	  (vhdl-template-field "type")
	  (insert ";")
	  (vhdl-comment-insert-inline)))
    (let ((char (vhdl-decision-query
		 "quantity" "(f)ree, (b)ranch, or (s)ource quantity?" t)))
      (cond ((eq char ?f) (vhdl-template-quantity-free))
	    ((eq char ?b) (vhdl-template-quantity-branch))
	    ((eq char ?s) (vhdl-template-quantity-source))
	    (t (vhdl-template-undo (point) (point)))))))

(defun vhdl-template-quantity-free ()
  "Insert a free quantity declaration."
  (interactive)
  (vhdl-insert-keyword "QUANTITY ")
  (vhdl-template-field "names")
  (insert " : ")
  (vhdl-template-field "type")
  (let ((position (point)))
    (insert " := ")
    (unless (vhdl-template-field "[initialization]" nil t)
      (delete-region position (point)))
    (insert ";")
    (vhdl-comment-insert-inline)))

(defun vhdl-template-quantity-branch ()
  "Insert a branch quantity declaration."
  (interactive)
  (let (position)
    (vhdl-insert-keyword "QUANTITY ")
    (when (vhdl-template-field "[across names]" " " t)
      (vhdl-insert-keyword "ACROSS "))
    (when (vhdl-template-field "[through names]" " " t)
      (vhdl-insert-keyword "THROUGH "))
    (vhdl-template-field "plus terminal name")
    (setq position (point))
    (vhdl-insert-keyword " TO ")
    (unless (vhdl-template-field "[minus terminal name]" nil t)
      (delete-region position (point)))
    (insert ";")
    (vhdl-comment-insert-inline)))

(defun vhdl-template-quantity-source ()
  "Insert a source quantity declaration."
  (interactive)
  (vhdl-insert-keyword "QUANTITY ")
  (vhdl-template-field "names")
  (insert " : ")
  (vhdl-template-field "type" " ")
  (if (eq (vhdl-decision-query nil "(s)pectrum or (n)oise?") ?n)
      (progn (vhdl-insert-keyword "NOISE ")
	     (vhdl-template-field "power expression"))
    (vhdl-insert-keyword "SPECTRUM ")
    (vhdl-template-field "magnitude expression" ", ")
    (vhdl-template-field "phase expression"))
  (insert ";")
  (vhdl-comment-insert-inline))

(defun vhdl-template-record (kind &optional name secondary)
  "Insert a record type declaration."
  (interactive)
  (let ((margin (current-column))
	(start (point))
	(first t))
    (vhdl-insert-keyword "RECORD\n")
    (indent-to (+ margin vhdl-basic-offset))
    (when (or (vhdl-template-field "element names"
				   nil (not secondary) start (point))
	      secondary)
      (while (or first (vhdl-template-field "[element names]" nil t))
	(insert " : ")
	(vhdl-template-field (if (eq kind 'type) "type" "nature") ";")
	(vhdl-comment-insert-inline)
	(insert "\n")
	(indent-to (+ margin vhdl-basic-offset))
	(setq first nil))
      (kill-line -0)
      (indent-to margin)
      (vhdl-insert-keyword "END RECORD")
      (unless (vhdl-standard-p '87) (and name (insert " " name)))
      (insert ";")
      (when vhdl-auto-align (vhdl-align-region-groups start (point) 1)))))

(defun vhdl-template-report ()
  "Insert a report statement."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "REPORT ")
    (if (equal "\"\"" (vhdl-template-field
		       "string expression" nil t start (point) t))
	(delete-backward-char 2)
      (setq start (point))
      (vhdl-insert-keyword " SEVERITY ")
      (unless (vhdl-template-field "[NOTE | WARNING | ERROR | FAILURE]" nil t)
	(delete-region start (point)))
      (insert ";"))))

(defun vhdl-template-return ()
  "Insert a return statement."
  (interactive)
  (vhdl-insert-keyword "RETURN ")
  (unless (vhdl-template-field "[expression]" nil t)
    (delete-char -1))
  (insert ";"))

(defun vhdl-template-selected-signal-asst ()
  "Insert a selected signal assignment."
  (interactive)
  (let ((margin (current-indentation))
	(start (point))
	(choices t))
    (let ((position (point)))
      (vhdl-insert-keyword " SELECT ")
      (goto-char position))
    (vhdl-insert-keyword "WITH ")
    (when (vhdl-template-field "selector expression"
			       nil t start (+ (point) 7))
      (forward-word 1)
      (delete-char 1)
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-template-field "target signal" " <= ")
;      (vhdl-template-field "[GUARDED] [TRANSPORT]")
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (vhdl-template-field "waveform")
      (vhdl-insert-keyword " WHEN ")
      (vhdl-template-field "choices" ",")
      (insert "\n")
      (indent-to (+ margin vhdl-basic-offset))
      (while (and choices (vhdl-template-field "[waveform]" nil t))
	(vhdl-insert-keyword " WHEN ")
	(if (setq choices (vhdl-template-field "[choices]" "," t))
	    (progn (insert "\n") (indent-to (+ margin vhdl-basic-offset)))
	  (vhdl-insert-keyword "OTHERS")))
      (when choices
	(fixup-whitespace)
	(delete-char -2))
      (insert ";")
      (when vhdl-auto-align (vhdl-align-region-groups start (point) 1)))))

(defun vhdl-template-signal ()
  "Insert a signal declaration."
  (interactive)
  (let ((start (point))
	(in-arglist (vhdl-in-argument-list-p)))
    (vhdl-insert-keyword "SIGNAL ")
    (when (vhdl-template-field "names" nil t start (point))
      (insert " : ")
      (when in-arglist (vhdl-template-field "[IN | OUT | INOUT]" " " t))
      (vhdl-template-field "type")
      (if in-arglist
	  (progn (insert ";")
		 (vhdl-comment-insert-inline))
	(let ((position (point)))
	  (insert " := ")
	  (unless (vhdl-template-field "[initialization]" nil t)
	    (delete-region position (point)))
	  (insert ";")
	  (vhdl-comment-insert-inline))))))

(defun vhdl-template-subnature ()
  "Insert a subnature declaration."
  (interactive)
  (let ((start (point))
	position)
    (vhdl-insert-keyword "SUBNATURE ")
    (when (vhdl-template-field "name" nil t start (point))
      (vhdl-insert-keyword " IS ")
      (vhdl-template-field "nature" " (")
      (if (vhdl-template-field "[index range]" nil t)
	  (insert ")")
	(delete-char -2))
      (setq position (point))
      (vhdl-insert-keyword " TOLERANCE ")
      (if (equal "\"\"" (vhdl-template-field "[string expression]"
					     nil t nil nil t))
	  (delete-region position (point))
	(vhdl-insert-keyword " ACROSS ")
	(vhdl-template-field "string expression" nil nil nil nil t)
	(vhdl-insert-keyword " THROUGH"))
      (insert ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-subprogram-body ()
  "Insert a subprogram body."
  (interactive)
  (if (eq (vhdl-decision-query nil "(p)rocedure or (f)unction?" t) ?f)
      (vhdl-template-function-body)
    (vhdl-template-procedure-body)))

(defun vhdl-template-subprogram-decl ()
  "Insert a subprogram declaration."
  (interactive)
  (if (eq (vhdl-decision-query nil "(p)rocedure or (f)unction?" t) ?f)
      (vhdl-template-function-decl)
    (vhdl-template-procedure-decl)))

(defun vhdl-template-subtype ()
  "Insert a subtype declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "SUBTYPE ")
    (when (vhdl-template-field "name" nil t start (point))
      (vhdl-insert-keyword " IS ")
      (vhdl-template-field "type" " ")
      (unless
	  (vhdl-template-field "[RANGE value range | ( index range )]" nil t)
	(delete-char -1))
      (insert ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-terminal ()
  "Insert a terminal declaration."
  (interactive)
  (let ((start (point)))
    (vhdl-insert-keyword "TERMINAL ")
    (when (vhdl-template-field "names" nil t start (point))
      (insert " : ")
      (vhdl-template-field "nature")
      (insert ";")
      (vhdl-comment-insert-inline))))

(defun vhdl-template-type ()
  "Insert a type declaration."
  (interactive)
  (let ((start (point))
	name mid-pos end-pos)
    (vhdl-insert-keyword "TYPE ")
    (when (setq name (vhdl-template-field "name" nil t start (point)))
      (vhdl-insert-keyword " IS ")
      (let ((definition
	      (upcase
	       (or (vhdl-template-field
		    "[scalar type | ARRAY | RECORD | ACCESS | FILE]" nil t)
		   ""))))
	(cond ((equal definition "")
	       (delete-backward-char 4)
	       (insert ";"))
	      ((equal definition "ARRAY")
	       (kill-word -1)
	       (vhdl-template-array 'type t))
	      ((equal definition "RECORD")
	       (setq mid-pos (point-marker))
	       (kill-word -1)
	       (vhdl-template-record 'type name t))
	      ((equal definition "ACCESS")
	       (insert " ")
	       (vhdl-template-field "type" ";"))
	      ((equal definition "FILE")
	       (vhdl-insert-keyword " OF ")
	       (vhdl-template-field "type" ";"))
	      (t (insert ";")))
	(when mid-pos
	  (setq end-pos (point-marker))
	  (goto-char mid-pos)
	  (end-of-line))
	(vhdl-comment-insert-inline)
	(when end-pos (goto-char end-pos))))))

(defun vhdl-template-use ()
  "Insert a use clause."
  (interactive)
  (let ((start (point)))
    (vhdl-prepare-search-1
     (vhdl-insert-keyword "USE ")
     (when (save-excursion (beginning-of-line) (looking-at "^\\s-*use\\>"))
       (vhdl-insert-keyword "..ALL;")
       (backward-char 6)
       (when (vhdl-template-field "library name" nil t start (+ (point) 6))
	 (forward-char 1)
	 (vhdl-template-field "package name")
	 (forward-char 5))))))

(defun vhdl-template-variable ()
  "Insert a variable declaration."
  (interactive)
  (let ((start (point))
	(in-arglist (vhdl-in-argument-list-p)))
    (vhdl-prepare-search-2
     (if (or (save-excursion
	       (and (re-search-backward
		     "\\<function\\|procedure\\|process\\|procedural\\|end\\>"
		     nil t)
		    (not (progn (backward-word 1) (looking-at "\\<end\\>")))))
	     (save-excursion (backward-word 1) (looking-at "\\<shared\\>")))
	 (vhdl-insert-keyword "VARIABLE ")
       (vhdl-insert-keyword "SHARED VARIABLE ")))
    (when (vhdl-template-field "names" nil t start (point))
      (insert " : ")
      (when in-arglist (vhdl-template-field "[IN | OUT | INOUT]" " " t))
      (vhdl-template-field "type")
      (if in-arglist
	  (progn (insert ";")
		 (vhdl-comment-insert-inline))
	(let ((position (point)))
	  (insert " := ")
	  (unless (vhdl-template-field "[initialization]" nil t)
	    (delete-region position (point)))
	  (insert ";")
	  (vhdl-comment-insert-inline))))))

(defun vhdl-template-wait ()
  "Insert a wait statement."
  (interactive)
  (vhdl-insert-keyword "WAIT ")
  (unless (vhdl-template-field
	   "[ON sensitivity list] [UNTIL condition] [FOR time expression]"
	   nil t)
    (delete-char -1))
  (insert ";"))

(defun vhdl-template-when ()
  "Indent correctly if within a case statement."
  (interactive)
  (let ((position (point))
	margin)
    (vhdl-prepare-search-2
     (if (and (= (current-column) (current-indentation))
	      (re-search-forward "\\<end\\>" nil t)
	      (looking-at "\\s-*\\<case\\>"))
	 (progn
	   (setq margin (current-indentation))
	   (goto-char position)
	   (delete-horizontal-space)
	   (indent-to (+ margin vhdl-basic-offset)))
       (goto-char position)))
    (vhdl-insert-keyword "WHEN ")))

(defun vhdl-template-while-loop ()
  "Insert a while loop."
  (interactive)
  (let* ((margin (current-indentation))
	 (start (point))
	 label)
    (if (not (eq vhdl-optional-labels 'all))
	(vhdl-insert-keyword "WHILE ")
      (vhdl-insert-keyword ": WHILE ")
      (goto-char start)
      (setq label (vhdl-template-field "[label]" nil t))
      (unless label (delete-char 2))
      (forward-word 1)
      (forward-char 1))
    (when vhdl-conditions-in-parenthesis (insert "("))
    (when (vhdl-template-field "condition" nil t start (point))
      (when vhdl-conditions-in-parenthesis (insert ")"))
      (vhdl-insert-keyword " LOOP\n\n")
      (indent-to margin)
      (vhdl-insert-keyword "END LOOP")
      (insert (if label (concat " " label ";") ";"))
      (forward-line -1)
      (indent-to (+ margin vhdl-basic-offset)))))

(defun vhdl-template-with ()
  "Insert a with statement (i.e. selected signal assignment)."
  (interactive)
  (vhdl-prepare-search-1
   (if (save-excursion
	 (re-search-backward "\\(\\<limit\\>\\|;\\)")
	 (equal ";" (match-string 1)))
       (vhdl-template-selected-signal-asst)
     (vhdl-insert-keyword "WITH "))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Special templates

(defun vhdl-template-clocked-wait ()
  "Insert a wait statement for rising/falling clock edge."
  (interactive)
  (let ((start (point))
	clock)
    (vhdl-insert-keyword "WAIT UNTIL ")
    (when (setq clock
		(or (and (not (equal "" vhdl-clock-name))
			 (progn (insert vhdl-clock-name) vhdl-clock-name))
		    (vhdl-template-field "clock name" nil t start (point))))
      (insert "'event")
      (vhdl-insert-keyword " AND ")
      (insert clock)
      (insert
       " = " (if vhdl-clock-rising-edge vhdl-one-string vhdl-zero-string) ";")
      (vhdl-comment-insert-inline
       (concat (if vhdl-clock-rising-edge "rising" "falling")
	       " clock edge")))))

(defun vhdl-template-seq-process (clock reset)
  "Insert a template for the body of a sequential process."
  (let ((margin (current-indentation))
	position)
    (vhdl-insert-keyword "IF ")
    (when (eq vhdl-reset-kind 'async)
      (insert reset " = "
	      (if vhdl-reset-active-high vhdl-one-string vhdl-zero-string))
      (vhdl-insert-keyword " THEN")
      (vhdl-comment-insert-inline
       (concat "asynchronous reset (active "
	       (if vhdl-reset-active-high "high" "low") ")"))
      (insert "\n") (indent-to (+ margin vhdl-basic-offset))
      (setq position (point))
      (insert "\n") (indent-to margin)
      (vhdl-insert-keyword "ELSIF "))
    (if (eq vhdl-clock-edge-condition 'function)
	(insert (if vhdl-clock-rising-edge "rising" "falling")
		"_edge(" clock ")")
      (insert clock "'event")
      (vhdl-insert-keyword " AND ")
      (insert clock " = "
	      (if vhdl-clock-rising-edge vhdl-one-string vhdl-zero-string)))
    (vhdl-insert-keyword " THEN")
    (vhdl-comment-insert-inline
     (concat (if vhdl-clock-rising-edge "rising" "falling") " clock edge"))
    (insert "\n") (indent-to (+ margin vhdl-basic-offset))
    (when (eq vhdl-reset-kind 'sync)
      (vhdl-insert-keyword "IF ")
      (setq reset (or (and (not (equal "" vhdl-reset-name))
			   (progn (insert vhdl-reset-name) vhdl-reset-name))
		      (vhdl-template-field "reset name") "<reset>"))
      (insert " = "
	      (if vhdl-reset-active-high vhdl-one-string vhdl-zero-string))
      (vhdl-insert-keyword " THEN")
      (vhdl-comment-insert-inline
       (concat "synchronous reset (active "
	       (if vhdl-reset-active-high "high" "low") ")"))
      (insert "\n") (indent-to (+ margin (* 2 vhdl-basic-offset)))
      (setq position (point))
      (insert "\n") (indent-to (+ margin vhdl-basic-offset))
      (vhdl-insert-keyword "ELSE")
      (insert "\n") (indent-to (+ margin (* 2 vhdl-basic-offset)))
      (insert "\n") (indent-to (+ margin vhdl-basic-offset))
      (vhdl-insert-keyword "END IF;"))
    (when (eq vhdl-reset-kind 'none)
      (setq position (point)))
    (insert "\n") (indent-to margin)
    (vhdl-insert-keyword "END IF;")
    (goto-char position)
    reset))

(defun vhdl-template-standard-package (library package)
  "Insert specification of a standard package.  Include a library
specification, if not already there."
  (let ((margin (current-indentation)))
    (unless (equal library "std")
      (save-excursion
	(vhdl-prepare-search-1
	 (and (not (bobp))
	      (re-search-backward
	       (concat "^\\s-*\\(library\\s-+\\(\\(\\w\\|\\s_\\)+,\\s-+\\)*"
		       library "\\|end\\)\\>") nil t))))
      (unless (and (match-string 1) (string-match "library" (match-string 1)))
	(vhdl-insert-keyword "LIBRARY ")
	(insert library ";\n")
	(indent-to margin)))
    (vhdl-insert-keyword "USE ")
    (insert library "." package)
    (vhdl-insert-keyword ".ALL;")))

(defun vhdl-template-package-math-complex ()
  "Insert specification of `math_complex' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "math_complex"))

(defun vhdl-template-package-math-real ()
  "Insert specification of `math_real' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "math_real"))

(defun vhdl-template-package-numeric-bit ()
  "Insert specification of `numeric_bit' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "numeric_bit"))

(defun vhdl-template-package-numeric-std ()
  "Insert specification of `numeric_std' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "numeric_std"))

(defun vhdl-template-package-std-logic-1164 ()
  "Insert specification of `std_logic_1164' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_1164"))

(defun vhdl-template-package-std-logic-arith ()
  "Insert specification of `std_logic_arith' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_arith"))

(defun vhdl-template-package-std-logic-misc ()
  "Insert specification of `std_logic_misc' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_misc"))

(defun vhdl-template-package-std-logic-signed ()
  "Insert specification of `std_logic_signed' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_signed"))

(defun vhdl-template-package-std-logic-textio ()
  "Insert specification of `std_logic_textio' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_textio"))

(defun vhdl-template-package-std-logic-unsigned ()
  "Insert specification of `std_logic_unsigned' package."
  (interactive)
  (vhdl-template-standard-package "ieee" "std_logic_unsigned"))

(defun vhdl-template-package-textio ()
  "Insert specification of `textio' package."
  (interactive)
  (vhdl-template-standard-package "std" "textio"))

(defun vhdl-template-directive (directive)
  "Insert directive."
  (unless (= (current-indentation) (current-column))
    (delete-horizontal-space)
    (insert "  "))
  (insert "-- pragma " directive))

(defun vhdl-template-directive-translate-on ()
  "Insert directive 'translate_on'."
  (interactive)
  (vhdl-template-directive "translate_on"))

(defun vhdl-template-directive-translate-off ()
  "Insert directive 'translate_off'."
  (interactive)
  (vhdl-template-directive "translate_off"))

(defun vhdl-template-directive-synthesis-on ()
  "Insert directive 'synthesis_on'."
  (interactive)
  (vhdl-template-directive "synthesis_on"))

(defun vhdl-template-directive-synthesis-off ()
  "Insert directive 'synthesis_off'."
  (interactive)
  (vhdl-template-directive "synthesis_off"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Header and footer templates

(defun vhdl-template-header (&optional file-title)
  "Insert a VHDL file header."
  (interactive)
  (unless (equal vhdl-file-header "")
    (let (pos)
      (save-excursion
	(goto-char (point-min))
	(vhdl-insert-string-or-file vhdl-file-header)
	(setq pos (point-marker)))
      (vhdl-template-replace-header-keywords
       (point-min-marker) pos file-title))))

(defun vhdl-template-footer ()
  "Insert a VHDL file footer."
  (interactive)
  (unless (equal vhdl-file-footer "")
    (let (pos)
      (save-excursion
	(goto-char (point-max))
	(insert "\n")
	(setq pos (point-marker))
	(vhdl-insert-string-or-file vhdl-file-footer)
	(unless (= (preceding-char) ?\n)
	  (insert "\n")))
      (vhdl-template-replace-header-keywords pos (point-max-marker)))))

(defun vhdl-template-replace-header-keywords (beg end &optional file-title
						  is-model)
  "Replace keywords in header and footer."
  (let ((project-title (or (nth 0 (aget vhdl-project-alist vhdl-project)) ""))
	(project-desc (or (nth 9 (aget vhdl-project-alist vhdl-project)) ""))
	pos)
    (vhdl-prepare-search-2
     (save-excursion
       (goto-char beg)
       (while (search-forward "<projectdesc>" end t)
	 (replace-match project-desc t t))
       (goto-char beg)
       (while (search-forward "<filename>" end t)
	 (replace-match (buffer-name) t t))
       (goto-char beg)
       (while (search-forward "<copyright>" end t)
	 (replace-match vhdl-copyright-string t t))
       (goto-char beg)
       (while (search-forward "<author>" end t)
	 (replace-match "" t t)
	 (insert (user-full-name))
	 (when user-mail-address (insert "  <" user-mail-address ">")))
       (goto-char beg)
       (while (search-forward "<login>" end t)
	 (replace-match (user-login-name) t t))
       (goto-char beg)
       (while (search-forward "<project>" end t)
	 (replace-match project-title t t))
       (goto-char beg)
       (while (search-forward "<company>" end t)
	 (replace-match vhdl-company-name t t))
       (goto-char beg)
       (while (search-forward "<platform>" end t)
	 (replace-match vhdl-platform-spec t t))
       (goto-char beg)
       ;; Replace <RCS> with $, so that RCS for the source is
       ;; not over-enthusiastic with replacements
       (while (search-forward "<RCS>" end t)
	 (replace-match "$" nil t))
       (goto-char beg)
       (while (search-forward "<date>" end t)
	 (replace-match "" t t)
	 (vhdl-template-insert-date))
       (goto-char beg)
       (while (search-forward "<year>" end t)
	 (replace-match (format-time-string "%Y" nil) t t))
       (goto-char beg)
       (when file-title
	 (while (search-forward "<title string>" end t)
	   (replace-match file-title t t))
	 (goto-char beg))
       (let (string)
	 (while
	     (re-search-forward "<\\(\\(\\w\\|\\s_\\)*\\) string>" end t)
	   (setq string (read-string (concat (match-string 1) ": ")))
	   (replace-match string t t)))
       (goto-char beg)
       (when (and (not is-model) (search-forward "<cursor>" end t))
	 (replace-match "" t t)
	 (setq pos (point))))
     (when pos (goto-char pos))
     (unless is-model
       (when (or (not project-title) (equal project-title ""))
	 (message "You can specify a project title in user option `vhdl-project-alist'"))
       (when (or (not project-desc) (equal project-desc ""))
	 (message "You can specify a project description in user option `vhdl-project-alist'"))
       (when (equal vhdl-platform-spec "")
	 (message "You can specify a platform in user option `vhdl-platform-spec'"))
       (when (equal vhdl-company-name "")
	 (message "You can specify a company name in user option `vhdl-company-name'"))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Comment templates and functions

(defun vhdl-comment-indent ()
  "Indent comments."
  (let* ((position (point))
	 (col
	  (progn
	    (forward-line -1)
	    (if (re-search-forward "--" position t)
		(- (current-column) 2)	; existing comment at bol stays there
	      (goto-char position)
	      (skip-chars-backward " \t")
	      (max comment-column	; else indent to comment column
		   (1+ (current-column))))))) ; except leave at least one space
    (goto-char position)
    col))

(defun vhdl-comment-insert ()
  "Start a comment at the end of the line.
If on line with code, indent at least `comment-column'.
If starting after end-comment-column, start a new line."
  (interactive)
  (when (> (current-column) end-comment-column) (newline-and-indent))
  (if (or (looking-at "\\s-*$") ; end of line
	  (and (not unread-command-events) ; called with key binding or menu
	       (not (end-of-line))))
      (let (margin)
	(while (= (preceding-char) ?-) (delete-char -1))
	(setq margin (current-column))
	(delete-horizontal-space)
	(if (bolp)
	    (progn (indent-to margin) (insert "--"))
	  (insert "  ")
	  (indent-to comment-column)
	  (insert "--"))
	(if (not unread-command-events) (insert " ")))
    ;; else code following current point implies commenting out code
    (let (next-input code)
      (while (= (preceding-char) ?-) (delete-char -2))
      (while (= (setq next-input (read-char)) 13) ; CR
	(insert "--") ; or have a space after it?
	(forward-char -2)
	(forward-line 1)
	(message "Enter CR if commenting out a line of code.")
	(setq code t))
      (when (not code)
	(insert "--")) ; hardwire to 1 space or use vhdl-basic-offset?
      (setq unread-command-events
	    (list (vhdl-character-to-event next-input)))))) ; pushback the char

(defun vhdl-comment-display (&optional line-exists)
  "Add 2 comment lines at the current indent, making a display comment."
  (interactive)
  (let ((margin (current-indentation)))
    (when (not line-exists) (vhdl-comment-display-line))
    (insert "\n") (indent-to margin)
    (insert "\n") (indent-to margin)
    (vhdl-comment-display-line)
    (end-of-line -0)
    (insert "-- ")))

(defun vhdl-comment-display-line ()
  "Displays one line of dashes."
  (interactive)
  (while (= (preceding-char) ?-) (delete-char -2))
  (let* ((col (current-column))
	 (len (- end-comment-column col)))
    (insert-char ?- len)))

(defun vhdl-comment-append-inline ()
  "Append empty inline comment to current line."
  (interactive)
  (end-of-line)
  (delete-horizontal-space)
  (insert "  ")
  (indent-to comment-column)
  (insert "-- "))

(defun vhdl-comment-insert-inline (&optional string always-insert)
  "Insert inline comment."
  (when (or (and string (or vhdl-self-insert-comments always-insert))
	    (and (not string) vhdl-prompt-for-comments))
    (let ((position (point)))
      (insert "  ")
      (indent-to comment-column)
      (insert "-- ")
      (if (not (or (and string (progn (insert string) t))
		   (vhdl-template-field "[comment]" nil t)))
	  (delete-region position (point))
	(while (= (preceding-char) ? ) (delete-backward-char 1))
; 	(when (> (current-column) end-comment-column)
; 	  (setq position (point-marker))
; 	  (re-search-backward "-- ")
; 	  (insert "\n")
; 	  (indent-to comment-column)
; 	  (goto-char position))
	))))

(defun vhdl-comment-block ()
  "Insert comment for code block."
  (when vhdl-prompt-for-comments
    (let ((final-pos (point-marker)))
      (vhdl-prepare-search-2
       (when (and (re-search-backward "^\\s-*begin\\>" nil t)
		  (re-search-backward "\\<\\(architecture\\|block\\|function\\|procedure\\|process\\|procedural\\)\\>" nil t))
	 (let (margin)
	   (back-to-indentation)
	   (setq margin (current-column))
	   (end-of-line -0)
	   (if (bobp)
	       (progn (insert "\n") (forward-line -1))
	     (insert "\n"))
	   (indent-to margin)
	   (insert "-- purpose: ")
	   (unless (vhdl-template-field "[description]" nil t)
	     (vhdl-line-kill-entire)))))
      (goto-char final-pos))))

(defun vhdl-comment-uncomment-region (beg end &optional arg)
  "Comment out region if not commented out, uncomment otherwise."
  (interactive "r\nP")
  (save-excursion
    (goto-char (1- end))
    (end-of-line)
    (setq end (point-marker))
    (goto-char beg)
    (beginning-of-line)
    (setq beg (point))
    (if (looking-at comment-start)
	(comment-region beg end -1)
      (comment-region beg end))))

(defun vhdl-comment-uncomment-line (&optional arg)
  "Comment out line if not commented out, uncomment otherwise."
  (interactive "p")
  (save-excursion
    (beginning-of-line)
    (let ((position (point)))
      (forward-line (or arg 1))
      (vhdl-comment-uncomment-region position (point)))))

(defun vhdl-comment-kill-region (beg end)
  "Kill comments in region."
  (interactive "r")
  (save-excursion
    (goto-char end)
    (setq end (point-marker))
    (goto-char beg)
    (beginning-of-line)
    (while (< (point) end)
      (if (looking-at "^\\(\\s-*--.*\n\\)")
	  (progn (delete-region (match-beginning 1) (match-end 1)))
	(beginning-of-line 2)))))

(defun vhdl-comment-kill-inline-region (beg end)
  "Kill inline comments in region."
  (interactive "r")
  (save-excursion
    (goto-char end)
    (setq end (point-marker))
    (goto-char beg)
    (beginning-of-line)
    (while (< (point) end)
      (when (looking-at "^.*[^ \t\n-]+\\(\\s-*--.*\\)$")
	(delete-region (match-beginning 1) (match-end 1)))
      (beginning-of-line 2))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Subtemplates

(defun vhdl-template-begin-end (construct name margin &optional empty-lines)
  "Insert a begin ... end pair with optional name after the end.
Point is left between them."
  (let (position)
    (insert "\n")
    (when (or empty-lines (eq vhdl-insert-empty-lines 'all)) (insert "\n"))
    (indent-to margin)
    (vhdl-insert-keyword "BEGIN")
    (when (and (or construct name) vhdl-self-insert-comments)
      (insert "  --")
      (when construct (insert " ") (vhdl-insert-keyword construct))
      (when name (insert " " name)))
    (insert "\n")
    (when (or empty-lines (eq vhdl-insert-empty-lines 'all)) (insert "\n"))
    (indent-to (+ margin vhdl-basic-offset))
    (setq position (point))
    (insert "\n")
    (when (or empty-lines (eq vhdl-insert-empty-lines 'all)) (insert "\n"))
    (indent-to margin)
    (vhdl-insert-keyword "END")
    (when construct (insert " ") (vhdl-insert-keyword construct))
    (insert (if name (concat " " name) "") ";")
    (goto-char position)))

(defun vhdl-template-argument-list (&optional is-function)
  "Read from user a procedure or function argument list."
  (insert " (")
  (let ((margin (current-column))
	(start (point))
	(end-pos (point))
	not-empty interface semicolon-pos)
    (when (not vhdl-argument-list-indent)
      (setq margin (+ (current-indentation) vhdl-basic-offset))
      (insert "\n")
      (indent-to margin))
    (setq interface (vhdl-template-field
		     (concat "[CONSTANT | SIGNAL"
			     (unless is-function " | VARIABLE") "]") " " t))
    (while (vhdl-template-field "[names]" nil t)
      (setq not-empty t)
      (insert " : ")
      (when (not is-function)
	(if (and interface (equal (upcase interface) "CONSTANT"))
	    (vhdl-insert-keyword "IN ")
	  (vhdl-template-field "[IN | OUT | INOUT]" " " t)))
      (vhdl-template-field "type")
      (setq semicolon-pos (point))
      (insert ";")
      (vhdl-comment-insert-inline)
      (setq end-pos (point))
      (insert "\n")
      (indent-to margin)
      (setq interface (vhdl-template-field
		       (concat "[CONSTANT | SIGNAL"
			       (unless is-function " | VARIABLE") "]") " " t)))
    (delete-region end-pos (point))
    (when semicolon-pos (goto-char semicolon-pos))
    (if not-empty
	(progn (delete-char 1) (insert ")"))
      (delete-backward-char 2))))

(defun vhdl-template-generic-list (optional &optional no-value)
  "Read from user a generic spec argument list."
  (let (margin
	(start (point)))
    (vhdl-insert-keyword "GENERIC (")
    (setq margin (current-column))
    (when (not vhdl-argument-list-indent)
      (let ((position (point)))
	(back-to-indentation)
	(setq margin (+ (current-column) vhdl-basic-offset))
	(goto-char position)
	(insert "\n")
	(indent-to margin)))
    (let ((vhdl-generics (vhdl-template-field
			  (concat (and optional "[") "name"
				  (and no-value "s") (and optional "]"))
			  nil optional)))
      (if (not vhdl-generics)
	  (if optional
	      (progn (vhdl-line-kill-entire) (end-of-line -0)
		     (when (not vhdl-argument-list-indent)
		       (vhdl-line-kill-entire) (end-of-line -0)))
	    (vhdl-template-undo start (point))
	    nil )
	(insert " : ")
	(let (semicolon-pos end-pos)
	  (while vhdl-generics
	    (vhdl-template-field "type")
	    (if no-value
		(progn (setq semicolon-pos (point))
		       (insert ";"))
	      (insert " := ")
	      (unless (vhdl-template-field "[value]" nil t)
		(delete-char -4))
	      (setq semicolon-pos (point))
	      (insert ";"))
	    (vhdl-comment-insert-inline)
	    (setq end-pos (point))
 	    (insert "\n")
	    (indent-to margin)
	    (setq vhdl-generics (vhdl-template-field
				 (concat "[name" (and no-value "s") "]")
				 " : " t)))
	  (delete-region end-pos (point))
	  (goto-char semicolon-pos)
	  (insert ")")
	  (end-of-line)
	  (when vhdl-auto-align (vhdl-align-region-groups start (point) 1))
	  t)))))

(defun vhdl-template-port-list (optional)
  "Read from user a port spec argument list."
  (let ((start (point))
	margin vhdl-ports object)
    (vhdl-insert-keyword "PORT (")
    (setq margin (current-column))
    (when (not vhdl-argument-list-indent)
      (let ((position (point)))
	(back-to-indentation)
	(setq margin (+ (current-column) vhdl-basic-offset))
	(goto-char position)
	(insert "\n")
	(indent-to margin)))
    (when (vhdl-standard-p 'ams)
      (setq object (vhdl-template-field "[SIGNAL | TERMINAL | QUANTITY]"
					" " t)))
    (setq vhdl-ports (vhdl-template-field
		      (concat (and optional "[") "names" (and optional "]"))
		      nil optional))
    (if (not vhdl-ports)
	(if optional
	    (progn (vhdl-line-kill-entire) (end-of-line -0)
		   (when (not vhdl-argument-list-indent)
		     (vhdl-line-kill-entire) (end-of-line -0)))
	  (vhdl-template-undo start (point))
	  nil)
      (insert " : ")
      (let (semicolon-pos end-pos)
	(while vhdl-ports
	  (cond ((or (null object) (equal "SIGNAL" (upcase object)))
		 (vhdl-template-field "IN | OUT | INOUT" " "))
		((equal "QUANTITY" (upcase object))
		 (vhdl-template-field "[IN | OUT]" " " t)))
	  (vhdl-template-field
	   (if (and object (equal "TERMINAL" (upcase object)))
		    "nature" "type"))
	  (setq semicolon-pos (point))
	  (insert ";")
	  (vhdl-comment-insert-inline)
	  (setq end-pos (point))
	  (insert "\n")
	  (indent-to margin)
	  (when (vhdl-standard-p 'ams)
	    (setq object (vhdl-template-field "[SIGNAL | TERMINAL | QUANTITY]"
					      " " t)))
	  (setq vhdl-ports (vhdl-template-field "[names]" " : " t)))
	(delete-region end-pos (point))
	(goto-char semicolon-pos)
	(insert ")")
	(end-of-line)
	(when vhdl-auto-align (vhdl-align-region-groups start end-pos 1))
	t))))

(defun vhdl-template-generate-body (margin label)
  "Insert body for generate template."
  (vhdl-insert-keyword " GENERATE")
;   (if (not (vhdl-standard-p '87))
;       (vhdl-template-begin-end "GENERATE" label margin)
  (insert "\n\n")
  (indent-to margin)
  (vhdl-insert-keyword "END GENERATE ")
  (insert label ";")
  (end-of-line 0)
  (indent-to (+ margin vhdl-basic-offset)))

(defun vhdl-template-insert-date ()
  "Insert date in appropriate format."
  (interactive)
  (insert
   (cond
    ;; 'american, 'european, 'scientific kept for backward compatibility
    ((eq vhdl-date-format 'american) (format-time-string "%m/%d/%Y" nil))
    ((eq vhdl-date-format 'european) (format-time-string "%d.%m.%Y" nil))
    ((eq vhdl-date-format 'scientific) (format-time-string "%Y/%m/%d" nil))
    (t (format-time-string vhdl-date-format nil)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Help functions

(defun vhdl-electric-space (count)
  "Expand abbreviations and self-insert space(s), do indent-new-comment-line
if in comment and past end-comment-column."
  (interactive "p")
  (cond ((vhdl-in-comment-p)
	 (self-insert-command count)
	 (cond ((>= (current-column) (+ 2 end-comment-column))
		(backward-char 1)
		(skip-chars-backward "^ \t\n")
		(indent-new-comment-line)
		(skip-chars-forward "^ \t\n")
		(forward-char 1))
	       ((>= (current-column) end-comment-column)
		(indent-new-comment-line))
	       (t nil)))
	((or (and (>= (preceding-char) ?a) (<= (preceding-char) ?z))
	     (and (>= (preceding-char) ?A) (<= (preceding-char) ?Z)))
	 (vhdl-prepare-search-1
	  (expand-abbrev))
	 (self-insert-command count))
	(t (self-insert-command count))))

(defun vhdl-template-field (prompt &optional follow-string optional
				   begin end is-string default)
  "Prompt for string and insert it in buffer with optional FOLLOW-STRING.
If OPTIONAL is nil, the prompt is left if an empty string is inserted.  If
an empty string is inserted, return nil and call `vhdl-template-undo' for
the region between BEGIN and END.  IS-STRING indicates whether a string
with double-quotes is to be inserted.  DEFAULT specifies a default string."
  (let ((position (point))
	string)
    (insert "<" prompt ">")
    (setq string
	  (condition-case ()
	      (read-from-minibuffer (concat prompt ": ")
				    (or (and is-string '("\"\"" . 2)) default)
				    vhdl-minibuffer-local-map)
	    (quit (if (and optional begin end)
		      (progn (beep) "")
		    (keyboard-quit)))))
    (when (or (not (equal string "")) optional)
      (delete-region position (point)))
    (when (and (equal string "") optional begin end)
      (vhdl-template-undo begin end)
      (message "Template aborted"))
    (when (not (equal string ""))
      (insert string)
      (vhdl-fix-case-region-1 position (point) vhdl-upper-case-keywords
			      vhdl-keywords-regexp))
    (when (or (not (equal string "")) (not optional))
      (insert (or follow-string "")))
    (if (equal string "") nil string)))

(defun vhdl-decision-query (string prompt &optional optional)
  "Query a decision from the user."
  (let ((start (point)))
    (when string (vhdl-insert-keyword (concat string " ")))
    (message prompt)
    (let ((char (read-char)))
      (delete-region start (point))
      (if (and optional (eq char ?\r))
	  (progn (insert " ")
		 (unexpand-abbrev)
		 (throw 'abort "Template aborted"))
	char))))

(defun vhdl-insert-keyword (keyword)
  "Insert KEYWORD and adjust case."
  (insert (if vhdl-upper-case-keywords (upcase keyword) (downcase keyword))))

(defun vhdl-case-keyword (keyword)
  "Adjust case of KEYWORD."
  (if vhdl-upper-case-keywords (upcase keyword) (downcase keyword)))

(defun vhdl-case-word (num)
  "Adjust case or following NUM words."
  (if vhdl-upper-case-keywords (upcase-word num) (downcase-word num)))

(defun vhdl-minibuffer-tab (&optional prefix-arg)
  "If preceeding character is part of a word or a paren then hippie-expand,
else if right of non whitespace on line then tab-to-tab-stop,
else indent line in proper way for current major mode (used for word
completion in VHDL minibuffer)."
  (interactive "P")
  (cond ((= (char-syntax (preceding-char)) ?w)
	 (let ((case-fold-search (not vhdl-word-completion-case-sensitive))
	       (case-replace nil)
	       (hippie-expand-only-buffers
		(or (and (boundp 'hippie-expand-only-buffers)
			 hippie-expand-only-buffers)
		    '(vhdl-mode))))
	   (vhdl-expand-abbrev prefix-arg)))
	((or (= (preceding-char) ?\() (= (preceding-char) ?\)))
	 (let ((case-fold-search (not vhdl-word-completion-case-sensitive))
	       (case-replace nil))
	   (vhdl-expand-paren prefix-arg)))
	((> (current-column) (current-indentation))
 	 (tab-to-tab-stop))
	(t (if (eq indent-line-function 'indent-to-left-margin)
	       (insert-tab prefix-arg)
	     (if prefix-arg
		 (funcall indent-line-function prefix-arg)
	       (funcall indent-line-function))))))

(defun vhdl-template-search-prompt ()
  "Search for left out template prompts and query again."
  (interactive)
  (vhdl-prepare-search-2
   (when (or (re-search-forward
	      (concat "<\\(" vhdl-template-prompt-syntax "\\)>") nil t)
	     (re-search-backward
	      (concat "<\\(" vhdl-template-prompt-syntax "\\)>") nil t))
     (let ((string (match-string 1)))
       (replace-match "")
       (vhdl-template-field string)))))

(defun vhdl-template-undo (begin end)
  "Undo aborted template by deleting region and unexpanding the keyword."
  (cond (vhdl-template-invoked-by-hook
	 (goto-char end)
	 (insert " ")
	 (delete-region begin end)
	 (unexpand-abbrev))
	(t (delete-region begin end))))

(defun vhdl-insert-string-or-file (string)
  "Insert STRING or file contents if STRING is an existing file name."
  (unless (equal string "")
    (l