idlwave / idlwave.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
;;; idlwave.el --- IDL editing mode for GNU Emacs
;; Copyright (c) 1999, 2000, 2001,2002 Free Software Foundation

;; Author: Carsten Dominik <dominik@astro.uva.nl>
;;         Chris Chase <chase@att.com>
;; Maintainer: J.D. Smith <jdsmith@as.arizona.edu>
;; Version: 4.15
;; Date: $Date$
;; Keywords: languages

;; 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:

;; In distant past, based on pascal.el.  Though bears little
;; resemblance to that now.
;;
;; Incorporates many ideas, such as abbrevs, action routines, and
;; continuation line indenting, from wave.el.
;; wave.el original written by Lubos Pochman, Precision Visuals, Boulder.
;;
;; See the mode description ("C-h m" in idlwave-mode or "C-h f idlwave-mode")
;; for features, key bindings, and info.
;; Also, Info format documentation is available with `M-x idlwave-info'
;;
;; New versions of IDLWAVE, documentation, and more information
;; available from:
;;                 http://idlwave.org
;;
;; INSTALLATION
;; ============
;;
;; Follow the instructions in the INSTALL file of the distribution.
;; In short, put this file on your load path and add the following
;; lines to your .emacs file:
;;
;; (autoload 'idlwave-mode "idlwave" "IDLWAVE Mode" t)
;; (autoload 'idlwave-shell "idlw-shell" "IDLWAVE Shell" t)
;; (setq auto-mode-alist (cons '("\\.pro\\'" . idlwave-mode) auto-mode-alist))
;;
;;
;; SOURCE
;; ======
;;
;; The newest version of this file is available from the maintainer's
;; Webpage.
;;
;;   http://idlwave.org
;;
;; DOCUMENTATION
;; =============
;;
;; IDLWAVE is documented online in info format.
;; A printable version of the documentation is available from the
;; maintainers webpage (see under SOURCE)
;;
;; 
;; ACKNOWLEDGMENTS
;; ===============
;;
;;  Thanks to the following people for their contributions and comments:
;;
;;    Ulrik Dickow <dickow@nbi.dk>
;;    Eric E. Dors <edors@lanl.gov>
;;    Stein Vidar H. Haugan <s.v.h.haugan@astro.uio.no>
;;    David Huenemoerder <dph@space.mit.edu>
;;    Kevin Ivory <Kevin.Ivory@linmpi.mpg.de>
;;    Xuyong Liu <liu@stsci.edu>
;;    Simon Marshall <Simon.Marshall@esrin.esa.it>
;;    Laurent Mugnier <mugnier@onera.fr>
;;    Lubos Pochman <lubos@rsinc.com>
;;    Bob Portmann <portmann@al.noaa.gov>
;;    Patrick M. Ryan <pat@jaameri.gsfc.nasa.gov>
;;    Marty Ryba <ryba@ll.mit.edu>
;;    Phil Williams <williams@irc.chmcc.org>
;;    Phil Sterne <sterne@dublin.llnl.gov>
;;
;; CUSTOMIZATION:
;; =============
;;
;; IDLWAVE has extensive customize support - so if you want to learn
;; about the variables which control the behavior of the mode, use
;; `M-x idlwave-customize'.
;;
;; You can set your own preferred values with Customize, or with Lisp
;; code in .emacs.  For an example of what to put into .emacs, check
;; the TexInfo documentation or see a complete .emacs at
;; http://idlwave.org.
;;
;; KNOWN PROBLEMS:
;; ==============
;;
;;   IDLWAVE support for the IDL-derived PV-WAVE CL language of Visual
;;   Numerics, Inc. is growing less and less complete as the two
;;   languages grow increasingly apart.  The mode probably shouldn't
;;   even have "WAVE" in it's title, but it's catchy, and required to
;;   avoid conflict with the CORBA idl.el mode.  Caveat WAVEor.
;;
;;   Moving the point backwards in conjunction with abbrev expansion
;;   does not work as I would like it, but this is a problem with
;;   emacs abbrev expansion done by the self-insert-command.  It ends
;;   up inserting the character that expanded the abbrev after moving
;;   point backward, e.g., "\cl" expanded with a space becomes
;;   "LONG( )" with point before the close paren.  This is solved by
;;   using a temporary function in `post-command-hook' - not pretty, 
;;   but it works.
;;
;;   Tabs and spaces are treated equally as whitespace when filling a
;;   comment paragraph.  To accomplish this, tabs are permanently
;;   replaced by spaces in the text surrounding the paragraph, which
;;   may be an undesirable side-effect.  Replacing tabs with spaces is
;;   limited to comments only and occurs only when a comment
;;   paragraph is filled via `idlwave-fill-paragraph'.
;;
;;   Avoid muti-statement lines (using "&") on block begin and end
;;   lines.  Multi-statement lines can mess up the formatting, for
;;   example, multiple end statements on a line: endif & endif.
;;   Using "&" outside of block begin/end lines should be okay.
;;
;;   Determining the expression at point for printing and other
;;   examination commands is somewhat rough: currently only fairly
;;   simple entities are found.  You can always drag-select or examine
;;   a region.
;;
;;   When forcing completion of method keywords, the initial
;;   query for a method has multiple entries for some methods.  Would
;;   be too difficult to fix this hardly used case.
;;

;;; Code:

(eval-when-compile (require 'cl))

(eval-and-compile
  ;; Kludge to allow `defcustom' for Emacs 19.
  (condition-case () (require 'custom) (error nil))
  (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
      nil ;; We've got what we needed
    ;; We have the old or no custom-library, hack around it!
    (defmacro defgroup (&rest args) nil)
    (defmacro defcustom (var value doc &rest args) 
      `(defvar ,var ,value ,doc))))

(defgroup idlwave nil
  "Major mode for editing IDL .pro files"
  :tag "IDLWAVE"
  :link '(url-link :tag "Home Page" 
		   "http://idlwave.org")
  :link '(emacs-commentary-link :tag "Commentary in idlw-shell.el"
				"idlw-shell.el")
  :link '(emacs-commentary-link :tag "Commentary in idlwave.el" "idlwave.el")
  :link '(custom-manual "(idlwave)Top")
  :prefix "idlwave"
  :group 'languages)

;;; Variables for indentation behavior ---------------------------------------

(defgroup idlwave-code-formatting nil
  "Indentation and formatting options for IDLWAVE mode."
  :group 'idlwave)

(defcustom idlwave-main-block-indent 0
  "*Extra indentation for the main block of code.
That is the block between the FUNCTION/PRO statement and the END
statement for that program unit."
  :group 'idlwave-code-formatting
  :type 'integer)

(defcustom idlwave-block-indent 4
  "*Extra indentation applied to block lines.
If you change this, you probably also want to change `idlwave-end-offset'."
  :group 'idlwave-code-formatting
  :type 'integer)

(defcustom idlwave-end-offset -4
  "*Extra indentation applied to block END lines.
A value equal to negative `idlwave-block-indent' will make END lines
line up with the block BEGIN lines."
  :group 'idlwave-code-formatting
  :type 'integer)

(defcustom idlwave-continuation-indent 2
  "*Extra indentation applied to continuation lines.
This extra offset applies to the first of a set of continuation lines.
The following lines receive the same indentation as the first."
  :group 'idlwave-code-formatting
  :type 'integer)

(defcustom idlwave-max-extra-continuation-indent 20
  "*Maximum additional indentation for special continuation indent.
Several special indentations are tried to help line up continuation
lines in routine calls or definitions, other statements with
parentheses, or assignment statements.  This variable specifies a
maximum amount by which this special indentation can exceed the
standard continuation indentation, otherwise defaulting to a fixed
offset.  Set to 0 to effectively disable all special continuation
indentation, or to a large number (like 100) to enable it in all
cases.  See also `idlwave-indent-top-open-paren', which can override
this variable."
  :group 'idlwave-code-formatting
  :type 'integer)

(defcustom idlwave-indent-to-open-paren t
  "*Non-nil means, indent continuation lines to innermost open
parenthesis.  This indentation occurs even if otherwise disallowed by
`idlwave-max-extra-continuation-indent'.  Matching parens and the
interleaving args are lined up.  Example:

  x = function_a(function_b(function_c( a, b, [1,2,3, $
                                               4,5,6 $
                                              ], $
                                        c, d $
                                      )))

When this variable is nil, paren alignment may still occur, based on
the value of `max-extra-continuation-indent', which, if zero, would
yield:

  x = function_a(function_b(function_c( a, b, [1,2,3, $
     4,5,6 $
     ], $
     c, d $
     )))"
 :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-hanging-indent t
  "*If set non-nil then comment paragraphs are indented under the
hanging indent given by `idlwave-hang-indent-regexp' match in the first line
of the paragraph."
  :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-hang-indent-regexp "- "
  "*Regular expression matching the position of the hanging indent
in the first line of a comment paragraph. The size of the indent
extends to the end of the match for the regular expression."
  :group 'idlwave-code-formatting
  :type 'regexp)

(defcustom idlwave-use-last-hang-indent nil
  "*If non-nil then use last match on line for `idlwave-indent-regexp'."
  :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-fill-comment-line-only t
  "*If non-nil then auto fill will only operate on comment lines."
  :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-auto-fill-split-string t
  "*If non-nil then auto fill will split strings with the IDL `+' operator.
When the line end falls within a string, string concatenation with the 
'+' operator will be used to distribute a long string over lines.  
If nil and a string is split then a terminal beep and warning are issued.

This variable is ignored when `idlwave-fill-comment-line-only' is
non-nil, since in this case code is not auto-filled."
  :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-split-line-string t
  "*If non-nil then `idlwave-split-line' will split strings with `+'.
When the splitting point of a line falls inside a string, split the string
using the `+' string concatenation operator.  If nil and a string is
split then a terminal beep and warning are issued."
  :group 'idlwave-code-formatting
  :type 'boolean)

(defcustom idlwave-no-change-comment ";;;"
  "*The indentation of a comment that starts with this regular
expression will not be changed. Note that the indentation of a comment
at the beginning of a line is never changed."
  :group 'idlwave-code-formatting
  :type 'string)

(defcustom idlwave-begin-line-comment nil
  "*A comment anchored at the beginning of line.
A comment matching this regular expression will not have its
indentation changed.  If nil the default is \"^;\", i.e., any line
beginning with a \";\".  Expressions for comments at the beginning of
the line should begin with \"^\"."
  :group 'idlwave-code-formatting
  :type '(choice (const :tag "Any line beginning with `;'" nil)
		 'regexp))

(defcustom idlwave-code-comment ";;[^;]"
  "*A comment that starts with this regular expression on a line by
itself is indented as if it is a part of IDL code.  As a result if
the comment is not preceded by whitespace it is unchanged."
  :group 'idlwave-code-formatting
  :type 'regexp)

;; Comments not matching any of the above will be indented as a
;; right-margin comment, i.e., to a minimum of `comment-column'.


;;; Routine Info and Completion ---------------------------------------

(defgroup idlwave-routine-info nil
  "Routine Info options for IDLWAVE mode."
  :group 'idlwave)


(defcustom idlwave-init-rinfo-when-idle-after 10
  "*Seconds of idle time before routine info is automatically initialized.
Initializing the routine info can take long, in particular if a large
library catalog is involved.  When Emacs is idle for more than the number
of seconds specified by this variable, it starts the initialization.
The process is split into five steps, in order to keep possible work 
interruption as short as possible.  If one of the steps finishes, and no
user input has arrived in the mean time, initialization proceeds immediately
to the next step.
A good value for this variable is about 1/3 of the time initialization
take in you setup.  So if you have a fast machine and no problems with a slow network connection, don't hesitate to set this to 2 seconds.
A Value of 0 means, don't initialize automatically."
  :group 'idlwave-routine-info
  :type 'number)

(defcustom idlwave-scan-all-buffers-for-routine-info t
  "*Non-nil means, scan buffers for IDL programs when updating info.
The scanning is done by the command `idlwave-update-routine-info'.
The following values are allowed:

nil       Don't scan any buffers.
t         Scan all idlwave-mode buffers in the current editing session.
current   Scan only the current buffer, but no other buffers."
  :group 'idlwave-routine-info
  :type '(choice
	  (const :tag "No buffer" nil)
	  (const :tag "All buffers" t)
	  (const :tag "Current buffer only" 'current)))

(defcustom idlwave-query-shell-for-routine-info t
  "*Non-nil means query the shell for info about compiled routines.
Querying the shell is useful to get information about compiled modules,
and it is turned on by default.  However, when you have a complete library
scan, this is not necessary."
  :group 'idlwave-routine-info
  :type 'boolean)

(defcustom idlwave-auto-routine-info-updates
  '(find-file save-buffer kill-buffer compile-buffer)
  "*Controls under what circumstances routine info is updated automatically.
Possible values:
nil       Never
t         All available
(...)     A list of circumstances. Allowed members are:
           find-file       Add info for new IDLWAVE buffers.
           save-buffer     Update buffer info when buffer is saved
           kill-buffer     Remove buffer info when buffer gets killed
           compile-buffer  Update shell info after `idlwave-shell-save-and...'"
  :group 'idlwave-routine-info
  :type '(choice
	  (const :tag "Never" nil)
	  (const :tag "As often as possible" t)
	  (set :tag "Checklist" :greedy t
	       (const :tag "When visiting a file" find-file)
	       (const :tag "When saving a buffer" save-buffer)
	       (const :tag "After a buffer was killed" kill-buffer)
	       (const :tag "After a buffer was compiled successfully, update shell info" compile-buffer))))
	       
(defcustom idlwave-rinfo-max-source-lines 5
  "*Maximum number of source files displayed in the Routine Info window.
When an integer, it is the maximum number of source files displayed.
t means to show all source files."
  :group 'idlwave-routine-info
  :type 'integer)

(defcustom idlwave-library-path nil
  "Library path for Windows and MacOS.  Not needed under Unix.
When selecting the directories to scan for IDL library routine info,
IDLWAVE can under UNIX query the shell for the exact search path.
However, under Windows and MacOS, the IDLWAVE shell does not work.  In this
case, this variable specifies the path where IDLWAVE can find library files.
The shell will only be asked when this variable is nil.
The value is a list of directories.  A directory preceeded by a `+' will
be searched recursively.  If you set this variable on a UNIX system, the shell
will not be asked.
See also `idlwave-system-directory'."
  :group 'idlwave-routine-info
  :type '(repeat (directory)))

(defcustom idlwave-system-directory ""
  "The IDL system directory for Windows and MacOS.  Not needed under UNIX.
Set this to the value of the `!DIR' system variable in IDL.  IDLWAVE uses
this to find out which of the library routines belong to the official system
library.  All files inside the `lib' subdirectory are considered system
library files - so don't install private stuff in this directory.
On UNIX systems, IDLWAVE queries the shell for the value of `!DIR'.
See also `idlwave-library-path'."
  :group 'idlwave-routine-info
  :type 'directory)

(defcustom idlwave-libinfo-file "~/.idlcat.el"
  "*File for routine information of the IDL library.
When this points to a file, the file will be loaded when IDLWAVE first
accesses routine info (or does completion).
When you scan the library with `idlwave-create-libinfo-file', this file
will be used to store the result."
  :group 'idlwave-routine-info
  :type 'file)

(defcustom idlwave-special-lib-alist nil
  "Alist of regular expressions matching special library directories.
When listing routine source locations, IDLWAVE gives a short hint where
the file defining the routine is located.  By default it lists `SystemLib' 
for routines in the system library `!DIR/lib' and `Library' for anything
else.  This variable can define additional types.  The car of each entry
is a regular expression matching the file name (they normally will match
on the path).  The cdr is the string to be used as identifier.  Max 10
chars are allowed."
  :group 'idlwave-routine-info
  :type '(repeat
	  (cons regexp string)))

(defgroup idlwave-online-help nil
  "Online Help options for IDLWAVE mode."
  :group 'idlwave)

(defcustom idlwave-help-directory ""
  "The directory where idlw-help.txt and idlw-help.el are stored."
  :group 'idlwave-online-help
  :type 'file)

(defcustom idlwave-help-use-dedicated-frame t
  "*Non-nil means, use a separate frame for Online Help if possible."
  :group 'idlwave-online-help
  :type 'boolean)

(defcustom idlwave-help-frame-parameters
  '((height . 20) (unsplittable . t))
  "The frame parameters for the special Online Help frame.
See also `idlwave-help-use-dedicated-frame'.
If you do not set the frame width here, the value specified in
`idlw-help.el' will be used."
  :group 'idlwave-online-help
  :type '(repeat
	  (cons symbol sexp)))

(defcustom idlwave-max-popup-menu-items 20
  "Maximum number of items per pane in popup menus.
Currently only used for class selection during completion help."
  :group 'idlwave-online-help
  :type 'integer)

(defcustom idlwave-extra-help-function 'idlwave-help-with-source
  "The function to call for online help if the normal help fails.
Online help works only for system routines which are described in the
IDL manuals.  A function may be specified to access help from other sources.

The function must accept four arguments: NAME, TYPE, CLASS, KEYWORD.
The Help buffer is current when this function is called, and the help
text should be loaded into this buffer.  If help is found, the function
should return the buffer position which should be used as `window-start'
in the help window.  Also, the variable `idlwave-help-mode-line-indicator'
should be set to a useful string, which will be displayed in the mode line
of the help window.  If should also set the variable `idlwave-min-frame-width'
to a positive integer.  IDLWAVE will ensure that the help frame is at
least that many columns wide.
Failure to find help should be indicated by throwing an error.

When this variable is non-nil, IDLWAVE will allow the mouse-3 help click
for every routine and keyword, even though the item may not be highlighted
in blue (indicating the availability of system documentation).

The default value for this function is `idlwave-help-with-source' which
loads the routine source file into the help buffer.  If you try to write
a different function which accesses a special help file or so, it is
probably a good idea to still call this function as a fallback."
  :group 'idlwave-online-help
  :type 'symbol)

(defcustom idlwave-help-fontify-source-code nil
  "*Non-nil means, fontify source code displayed as help like normal code."
  :group 'idlwave-online-help
  :type 'boolean)

(defcustom idlwave-help-source-try-header t
  "*Non-nil means, try to find help in routine header when displaying source.
Routines which are not documented in the system manual use their source as
help text.  When this variable is non-nil, we try to find a description of
the help item in the first routine doclib header above the routine definition.
If the variable is nil, or if we cannot find/parse the header, the routine
definition is displayed instead."
  :group 'idlwave-online-help
  :type 'boolean)

(defface idlwave-help-link-face
  '((((class color)) (:foreground "Blue"))
    (t (:weight bold)))
  "Face for highlighting links into IDLWAVE online help."
  :group 'idlwave-online-help)

(defcustom idlwave-help-activate-links-aggressively t
  "*Non-nil means, make all possible links in help active.
This just activates all words which are also a help topic - some links may
be misleading."
  :group 'idlwave-online-help
  :type 'boolean)
  

(defgroup idlwave-completion nil
  "Completion options for IDLWAVE mode."
  :prefix "idlwave"
  :group 'idlwave)

(eval-and-compile
  (defconst idlwave-tmp
    '(choice :tag "by applying the function"
      (const upcase)
      (const downcase)
      (const capitalize)
      (const preserve)
      (symbol :tag "Other"))))

(defcustom idlwave-completion-case '((routine . upcase)
				     (keyword . upcase)
				     (class   . preserve)
				     (method  . preserve))
  "Association list setting the case of completed words.

This variable determines the case (UPPER/lower/Capitalized...) of
words inserted into the buffer by completion.  The preferred case can
be specified separately for routine names, keywords, classes and
methods. 
This alist should therefore have entries for `routine' (normal
functions and procedures, i.e. non-methods), `keyword', `class', and
`method'.  Plausible values are

upcase      upcase whole word, like `BOX_CURSOR'
downcase    downcase whole word, like `read_ppm'
capitalize  capitalize each part, like `Widget_Control'
preserve    preserve case as is, like `IDLgrView'

The value can also be any Emacs Lisp function which transforms the
case of characters in a string.

A value of `preserve' means that the case of the completed word is
identical to the way it was written in the definition statement of the
routine.  This was implemented to allow for mixed-case completion, in
particular of object classes and methods.
If a completable word is defined in multiple locations, the meaning of
`preserve' is not unique since the different definitions might be
cased differently.  Therefore IDLWAVE always takes the case of the
*first* definition it encounters during routine info collection and
uses the case derived from it consistently.

Note that a lowercase-only string in the buffer will always be completed in
lower case (but see the variable `idlwave-completion-force-default-case').

After changing this variable, you need to either restart Emacs or press
`C-u C-c C-i' to update the internal lists."
  :group 'idlwave-completion
  :type `(repeat
	  (cons (symbol :tag "Derive completion case for")
		,idlwave-tmp)))

(defcustom idlwave-completion-force-default-case nil
  "*Non-nil means, completion will always honor `idlwave-completion-case'.
When nil, only the completion of a mixed case or upper case string
will honor the default settings in `idlwave-completion-case', while
the completion of lower case strings will be completed entirely in
lower case."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-complete-empty-string-as-lower-case nil
  "*Non-nil means, the empty string is considered downcase for completion.
The case of what is already in the buffer determines the case of completions.
When this variable is non-nil, the empty string is considered to be downcase.
Completing on the empty string then offers downcase versions of the possible
completions."
  :group 'idlwave-completion
  :type 'boolean)

(defvar idlwave-default-completion-case-is-down nil
  "Obsolete variable.  See `idlwave-complete-empty-string-as-lower-case' and
`idlwave-completion-case'.")

(defcustom idlwave-buffer-case-takes-precedence nil
  "*Non-nil means, the case of tokens in buffers dominates over system stuff.
To make this possible, we need to re-case everything each time we update
the routine info from the buffers.  This is slow.
The default is to consider the case given in the system and library files
first which makes updating much faster."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-highlight-help-links-in-completion t
  "*Non-nil means, highlight completions for which system help is available.
Help can then be accessed with mouse-3.
This option is only effective when the online help system is installed."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-support-inheritance t
  "Non-nil means, treat inheritance with completion, online help etc.
When nil, IDLWAVE only knows about the native methods and tags of a class,
not about inherited ones."
  :group 'idlwave-routine-info
  :type 'boolean)

(defcustom idlwave-keyword-class-inheritance '("^[gs]etproperty$" "^init$")
  "List of regular expressions for class-driven keyword inheritance.
Keyword inheritance is often tied to class inheritance by \"chaining\"
up the class tree.  While it cannot be assumed that the presence of an
_EXTRA or _REF_EXTRA symbol guarantees such chaining will occur, for
certain methods this assumption is almost always true.  The methods
for which to assume this can be set here."
  :group 'idlwave-routine-info
  :type '(repeat (regexp :tag "Match method:")))
  

(defcustom idlwave-completion-show-classes 1
  "*Number of classes to show when completing object methods and keywords.
When completing methods or keywords for an object with unknown class,
the *Completions* buffer will show the legal classes for each completion
like this:

MyMethod <Class1,Class2,Class3>

The value of this variable may be nil to inhibit display, or an integer to
indicate the maximum number of classes to display.

On XEmacs, a full list of classes will also be placed into a `help-echo'
property on the competion items, so that the list of classes for the current
item is displayed in the echo area.  If the value of this variable is a
negative integer, the `help-echo' property will be suppressed."
  :group 'idlwave-completion
  :type '(choice (const :tag "Don't show" nil)
		 (integer :tag "Number of classes shown" 1)))

(defcustom idlwave-completion-fontify-classes t
  "*Non-nil means, fontify the classes in completions buffer.
This makes it easier to distinguish the completion items from the extra
class info listed.  See `idlwave-completion-show-classes'."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-query-class '((method-default . nil)
				 (keyword-default . nil))
  "Association list governing specification of object classes for completion.

When IDLWAVE tries to complete object-oriented methods, it usually
cannot determine the class of a given object from context.  In order
to provide the user with a correct list of methods or keywords, it
needs to determine the appropriate class.  IDLWAVE has two ways of
doing this (well, three ways if you count the shell... see
`idlwave-shell-query-for-class'):

1. Combine the items of all available classes which contain this
   method for the purpose of completion.  So when completing a method,
   all methods of all known classes are available, and when completing
   a keyword, all keywords allowed for this method in any class are
   shown.  This behavior is very much like normal completion and is
   therefore the default.  It works much better than one might think -
   only for the INIT, GETPROPERTY and SETPROPERTY the keyword lists
   become uncomfortably long.  See also
   `idlwave-completion-show-classes'.

2. The second possibility is to ask the user on each occasion.  To
   make this less interruptive, IDLWAVE can store the class as a text
   property on the object operator `->'.  For a given object in the
   source code, class selection will then be needed only once
   - for example to complete the method.  Keywords to the method can
   then be completed directly, because the class is already known.
   You will have to turn on the storage of the selected class
   explicitly with the variable `idlwave-store-inquired-class'.

This variable allows you to configure IDLWAVE's method and
method-keyword completion behavior.  Its value is an alist, which
should contain at least two elements: (method-default . VALUE) and
(keyword-default . VALUE), where VALUE is either t or nil.  These
specify if the class should be found during method and keyword
completion, respectively.

The alist may have additional entries specifying exceptions from the 
keyword completion rule for specific methods, like INIT or
GETPROPERTY.  In order to turn on class specification for the INIT
method, add an entry (\"INIT\" . t).  The method name must be ALL-CAPS."
  :group 'idlwave-completion
  :type '(list
	  (cons (const method-default)
		(boolean :tag "Determine class when completing METHODS    "))
	  (cons (const keyword-default)
		(boolean :tag "Determine class when completing KEYWORDS   "))
	  (repeat
	   :tag "Exceptions to defaults"
	   :inline t
	   (cons (string  :tag "MODULE" :value "")
		 (boolean :tag "Determine class for this method")))))

(defcustom idlwave-store-inquired-class nil
  "*Non-nil means, store class of a method call as text property on `->'.
IDLWAVE sometimes has to ask the user for the class associated with a
particular object method call.  This happens during the commands
`idlwave-routine-info' and `idlwave-complete', depending upon the
value of the variable `idlwave-query-class'.

When you specify a class, this information can be stored as a text
property on the `->' arrow in the source code, so that during the same 
editing session, IDLWAVE will not have to ask again.  When this
variable is non-nil, IDLWAVE will store and reuse the class information.
The class stored can be checked and removed with `\\[idlwave-routine-info]'
on the arrow.

The default of this variable is nil, since the result of commands then
is more predictable.  However, if you know what you are doing, it can
be nice to turn this on.

An arrow which knows the class will be highlighted with
`idlwave-class-arrow-face'.  The command \\[idlwave-routine-info]
displays (with prefix arg: deletes) the class stored on the arrow
at point."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-class-arrow-face 'bold
  "*Face to highlight object operator arrows `->' which carry a class property.
When IDLWAVE stores a class name as text property on an object arrow
(see variable `idlwave-store-inquired-class', it highlights the arrow
with this font in order to remind the user that this arrow is special."
  :group 'idlwave-completion
  :type 'symbol)

(defcustom idlwave-resize-routine-help-window t
  "*Non-nil means, resize the Routine-info *Help* window to fit the content."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-keyword-completion-adds-equal t
  "*Non-nil means, completion automatically adds `=' after completed keywords."
  :group 'idlwave-completion
  :type 'boolean)

(defcustom idlwave-function-completion-adds-paren t
  "*Non-nil means, completion automatically adds `(' after completed function.
nil means, don't add anything.
A value of `2' means, also add the closing parenthesis and position cursor
between the two."
  :group 'idlwave-completion
  :type '(choice (const :tag "Nothing" nil)
		 (const :tag "(" t)
		 (const :tag "()" 2)))

(defcustom idlwave-completion-restore-window-configuration t
  "*Non-nil means, try to restore the window configuration after completion.
When completion is not unique, Emacs displays a list of completions.
This messes up your window configuration.  With this variable set, IDLWAVE
restores the old configuration after successful completion."
  :group 'idlwave-completion
  :type 'boolean)

;;; Variables for abbrev and action behavior -----------------------------

(defgroup idlwave-abbrev-and-indent-action nil
  "IDLWAVE performs actions when expanding abbreviations or indenting lines.
The variables in this group govern this."
  :group 'idlwave)

(defcustom idlwave-do-actions nil
  "*Non-nil means performs actions when indenting.
The actions that can be performed are listed in `idlwave-indent-action-table'."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-abbrev-start-char "\\"
  "*A single character string used to start abbreviations in abbrev mode.
Possible characters to chose from: ~`\%
or even '?'.  '.' is not a good choice because it can make structure
field names act like abbrevs in certain circumstances.

Changes to this in `idlwave-mode-hook' will have no effect.  Instead a user
must set it directly using `setq' in the .emacs file before idlwave.el
is loaded."
  :group 'idlwave-abbrev-and-indent-action
  :type 'string)

(defcustom idlwave-surround-by-blank nil
  "*Non-nil means, enable `idlwave-surround'.
If non-nil, `=',`<',`>',`&',`,', `->' are surrounded with spaces by
`idlwave-surround'.
See help for `idlwave-indent-action-table' for symbols using `idlwave-surround'.

Also see the default key bindings for keys using `idlwave-surround'.
Keys are bound and made into actions calling `idlwave-surround' with
`idlwave-action-and-binding'.
See help for `idlwave-action-and-binding' for examples.

Also see help for `idlwave-surround'."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-pad-keyword t
  "*Non-nil means pad '=' for keywords like assignments.
Whenever `idlwave-surround' is non-nil then this affects how '=' is padded
for keywords.  If t, it is padded the same as for assignments.
If nil then spaces are removed.  With any other value, spaces are left
unchanged."
  :group 'idlwave-abbrev-and-indent-action
  :type '(choice
	  (const :tag "Pad like assignments" t)
	  (const :tag "Remove space near `='" nil)
	  (const :tag "Keep space near `='" 'keep)))

(defcustom idlwave-show-block t
  "*Non-nil means point blinks to block beginning for `idlwave-show-begin'."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-expand-generic-end nil
  "*Non-nil means expand generic END to ENDIF/ENDELSE/ENDWHILE etc."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-reindent-end t
  "*Non-nil means re-indent line after END was typed."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-abbrev-move t
  "*Non-nil means the abbrev hook can move point.
Set to nil by `idlwave-expand-region-abbrevs'. To see the abbrev
definitions, use the command `list-abbrevs', for abbrevs that move
point. Moving point is useful, for example, to place point between
parentheses of expanded functions.

See `idlwave-check-abbrev'."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-abbrev-change-case nil
  "*Non-nil means all abbrevs will be forced to either upper or lower case.
If the value t, all expanded abbrevs will be upper case.
If the value is 'down then abbrevs will be forced to lower case.
If nil, the case will not change.
If `idlwave-reserved-word-upcase' is non-nil, reserved words will always be
upper case, regardless of this variable."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

(defcustom idlwave-reserved-word-upcase nil
  "*Non-nil means, reserved words will be made upper case via abbrev expansion.
If nil case of reserved words is controlled by `idlwave-abbrev-change-case'.
Has effect only if in abbrev-mode."
  :group 'idlwave-abbrev-and-indent-action
  :type 'boolean)

;;; Action/Expand Tables.
;;
;; The average user may have difficulty modifying this directly.  It
;; can be modified/set in idlwave-mode-hook, but it is easier to use
;; idlwave-action-and-binding. See help for idlwave-action-and-binding for
;; examples of how to add an action.
;;
;; The action table is used by `idlwave-indent-line' whereas both the
;; action and expand tables are used by `idlwave-indent-and-action'.  In
;; general, the expand table is only used when a line is explicitly
;; indented.  Whereas, in addition to being used when the expand table
;; is used, the action table is used when a line is indirectly
;; indented via line splitting, auto-filling or a new line creation.
;;
;; Example actions:
;;
;;  Capitalize system vars
;;   (idlwave-action-and-binding idlwave-sysvar '(capitalize-word 1) t)
;;
;;  Capitalize procedure name
;;   (idlwave-action-and-binding "\\<\\(pro\\|function\\)\\>[ \t]*\\<"
;;                           '(capitalize-word 1) t)
;;
;;  Capitalize common block name
;;   (idlwave-action-and-binding "\\<common\\>[ \t]+\\<"
;;                           '(capitalize-word 1) t)
;;  Capitalize label
;;   (idlwave-action-and-binding (concat "^[ \t]*" idlwave-label)
;;                           '(capitalize-word -1) t)

(defvar idlwave-indent-action-table nil
  "*Associated array containing action lists of search string (car),
and function as a cdr. This table is used by `idlwave-indent-line'.
See documentation for `idlwave-do-action' for a complete description of
the action lists.

Additions to the table are made with `idlwave-action-and-binding' when a
binding is not requested.
See help on `idlwave-action-and-binding' for examples.")

(defvar idlwave-indent-expand-table nil
  "*Associated array containing action lists of search string (car),
and function as a cdr. The table is used by the
`idlwave-indent-and-action' function. See documentation for
`idlwave-do-action' for a complete description of the action lists.

Additions to the table are made with `idlwave-action-and-binding' when a
binding is requested.
See help on `idlwave-action-and-binding' for examples.")

;;; Documentation header and history keyword ---------------------------------

(defgroup idlwave-documentation nil
  "Options for documenting IDLWAVE files."
  :group 'idlwave)

;; FIXME: make defcustom?
(defvar idlwave-file-header
  (list nil
        ";+
; NAME:
;
;
;
; PURPOSE:
;
;
;
; CATEGORY:
;
;
;
; CALLING SEQUENCE:
;
;
;
; INPUTS:
;
;
;
; OPTIONAL INPUTS:
;
;
;
; KEYWORD PARAMETERS:
;
;
;
; OUTPUTS:
;
;
;
; OPTIONAL OUTPUTS:
;
;
;
; COMMON BLOCKS:
;
;
;
; SIDE EFFECTS:
;
;
;
; RESTRICTIONS:
;
;
;
; PROCEDURE:
;
;
;
; EXAMPLE:
;
;
;
; MODIFICATION HISTORY:
;
;-
")
  "*A list (PATHNAME STRING) specifying the doc-header template to use for
summarizing a file. If PATHNAME is non-nil then this file will be included.
Otherwise STRING is used. If nil, the file summary will be omitted.
For example you might set PATHNAME to the path for the
lib_template.pro file included in the IDL distribution.")

(defcustom idlwave-header-to-beginning-of-file nil
  "*Non-nil means, the documentation header will always be at start of file.
When nil, the header is positioned between the PRO/FUNCTION line of
the current routine and the code, allowing several routine headers in
a file."
  :group 'idlwave-documentation
  :type 'boolean)

(defcustom idlwave-timestamp-hook 'idlwave-default-insert-timestamp
  "*The hook function used to update the timestamp of a function."
  :group 'idlwave-documentation
  :type 'function)

(defcustom idlwave-doc-modifications-keyword "HISTORY"
  "*The modifications keyword to use with the log documentation commands.
A ':' is added to the keyword end.
Inserted by doc-header and used to position logs by doc-modification.
If nil it will not be inserted."
  :group 'idlwave-documentation
  :type 'string)

(defcustom idlwave-doclib-start "^;+\\+"
  "*Regexp matching the start of a document library header."
  :group 'idlwave-documentation
  :type 'regexp)

(defcustom idlwave-doclib-end "^;+-"
  "*Regexp matching the end of a document library header."
  :group 'idlwave-documentation
  :type 'regexp)

;;; External Programs -------------------------------------------------------

(defgroup idlwave-external-programs nil
  "Path locations of external commands used by IDLWAVE."
  :group 'idlwave)

;; WARNING: The following variable has recently been moved from
;; idlw-shell.el to this file.  I hope this does not break
;; anything.

(defcustom idlwave-shell-explicit-file-name "idl"
  "*If non-nil, this is the command to run IDL.
Should be an absolute file path or path relative to the current environment
execution search path.  If you want to specify command line switches
for the idl program, use `idlwave-shell-command-line-options'.

I know the name of this variable is badly chosen, but I cannot change
it without compromizing backwards-compatibility."
  :group 'idlwave-external-programs
  :type 'string)

(defcustom idlwave-shell-command-line-options nil
  "*A list of command line options for calling the IDL program.
Since IDL is executed directly without going through a shell like /bin/sh,
this should be a list of strings like '(\"-rt=file\" \"-nw\") with a separate
string for each argument.  But you may also give a single string which
contains the options whitespace-separated.  Emacs will be kind enough to
split it for you."
  :type '(choice
	  string
	  (repeat (string :value "")))
  :group 'idlwave-external-programs)

(defcustom idlwave-help-application "idlhelp"
  "*The external application providing reference help for programming."
  :group 'idlwave-external-programs
  :type 'string)

;;; Some Shell variables which must be defined here.-----------------------

(defcustom idlwave-shell-debug-modifiers '()
  "List of modifiers to be used for the debugging commands.
Will be used to bind debugging commands in the shell buffer and in all
source buffers.  These are additional convenience bindings, the debugging
commands are always available with the `C-c C-d' prefix.
If you set this to '(control shift), this means setting a breakpoint will
be on `C-S-b', compiling a source file on `C-S-c' etc.  Possible modifiers
are `control', `meta', `super', `hyper', `alt', and `shift'."
  :group 'idlwave-shell-general-setup
  :type '(set :tag "Specify modifiers"
	       (const control)
	       (const meta)
	       (const super)
	       (const hyper)
	       (const alt)
	       (const shift)))

(defcustom idlwave-shell-automatic-start nil
  "*If non-nil attempt invoke idlwave-shell if not already running.
This is checked when an attempt to send a command to an
IDL process is made."
  :group 'idlwave-shell-general-setup
  :type 'boolean)

;;; Miscellaneous variables -------------------------------------------------

(defgroup idlwave-misc nil
  "Miscellaneous options for IDLWAVE mode."
  :group 'idlwave)

(defcustom idlwave-startup-message t
  "*Non-nil displays a startup message when `idlwave-mode' is first called."
  :group 'idlwave-misc
  :type 'boolean)

(defcustom idlwave-default-font-lock-items 
  '(pros-and-functions batch-files idl-keywords label goto
		       common-blocks class-arrows)
  "Items which should be fontified on the default fontification level 2.
IDLWAVE defines 3 levels of fontification.  Level 1 is very little, level 3
is everything and level 2 is specified by this list.
This variable must be set before IDLWAVE gets loaded.  It is
a list of symbols, the following symbols are allowed.

pros-and-functions   Procedure and Function definitions
batch-files          Batch Files
idl-keywords         IDL Keywords
label                Statement Labels
goto                 Goto Statements
common-blocks        Common Blocks
keyword-parameters   Keyword Parameters in routine definitions and calls
system-variables     System Variables
fixme                FIXME: Warning in comments (on XEmacs only v. 21.0 and up)
class-arrows         Object Arrows with class property"
  :group 'idlwave-misc
  :type '(set
	  :inline t :greedy t
	  (const :tag "Procedure and Function definitions" pros-and-functions)
	  (const :tag "Batch Files"                        batch-files)
	  (const :tag "IDL Keywords (reserved words)"      idl-keywords)
	  (const :tag "Statement Labels"                   label)
	  (const :tag "Goto Statements"                    goto)
	  (const :tag "Tags in Structure Definition"       structtag)
	  (const :tag "Structure Name"                     structname)
	  (const :tag "Common Blocks"                      common-blocks)
	  (const :tag "Keyword Parameters"                 keyword-parameters)
	  (const :tag "System Variables"                   system-variables)
	  (const :tag "FIXME: Warning"                     fixme)
	  (const :tag "Object Arrows with class property " class-arrows)))

(defcustom idlwave-mode-hook nil
  "Normal hook.  Executed when a buffer is put into `idlwave-mode'."
  :group 'idlwave-misc
  :type 'hook)

(defcustom idlwave-load-hook nil
  "Normal hook.  Executed when idlwave.el is loaded."
  :group 'idlwave-misc
  :type 'hook)

(defvar idlwave-experimental nil
  "Non-nil means turn on a few experimental features.
This variable is only for the maintainer, to test difficult stuff,
while still distributing stable releases.
As a user, you should not set this to t.")

;;;
;;; End customization variables section
;;;

;;; Non customization variables

;;; font-lock mode - Additions by Phil Williams, Ulrik Dickow and
;;; Simon Marshall <simon@gnu.ai.mit.edu>
;;; and Carsten Dominik...

(defconst idlwave-font-lock-keywords-1 nil
  "Subdued level highlighting for IDLWAVE mode.")

(defconst idlwave-font-lock-keywords-2 nil
  "Medium level highlighting for IDLWAVE mode.")

(defconst idlwave-font-lock-keywords-3 nil
  "Gaudy level highlighting for IDLWAVE mode.")

;; The following are the reserved words in IDL.  Maybe we should
;; highlight some more stuff as well?       
;; Procedure declarations.  Fontify keyword plus procedure name.
(defvar idlwave-idl-keywords
  ;; To update this regexp, update the list of keywords and 
  ;; evaluate the form.
  ;;	(insert 
  ;;	 (prin1-to-string
  ;;	  (concat 
  ;;	   "\\<\\("
  ;;	   (regexp-opt 
  ;;	    '("and" "or" "xor" "not"
  ;;	      "eq" "ge" "gt" "le" "lt" "ne" 
  ;;	      "for" "do" "endfor"
  ;;	      "if" "then" "endif" "else" "endelse" 
  ;;	      "case" "of" "endcase"
  ;;	      "switch" "break" "continue" "endswitch"
  ;;	      "begin" "end"
  ;;	      "repeat" "until" "endrep"
  ;;	      "while" "endwhile" 
  ;;	      "goto" "return"
  ;;	      "inherits" "mod"
  ;;	      "compile_opt" "forward_function"
  ;;	      "on_error" "on_ioerror"))  ; on_error is not officially reserved
  ;;	   "\\)\\>")))
  "\\<\\(and\\|b\\(egin\\|reak\\)\\|c\\(ase\\|o\\(mpile_opt\\|ntinue\\)\\)\\|do\\|e\\(lse\\|nd\\(case\\|else\\|for\\|if\\|rep\\|switch\\|while\\)?\\|q\\)\\|for\\(ward_function\\)?\\|g\\(oto\\|[et]\\)\\|i\\(f\\|nherits\\)\\|l[et]\\|mod\\|n\\(e\\|ot\\)\\|o\\(n_\\(error\\|ioerror\\)\\|[fr]\\)\\|re\\(peat\\|turn\\)\\|switch\\|then\\|until\\|while\\|xor\\)\\>")

(let* ((oldp (or (string-match "Lucid" emacs-version)
		 (not (boundp 'emacs-minor-version))
		 (and (<= emacs-major-version 19) 
		      (<= emacs-minor-version 29))))
       
       (idl-keywords idlwave-idl-keywords)
       ;; Procedure declarations.  Fontify keyword plus procedure name.
       ;; Function  declarations.  Fontify keyword plus function  name.
       (pros-and-functions
	'("\\<\\(function\\|pro\\)\\>[ \t]+\\(\\sw+\\(::\\sw+\\)?\\)"
	  (1 font-lock-keyword-face)
	  (2 font-lock-function-name-face nil t)))

       ;; Common blocks
       (common-blocks
	'("\\<\\(common\\)\\>[ \t]*\\(\\sw+\\)?[ \t]*,?"
	  (1 font-lock-keyword-face)	          ; "common"
	  (2 font-lock-reference-face nil t)      ; block name
	  (font-lock-match-c++-style-declaration-item-and-skip-to-next
	   ;; Start with point after block name and comma
	   (goto-char (match-end 0))  ; needed for XEmacs, could be nil 
	   nil
	   (1 font-lock-variable-name-face)       ; variable names
	   )))

       ;; Batch files
       (batch-files
	'("^[ \t]*\\(@[^ \t\n]+\\)" (1 font-lock-string-face)))

       ;; FIXME warning.
       (fixme
	'("\\<FIXME:" (0 font-lock-warning-face t)))

       ;; Labels
       (label
	'("^[ \t]*\\([a-zA-Z]\\sw*:\\)" (1 font-lock-reference-face)))

       ;; The goto statement and its label
       (goto
	'("\\(goto\\)[ \t]*,[ \t]*\\([a-zA-Z]\\sw*\\)"
	  (1 font-lock-keyword-face)
	  (2 font-lock-reference-face)))

       ;; Tags in structure definitions.  Note that this definition actually
       ;; collides with labels, so we have to use the same face.
       (structtag
	'("\\<\\([a-zA-Z][a-zA-Z0-9_]*:\\)[^:]" (1 font-lock-reference-face)))

       ;; Structure names
       (structname
	'("\\({\\|\\<inherits\\s-\\)\\s-*\\([a-zA-Z][a-zA-Z0-9_]*\\)[},\t \n]"
	  (2 font-lock-function-name-face)))

       ;; Named parameters, like /xlog or ,xrange=[]
       ;; This is anchored to the comma preceeding the keyword.
       ;; Treats continuation lines, works only during whole buffer
       ;; fontification.  Slow, use it only in fancy fontification.
       (keyword-parameters
	'("\\(,\\|[a-zA-Z0-9_](\\)[ \t]*\\(\\$[ \t]*\\(;.*\\)?\\(\n[ \t]*;.*\\)*\n[ \t]*\\)?\\(/[a-zA-Z_]\\sw*\\|[a-zA-Z_]\\sw*[ \t]*=\\)"
	  (5 font-lock-reference-face)))

       ;; System variables start with a bang.
       (system-variables
	'("\\(![a-zA-Z_0-9]+\\(\\.\\sw+\\)?\\)"
	  (1 font-lock-variable-name-face)))

       ;; Special and unusual operators (not used because too noisy)
       (special-operators
	'("[<>#]" (0 font-lock-keyword-face)))

       ;; All operators (not used because too noisy)
       (all-operators
	'("[-*^#+<>/]" (0 font-lock-keyword-face)))
	
       ;; Arrows with text property `idlwave-class'
       (class-arrows
	(list 'idlwave-match-class-arrows 
	      (list 0 (if (featurep 'xemacs) 
			  idlwave-class-arrow-face
			'idlwave-class-arrow-face))))

       )

  ;; The following lines are just a dummy to make the compiler shut up
  ;; about variables bound but not used.
  (setq oldp oldp
	pros-and-functions pros-and-functions
	common-blocks common-blocks
	batch-files batch-files
	fixme fixme
	label label
	goto goto
	structtag structtag
	structname structname
	keyword-parameters keyword-parameters
	system-variables system-variables
	special-operators special-operators
	all-operators all-operators
	class-arrows class-arrows)

  (setq idlwave-font-lock-keywords-1
	(list pros-and-functions
	      batch-files
	      ))

  (setq idlwave-font-lock-keywords-2
	(mapcar 'symbol-value idlwave-default-font-lock-items))

  (setq idlwave-font-lock-keywords-3 
	(list pros-and-functions
	      batch-files
	      idlwave-idl-keywords
	      label goto
	      structtag
	      structname
	      common-blocks
	      keyword-parameters
	      system-variables
	      class-arrows
	      ))
  )

(defun idlwave-match-class-arrows (limit)
  ;; Match an object arrow with class property
  (and idlwave-store-inquired-class
       (re-search-forward "->" limit 'limit)
       (get-text-property (match-beginning 0) 'idlwave-class)))

(defvar idlwave-font-lock-keywords idlwave-font-lock-keywords-2
  "Default expressions to highlight in IDLWAVE mode.")

(defvar idlwave-font-lock-defaults
  '((idlwave-font-lock-keywords
     idlwave-font-lock-keywords-1 
     idlwave-font-lock-keywords-2
     idlwave-font-lock-keywords-3)
    nil t 
    ((?$ . "w") (?_ . "w") (?. . "w")) 
    beginning-of-line))

(put 'idlwave-mode 'font-lock-defaults 
     idlwave-font-lock-defaults) ; XEmacs

(defconst idlwave-comment-line-start-skip "^[ \t]*;"
  "Regexp to match the start of a full-line comment.
That is the _beginning_ of a line containing a comment delimiter `;' preceded
only by whitespace.")

(defconst idlwave-begin-block-reg 
  "\\<\\(pro\\|function\\|begin\\|case\\|switch\\)\\>"
  "Regular expression to find the beginning of a block. The case does
not matter. The search skips matches in comments.")

(defconst idlwave-begin-unit-reg "\\<\\(pro\\|function\\)\\>\\|\\`"
  "Regular expression to find the beginning of a unit. The case does
not matter.")

(defconst idlwave-end-unit-reg "\\<\\(pro\\|function\\)\\>\\|\\'"
  "Regular expression to find the line that indicates the end of unit.
This line is the end of buffer or the start of another unit. The case does
not matter. The search skips matches in comments.")

(defconst idlwave-continue-line-reg "\\<\\$"
  "Regular expression to match a continued line.")

(defconst idlwave-end-block-reg
  "\\<end\\(\\|case\\|switch\\|else\\|for\\|if\\|rep\\|while\\)\\>"
  "Regular expression to find the end of a block. The case does
not matter. The search skips matches found in comments.")

(defconst idlwave-block-matches
  '(("pro"      . "end")
    ("function" . "end")
    ("case"     . "endcase")
    ("else"     . "endelse")
    ("for"      . "endfor")
    ("then"     . "endif")
    ("repeat"   . "endrep")
    ("switch"   . "endswitch")
    ("while"    . "endwhile"))
  "Matches between statements and the corresponding END variant.
The cars are the reserved words starting a block.  If the block really
begins with BEGIN, the cars are the reserved words before the begin
which can be used to identify the block type.
This is used to check for the correct END type, to close blocks and
to expand generic end statements to their detailed form.")

(defconst idlwave-block-match-regexp
  "\\<\\(else\\|for\\|then\\|repeat\\|while\\)\\>"
"Regular expression matching reserved words which can stand before
blocks starting with a BEGIN statement.  The matches must have associations
`idlwave-block-matches'")

(defconst idlwave-identifier "[a-zA-Z][a-zA-Z0-9$_]*"
  "Regular expression matching an IDL identifier.")

(defconst idlwave-sysvar (concat "!" idlwave-identifier)
  "Regular expression matching IDL system variables.")

(defconst idlwave-variable (concat idlwave-identifier "\\|" idlwave-sysvar)
  "Regular expression matching IDL variable names.")

(defconst idlwave-label (concat idlwave-identifier ":")
  "Regular expression matching IDL labels.")

(defconst idlwave-statement-match
  (list
   ;; "endif else" is the only possible "end" that can be
   ;; followed by a statement on the same line.
   '(endelse . ("end\\(\\|if\\)\\s +else" "end\\(\\|if\\)\\s +else"))
   ;; all other "end"s can not be followed by a statement.
   (cons 'end (list idlwave-end-block-reg nil))
   '(if . ("if\\>" "then"))
   '(for . ("for\\>" "do"))
   '(begin . ("begin\\>" nil))
   '(pdef . ("pro\\>\\|function\\>" nil))
   '(while . ("while\\>" "do"))
   '(repeat . ("repeat\\>" "repeat"))
   '(goto . ("goto\\>" nil))
   '(case . ("case\\>" nil))
   '(switch . ("switch\\>" nil))
   (cons 'call (list (concat idlwave-identifier "\\(\\s *$\\|\\s *,\\)") nil))
   '(assign . ("[^=>\n]*=" nil)))
  
  "Associated list of statement matching regular expressions.
Each regular expression matches the start of an IDL statement.  The
first element of each association is a symbol giving the statement
type.  The associated value is a list.  The first element of this list
is a regular expression matching the start of an IDL statement for
identifying the statement type.  The second element of this list is a
regular expression for finding a substatement for the type.  The
substatement starts after the end of the found match modulo
whitespace.  If it is nil then the statement has no substatement.  The
list order matters since matching an assignment statement exactly is
not possible without parsing.  Thus assignment statement become just
the leftover unidentified statements containing an equal sign."  )

(defvar idlwave-fill-function 'auto-fill-function
  "IDL mode auto fill function.")

(defvar idlwave-comment-indent-function 'comment-indent-function
  "IDL mode comment indent function.")

;; Note that this is documented in the v18 manuals as being a string
;; of length one rather than a single character.
;; The code in this file accepts either format for compatibility.
(defvar idlwave-comment-indent-char ?\ 
  "Character to be inserted for IDL comment indentation.
Normally a space.")

(defconst idlwave-continuation-char ?$
  "Character which is inserted as a last character on previous line by
   \\[idlwave-split-line] to begin a continuation line.  Normally $.")

(defconst idlwave-mode-version " 4.15")

(defmacro idlwave-keyword-abbrev (&rest args)
  "Creates a function for abbrev hooks to call `idlwave-check-abbrev' with args."
  `(quote (lambda ()
	    ,(append '(idlwave-check-abbrev) args))))

;; If I take the time I can replace idlwave-keyword-abbrev with
;; idlwave-code-abbrev and remove the quoted abbrev check from
;; idlwave-check-abbrev.  Then, e.g, (idlwave-keyword-abbrev 0 t) becomes
;; (idlwave-code-abbrev idlwave-check-abbrev 0 t).  In fact I should change
;; the name of idlwave-check-abbrev to something like idlwave-modify-abbrev.

(defmacro idlwave-code-abbrev (&rest args)
  "Creates a function for abbrev hooks that ensures abbrevs are not quoted.
Specifically, if the abbrev is in a comment or string it is unexpanded.
Otherwise ARGS forms a list that is evaluated."
  `(quote (lambda ()
	    ,(prin1-to-string args)  ;; Puts the code in the doc string
	    (if (idlwave-quoted)
		(progn (unexpand-abbrev) nil)
	      ,(append args)))))

(defvar idlwave-mode-map (make-sparse-keymap)
  "Keymap used in IDL mode.")

(defvar idlwave-mode-syntax-table (make-syntax-table)
  "Syntax table in use in `idlwave-mode' buffers.")

(modify-syntax-entry ?+   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?-   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?*   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?/   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?^   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?#   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?=   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?%   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?<   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?>   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?\'  "\"" idlwave-mode-syntax-table)
(modify-syntax-entry ?\"  "\"" idlwave-mode-syntax-table)
(modify-syntax-entry ?\\  "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?_   "_"  idlwave-mode-syntax-table)
(modify-syntax-entry ?{   "(}" idlwave-mode-syntax-table)
(modify-syntax-entry ?}   "){" idlwave-mode-syntax-table)
(modify-syntax-entry ?$   "_"  idlwave-mode-syntax-table)
(modify-syntax-entry ?.   "."  idlwave-mode-syntax-table)
(modify-syntax-entry ?\;  "<"  idlwave-mode-syntax-table)
(modify-syntax-entry ?\n  ">"  idlwave-mode-syntax-table)
(modify-syntax-entry ?\f  ">"  idlwave-mode-syntax-table)

(defvar idlwave-find-symbol-syntax-table
  (copy-syntax-table idlwave-mode-syntax-table)
  "Syntax table that treats symbol characters as word characters.")

(modify-syntax-entry ?$   "w"  idlwave-find-symbol-syntax-table)
(modify-syntax-entry ?_   "w"  idlwave-find-symbol-syntax-table)
(modify-syntax-entry ?!   "w"  idlwave-find-symbol-syntax-table)
(modify-syntax-entry ?.   "w"  idlwave-find-symbol-syntax-table)

(defmacro idlwave-with-special-syntax (&rest body)
  "Execute BODY with a different syntax table."
  `(let ((saved-syntax (syntax-table)))
     (unwind-protect
	 (progn
	   (set-syntax-table idlwave-find-symbol-syntax-table)
	   ,@body)
       (set-syntax-table saved-syntax))))

;(defmacro idlwave-with-special-syntax1 (&rest body)
;  "Execute BODY with a different syntax table."
;  `(let ((saved-syntax (syntax-table)))
;     (unwind-protect
;	  (progn
;	    (set-syntax-table idlwave-find-symbol-syntax-table)
;	    ,@body)
;	(set-syntax-table saved-syntax))))

(defun idlwave-action-and-binding (key cmd &optional select)
  "KEY and CMD are made into a key binding and an indent action.
KEY is a string - same as for the `define-key' function.  CMD is a
function of no arguments or a list to be evaluated.  CMD is bound to
KEY in `idlwave-mode-map' by defining an anonymous function calling
`self-insert-command' followed by CMD.  If KEY contains more than one
character a binding will only be set if SELECT is 'both.

\(KEY . CMD\) is also placed in the `idlwave-indent-expand-table',
replacing any previous value for KEY.  If a binding is not set then it
will instead be placed in `idlwave-indent-action-table'.

If the optional argument SELECT is nil then an action and binding are
created.  If SELECT is 'noaction, then a binding is always set and no
action is created.  If SELECT is 'both then an action and binding
will both be created even if KEY contains more than one character.
Otherwise, if SELECT is non-nil then only an action is created.

Some examples:
No spaces before and 1 after a comma
   (idlwave-action-and-binding \",\"  '(idlwave-surround 0 1))
A minimum of 1 space before and after `=' (see `idlwave-expand-equal').
   (idlwave-action-and-binding \"=\"  '(idlwave-expand-equal -1 -1))
Capitalize system variables - action only
   (idlwave-action-and-binding idlwave-sysvar '(capitalize-word 1) t)"
  (if (not (equal select 'noaction))
      ;; Add action
      (let* ((table (if select 'idlwave-indent-action-table
                      'idlwave-indent-expand-table))
             (cell (assoc key (eval table))))
        (if cell
            ;; Replace action command
            (setcdr cell cmd)
          ;; New action
          (set table (append (eval table) (list (cons key cmd)))))))
  ;; Make key binding for action
  (if (or (and (null select) (= (length key) 1))
          (equal select 'noaction)
          (equal select 'both))
      (define-key idlwave-mode-map key
        (append '(lambda ()
                            (interactive)
                            (self-insert-command 1))
                (list (if (listp cmd)
                          cmd
                        (list cmd)))))))

(fset 'idlwave-debug-map (make-sparse-keymap))

(define-key idlwave-mode-map "\C-c "    'idlwave-hard-tab)
(define-key idlwave-mode-map [(control tab)] 'idlwave-hard-tab)
;(define-key idlwave-mode-map "\C-c\C- " 'idlwave-hard-tab)
(define-key idlwave-mode-map "'"        'idlwave-show-matching-quote)
(define-key idlwave-mode-map "\""       'idlwave-show-matching-quote)
(define-key idlwave-mode-map "\C-g"     'idlwave-keyboard-quit)
(define-key idlwave-mode-map "\C-c;"    'idlwave-toggle-comment-region)
(define-key idlwave-mode-map "\C-\M-a"  'idlwave-beginning-of-subprogram)
(define-key idlwave-mode-map "\C-\M-e"  'idlwave-end-of-subprogram)
(define-key idlwave-mode-map "\C-c{"    'idlwave-beginning-of-block)
(define-key idlwave-mode-map "\C-c}"    'idlwave-end-of-block)
(define-key idlwave-mode-map "\C-c]"    'idlwave-close-block)
(define-key idlwave-mode-map "\M-\C-h"  'idlwave-mark-subprogram)
(define-key idlwave-mode-map "\M-\C-n"  'idlwave-forward-block)
(define-key idlwave-mode-map "\M-\C-p"  'idlwave-backward-block)
(define-key idlwave-mode-map "\M-\C-d"  'idlwave-down-block)
(define-key idlwave-mode-map "\M-\C-u"  'idlwave-backward-up-block)
(define-key idlwave-mode-map "\M-\r"    'idlwave-split-line)
(define-key idlwave-mode-map "\M-\C-q"  'idlwave-indent-subprogram)
(define-key idlwave-mode-map "\C-c\C-p" 'idlwave-previous-statement)
(define-key idlwave-mode-map "\C-c\C-n" 'idlwave-next-statement)
;; (define-key idlwave-mode-map "\r"       'idlwave-newline)
;; (define-key idlwave-mode-map "\t"       'idlwave-indent-line)
(define-key idlwave-mode-map [(shift tab)] 'idlwave-indent-statement)
(define-key idlwave-mode-map "\C-c\C-a" 'idlwave-auto-fill-mode)
(define-key idlwave-mode-map "\M-q"     'idlwave-fill-paragraph)
(define-key idlwave-mode-map "\M-s"     'idlwave-edit-in-idlde)
(define-key idlwave-mode-map "\C-c\C-h" 'idlwave-doc-header)
(define-key idlwave-mode-map "\C-c\C-m" 'idlwave-doc-modification)
(define-key idlwave-mode-map "\C-c\C-c" 'idlwave-case)
(define-key idlwave-mode-map "\C-c\C-d" 'idlwave-debug-map)
(define-key idlwave-mode-map "\C-c\C-d\C-c" 'idlwave-shell-save-and-run)
(define-key idlwave-mode-map "\C-c\C-d\C-b" 'idlwave-shell-break-here)
(when (and (boundp 'idlwave-shell-debug-modifiers)
	 (listp idlwave-shell-debug-modifiers)
	 (not (equal idlwave-shell-debug-modifiers '())))
  ;; Bind the debug commands also with the special modifiers.
  (let ((shift (memq 'shift idlwave-shell-debug-modifiers))
	(mods-noshift (delq 'shift 
			    (copy-sequence idlwave-shell-debug-modifiers))))
    (define-key idlwave-mode-map 
      (vector (append mods-noshift (list (if shift ?C ?c))))
      'idlwave-shell-save-and-run)
    (define-key idlwave-mode-map 
      (vector (append mods-noshift (list (if shift ?B ?b))))
      'idlwave-shell-break-here)))
(define-key idlwave-mode-map "\C-c\C-f" 'idlwave-for)
;;  (define-key idlwave-mode-map "\C-c\C-f" 'idlwave-function)
;;  (define-key idlwave-mode-map "\C-c\C-p" 'idlwave-procedure)
(define-key idlwave-mode-map "\C-c\C-r" 'idlwave-repeat)
(define-key idlwave-mode-map "\C-c\C-w" 'idlwave-while)
(define-key idlwave-mode-map "\C-c\C-k" 'idlwave-kill-autoloaded-buffers)
(define-key idlwave-mode-map "\C-c\C-s" 'idlwave-shell)
(define-key idlwave-mode-map "\C-c\C-l" 'idlwave-shell-recenter-shell-window)
(define-key idlwave-mode-map "\C-c\C-b" 'idlwave-list-buffer-load-path-shadows)
(autoload 'idlwave-shell "idlw-shell"
  "Run an inferior IDL, with I/O through buffer `(idlwave-shell-buffer)'." t)
(autoload 'idlwave-shell-send-command "idlw-shell")
(autoload 'idlwave-shell-recenter-shell-window "idlw-shell"
  "Run `idlwave-shell' and switch back to current window" t)
(autoload 'idlwave-shell-save-and-run "idlw-shell"
  "Save and run buffer under the shell." t)
(autoload 'idlwave-shell-break-here "idlw-shell"
  "Set breakpoint in current line." t)
(define-key idlwave-mode-map "\C-c\C-v"   'idlwave-find-module)
(define-key idlwave-mode-map "\C-c?"      'idlwave-routine-info)
(define-key idlwave-mode-map "\M-?"       'idlwave-context-help)
(define-key idlwave-mode-map [(control meta ?\?)] 'idlwave-online-help)
(define-key idlwave-mode-map [(meta tab)] 'idlwave-complete)
(define-key idlwave-mode-map "\C-c\C-i"   'idlwave-update-routine-info)
(define-key idlwave-mode-map "\C-c="      'idlwave-resolve)
(define-key idlwave-mode-map 
  (if (featurep 'xemacs) [(shift button3)] [(shift mouse-3)])
  'idlwave-mouse-context-help)

;; Set action and key bindings.
;; See description of the function `idlwave-action-and-binding'.
;; Automatically add spaces for the following characters
(idlwave-action-and-binding "&"  '(idlwave-surround -1 -1))
(idlwave-action-and-binding "<"  '(idlwave-surround -1 -1))
;; Binding works for both > and ->, by changing the length of the token.
(idlwave-action-and-binding ">"  '(idlwave-surround -1 -1 '(?-) 1 
						    'idlwave-gtr-pad-hook))
(idlwave-action-and-binding "->" '(idlwave-surround -1 -1 nil 2) t)
(idlwave-action-and-binding ","  '(idlwave-surround 0 -1))
;; Automatically add spaces to equal sign if not keyword
(idlwave-action-and-binding "="  '(idlwave-expand-equal -1 -1))

;;;
;;; Abbrev Section
;;;
;;; When expanding abbrevs and the abbrev hook moves backward, an extra
;;; space is inserted (this is the space typed by the user to expanded
;;; the abbrev).
;;;
(defvar idlwave-mode-abbrev-table nil
  "Abbreviation table used for IDLWAVE mode")
(define-abbrev-table 'idlwave-mode-abbrev-table ())

(defun idlwave-define-abbrev (name expansion hook &optional noprefix table)
  "Define-abbrev with backward compatibility.

If NOPREFIX is non-nil, don't prepend prefix character.  Installs into
idlwave-mode-abbrev-table unless TABLE is non-nil."
  (let ((abbrevs-changed nil)  ;; mask the current value to avoid save
	(args (list (or table idlwave-mode-abbrev-table)
		    (if noprefix name (concat idlwave-abbrev-start-char name))
		    expansion
		    hook)))
    (condition-case nil
	(apply 'define-abbrev (append args '(0 t)))
      (error (apply 'define-abbrev args)))))

(condition-case nil
    (modify-syntax-entry (string-to-char idlwave-abbrev-start-char) 
			 "w" idlwave-mode-syntax-table)
  (error nil))

;;
;; Templates
;;
(idlwave-define-abbrev "c"   "" (idlwave-code-abbrev idlwave-case))
(idlwave-define-abbrev "sw"  "" (idlwave-code-abbrev idlwave-switch))
(idlwave-define-abbrev "f"   "" (idlwave-code-abbrev idlwave-for))
(idlwave-define-abbrev "fu"  "" (idlwave-code-abbrev idlwave-function))
(idlwave-define-abbrev "pr"  "" (idlwave-code-abbrev idlwave-procedure))
(idlwave-define-abbrev "r"   "" (idlwave-code-abbrev idlwave-repeat))
(idlwave-define-abbrev "w"   "" (idlwave-code-abbrev idlwave-while))
(idlwave-define-abbrev "i"   "" (idlwave-code-abbrev idlwave-if))
(idlwave-define-abbrev "elif" "" (idlwave-code-abbrev idlwave-elif))
;;
;; Keywords, system functions, conversion routines
;;
(idlwave-define-abbrev "ap" "arg_present()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "b"  "begin"        (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "co" "common"       (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "cb" "byte()"       (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cx" "fix()"        (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cl" "long()"       (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cf" "float()"      (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cs" "string()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cc" "complex()"    (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "cd" "double()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "e"  "else"         (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "ec" "endcase"      'idlwave-show-begin)
(idlwave-define-abbrev "es" "endswitch"    'idlwave-show-begin)
(idlwave-define-abbrev "ee" "endelse"      'idlwave-show-begin)
(idlwave-define-abbrev "ef" "endfor"       'idlwave-show-begin)
(idlwave-define-abbrev "ei" "endif else if" 'idlwave-show-begin)
(idlwave-define-abbrev "el" "endif else"   'idlwave-show-begin)
(idlwave-define-abbrev "en" "endif"        'idlwave-show-begin)
(idlwave-define-abbrev "er" "endrep"       'idlwave-show-begin)
(idlwave-define-abbrev "ew" "endwhile"     'idlwave-show-begin)
(idlwave-define-abbrev "g"  "goto,"        (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "h"  "help,"        (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "k"  "keyword_set()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "n"  "n_elements()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "on" "on_error,"    (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "oi" "on_ioerror,"  (idlwave-keyword-abbrev 0 1))
(idlwave-define-abbrev "ow" "openw,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "or" "openr,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "ou" "openu,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "p"  "print,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "pt" "plot,"        (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "re" "read,"        (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "rf" "readf,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "ru" "readu,"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "rt" "return"       (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "sc" "strcompress()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "sn" "strlen()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "sl" "strlowcase()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "su" "strupcase()"  (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "sm" "strmid()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "sp" "strpos()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "st" "strput()"     (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "sr" "strtrim()"    (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "t"  "then"         (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "u"  "until"        (idlwave-keyword-abbrev 0 t))
(idlwave-define-abbrev "wu" "writeu,"      (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "iap" "if arg_present() then"     (idlwave-keyword-abbrev 6))
(idlwave-define-abbrev "ik" "if keyword_set() then" (idlwave-keyword-abbrev 6))
(idlwave-define-abbrev "ine" "if n_elements() eq 0 then" (idlwave-keyword-abbrev 11))
(idlwave-define-abbrev "inn" "if n_elements() ne 0 then" (idlwave-keyword-abbrev 11))
(idlwave-define-abbrev "np" "n_params()"   (idlwave-keyword-abbrev 0))
(idlwave-define-abbrev "s"  "size()"       (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "wi" "widget_info()" (idlwave-keyword-abbrev 1))
(idlwave-define-abbrev "wc" "widget_control," (idlwave-keyword-abbrev 0))
  
;; This section is reserved words only. (From IDL user manual)
;;
(idlwave-define-abbrev "and"        "and"       (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "begin"      "begin"     (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "break"      "break"     (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "case"       "case"      (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "common"     "common"    (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "continue"   "continue"  (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "do"         "do"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "else"       "else"      (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "end"        "end"       'idlwave-show-begin-check t)
(idlwave-define-abbrev "endcase"    "endcase"   'idlwave-show-begin-check t)
(idlwave-define-abbrev "endelse"    "endelse"   'idlwave-show-begin-check t)
(idlwave-define-abbrev "endfor"     "endfor"    'idlwave-show-begin-check t)
(idlwave-define-abbrev "endif"      "endif"     'idlwave-show-begin-check t)
(idlwave-define-abbrev "endrep"     "endrep"    'idlwave-show-begin-check t)
(idlwave-define-abbrev "endswitch"  "endswitch" 'idlwave-show-begin-check t)
(idlwave-define-abbrev "endwhi"     "endwhi"    'idlwave-show-begin-check t)
(idlwave-define-abbrev "endwhile"   "endwhile"  'idlwave-show-begin-check t)
(idlwave-define-abbrev "eq"         "eq"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "for"        "for"       (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "function"   "function"  (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "ge"         "ge"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "goto"       "goto"      (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "gt"         "gt"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "if"         "if"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "le"         "le"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "lt"         "lt"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "mod"        "mod"       (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "ne"         "ne"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "not"        "not"       (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "of"         "of"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "on_ioerror" "on_ioerror" (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "or"         "or"        (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "pro"        "pro"       (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "repeat"     "repeat"    (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "switch"     "switch"    (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "then"       "then"      (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "until"      "until"     (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "while"      "while"     (idlwave-keyword-abbrev 0 t) t)
(idlwave-define-abbrev "xor"        "xor"       (idlwave-keyword-abbrev 0 t) t)

(defvar imenu-create-index-function)
(defvar extract-index-name-function)
(defvar prev-index-position-function)
(defvar imenu-extract-index-name-function)
(defvar imenu-prev-index-position-function)
;; defined later - so just make the compiler hush
(defvar idlwave-mode-menu)  
(defvar idlwave-mode-debug-menu)

;;;###autoload
(defun idlwave-mode ()
  "Major mode for editing IDL and WAVE CL .pro files.

The main features of this mode are

1. Indentation and Formatting
   --------------------------
   Like other Emacs programming modes, C-j inserts a newline and indents.
   TAB is used for explicit indentation of the current line.

   To start a continuation line, use \\[idlwave-split-line].  This
   function can also be used in the middle of a line to split the line
   at that point.  When used inside a long constant string, the string
   is split at that point with the `+' concatenation operator.

   Comments are indented as follows:

   `;;;' Indentation remains unchanged.
   `;;'  Indent like the surrounding code
   `;'   Indent to a minimum column.

   The indentation of comments starting in column 0 is never changed.

   Use \\[idlwave-fill-paragraph] to refill a paragraph inside a
   comment.  The indentation of the second line of the paragraph
   relative to the first will be retained.  Use
   \\[idlwave-auto-fill-mode] to toggle auto-fill mode for these
   comments.  When the variable `idlwave-fill-comment-line-only' is
   nil, code can also be auto-filled and auto-indented (not
   recommended).

   To convert pre-existing IDL code to your formatting style, mark the
   entire buffer with \\[mark-whole-buffer] and execute
   \\[idlwave-expand-region-abbrevs].  Then mark the entire buffer
   again followed by \\[indent-region] (`indent-region').

2. Routine Info
   ------------
   IDLWAVE displays information about the calling sequence and the
   accepted keyword parameters of a procedure or function with
   \\[idlwave-routine-info].  \\[idlwave-find-module] jumps to the
   source file of a module.  These commands know about system
   routines, all routines in idlwave-mode buffers and (when the
   idlwave-shell is active) about all modules currently compiled under
   this shell.  Use \\[idlwave-update-routine-info] to update this
   information, which is also used for completion (see item 4).

3. Online IDL Help
   ---------------
   \\[idlwave-context-help] displays the IDL documentation relevant
   for the system variable, keyword, or routine at point.  A single key
   stroke gets you directly to the right place in the docs.  Two additional
   files (an ASCII version of the IDL documentation and a topics file) must
   be installed for this - check the IDLWAVE webpage for these files.

4. Completion
   ----------
   \\[idlwave-complete] completes the names of procedures, functions
   class names and keyword parameters.  It is context sensitive and
   figures out what is expected at point (procedure/function/keyword).
   Lower case strings are completed in lower case, other strings in
   mixed or upper case.

5. Code Templates and Abbreviations
   --------------------------------
   Many Abbreviations are predefined to expand to code fragments and templates.
   The abbreviations start generally with a `\\`.  Some examples

   \\pr        PROCEDURE template
   \\fu        FUNCTION template
   \\c         CASE statement template
   \\sw        SWITCH statement template
   \\f         FOR loop template
   \\r         REPEAT Loop template
   \\w         WHILE loop template
   \\i         IF statement template
   \\elif      IF-ELSE statement template
   \\b         BEGIN
   
   For a full list, use \\[idlwave-list-abbrevs].  Some templates also have
   direct keybindings - see the list of keybindings below.

   \\[idlwave-doc-header] inserts a documentation header at the beginning of the
   current program unit (pro, function or main).  Change log entries
   can be added to the current program unit with \\[idlwave-doc-modification].

6. Automatic Case Conversion
   -------------------------
   The case of reserved words and some abbrevs is controlled by
   `idlwave-reserved-word-upcase' and `idlwave-abbrev-change-case'.

7. Automatic END completion
   ------------------------
   If the variable `idlwave-expand-generic-end' is non-nil, each END typed
   will be converted to the specific version, like ENDIF, ENDFOR, etc.

8. Hooks
   -----
   Loading idlwave.el runs `idlwave-load-hook'.
   Turning on `idlwave-mode' runs `idlwave-mode-hook'.

9. Documentation and Customization
   -------------------------------
   Info documentation for this package is available.  Use
   \\[idlwave-info] to display (complain to your sysadmin if that does
   not work).  For Postscript, PDF, and HTML versions of the
   documentation, check IDLWAVE's homepage at `http://idlwave.org'.
   IDLWAVE has customize support - see the group `idlwave'.

10.Keybindings
   -----------
   Here is a list of all keybindings of this mode.
   If some of the key bindings below show with ??, use \\[describe-key]
   followed by the key sequence to see what the key sequence does.

\\{idlwave-mode-map}"

  (interactive)
  (kill-all-local-variables)
  
  (if idlwave-startup-message
      (message "Emacs IDLWAVE mode version %s." idlwave-mode-version))
  (setq idlwave-startup-message nil)
  
  (setq local-abbrev-table idlwave-mode-abbrev-table)
  (set-syntax-table idlwave-mode-syntax-table)
  
  (set (make-local-variable 'indent-line-function) 'idlwave-indent-and-action)
  
  (make-local-variable idlwave-comment-indent-function)
  (set idlwave-comment-indent-function 'idlwave-comment-hook)
  
  (set (make-local-variable 'comment-start-skip) ";+[ \t]*")
  (set (make-local-variable 'comment-start) ";")
  (set (make-local-variable 'require-final-newline) t)
  (set (make-local-variable 'abbrev-all-caps) t)
  (set (make-local-variable 'indent-tabs-mode) nil)
  (set (make-local-variable 'completion-ignore-case) t)
  
  (use-local-map idlwave-mode-map)

  (when (featurep 'easymenu)
    (easy-menu-add idlwave-mode-menu idlwave-mode-map)
    (easy-menu-add idlwave-mode-debug-menu idlwave-mode-map))

  (setq mode-name "IDLWAVE")
  (setq major-mode 'idlwave-mode)
  (setq abbrev-mode t)
  
  (set (make-local-variable idlwave-fill-function) 'idlwave-auto-fill)
  (setq comment-end "")
  (set (make-local-variable 'comment-multi-line) nil)
  (set (make-local-variable 'paragraph-separate) 
       "[ \t\f]*$\\|[ \t]*;+[ \t]*$\\|;+[+=-_*]+$")
  (set (make-local-variable 'paragraph-start) "[ \t\f]\\|[ \t]*;+[ \t]")
  (set (make-local-variable 'paragraph-ignore-fill-prefix) nil)
  (set (make-local-variable 'parse-sexp-ignore-comments) t)
  
  ;; Set tag table list to use IDLTAGS as file name.
  (if (boundp 'tag-table-alist)
      (add-to-list 'tag-table-alist '("\\.pro$" . "IDLTAGS")))
  
  ;; Font-lock additions - originally Phil Williams, then Ulrik Dickow
  ;; Following line is for Emacs - XEmacs uses the corresponding porperty
  ;; on the `idlwave-mode' symbol.
  (set (make-local-variable 'font-lock-defaults) idlwave-font-lock-defaults)

  ;; Imenu setup
  (set (make-local-variable 'imenu-create-index-function)
       'imenu-default-create-index-function)
  (set (make-local-variable 'imenu-extract-index-name-function)
       'idlwave-unit-name)
  (set (make-local-variable 'imenu-prev-index-position-function)
       'idlwave-prev-index-position)

  ;; Make a local post-command-hook and add our hook to it
  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
  (make-local-hook 'post-command-hook)
  (add-hook 'post-command-hook 'idlwave-command-hook nil 'local)

  ;; Make local hooks for buffer updates
  ;; NB: `make-local-hook' needed for older/alternative Emacs compatibility
  (make-local-hook 'kill-buffer-hook)
  (add-hook 'kill-buffer-hook 'idlwave-kill-buffer-update nil 'local)
  (make-local-hook 'after-save-hook)
  (add-hook 'after-save-hook 'idlwave-save-buffer-update nil 'local)
  (add-hook 'after-save-hook 'idlwave-revoke-license-to-kill nil 'local)

  ;; Update the routine info with info about current buffer?
  (idlwave-new-buffer-update)

  ;; Run the mode hook
  (run-hooks 'idlwave-mode-hook))

;;
;;  Done with start up and initialization code.
;;  The remaining routines are the code formatting functions.
;;

(defun idlwave-push-mark (&rest rest)
  "Push mark for compatibility with Emacs 18/19."
  (if (fboundp 'iconify-frame)
      (apply 'push-mark rest)
    (push-mark)))

(defun idlwave-hard-tab ()
  "Inserts TAB in buffer in current position."
  (interactive)
  (insert "\t"))

;;; This stuff is experimental

(defvar idlwave-command-hook nil
  "If non-nil, a list that can be evaluated using `eval'.
It is evaluated in the lisp function `idlwave-command-hook' which is
placed in `post-command-hook'.")

(defun idlwave-command-hook ()
  "Command run after every command.
Evaluates a non-nil value of the *variable* `idlwave-command-hook' and
sets the variable to zero afterwards."
  (and idlwave-command-hook
       (listp idlwave-command-hook)
       (condition-case nil
	   (eval idlwave-command-hook)
	 (error nil)))
  (setq idlwave-command-hook nil))

;;; End experiment

;; It would be better to use expand.el for better abbrev handling and
;; versatility.

(defun idlwave-check-abbrev (arg &optional reserved)
  "Reverses abbrev expansion if in comment or string.
Argument ARG is the number of characters to move point
backward if `idlwave-abbrev-move' is non-nil.
If optional argument RESERVED is non-nil then the expansion
consists of reserved words, which will be capitalized if
`idlwave-reserved-word-upcase' is non-nil.
Otherwise, the abbrev will be capitalized if `idlwave-abbrev-change-case'
is non-nil, unless its value is \`down in which case the abbrev will be
made into all lowercase.
Returns non-nil if abbrev is left expanded."
  (if (idlwave-quoted)
      (progn (unexpand-abbrev)
             nil)
    (if (and reserved idlwave-reserved-word-upcase)
        (upcase-region last-abbrev-location (point))
      (cond
       ((equal idlwave-abbrev-change-case 'down)
        (downcase-region last-abbrev-location (point)))
       (idlwave-abbrev-change-case
        (upcase-region last-abbrev-location (point)))))
    (if (and idlwave-abbrev-move (> arg 0))
        (if (boundp 'post-command-hook)
            (setq idlwave-command-hook (list 'backward-char (1+ arg)))
          (backward-char arg)))
    t))

(defun idlwave-in-comment ()
  "Returns t if point is inside a comment, nil otherwise."
  (save-excursion
    (let ((here (point)))
      (and (idlwave-goto-comment) (> here (point))))))

(defun idlwave-goto-comment ()
  "Move to start of comment delimiter on current line.
Moves to end of line if there is no comment delimiter.
Ignores comment delimiters in strings.
Returns point if comment found and nil otherwise."
  (let ((eos (progn (end-of-line) (point)))
        (data (match-data))
        found)
    ;; Look for first comment delimiter not in a string
    (beginning-of-line)
    (setq found (search-forward comment-start eos 'lim))
    (while (and found (idlwave-in-quote))
      (setq found (search-forward comment-start eos 'lim)))
    (store-match-data data)
    (and found (not (idlwave-in-quote))
         (progn
           (backward-char 1)
           (point)))))

(defvar transient-mark-mode)
(defvar zmacs-regions)
(defvar mark-active)
(defun idlwave-region-active-p ()
  "Is transien-mark-mode on an the region active?
Works on both Emacs and XEmacs."
  (if (featurep 'xemacs)
      (and zmacs-regions (region-active-p))
    (and transient-mark-mode mark-active)))

(defun idlwave-show-matching-quote ()
  "Insert quote and show matching quote if this is end of a string."
  (interactive)
  (let ((bq (idlwave-in-quote))
        (inq last-command-char))
    (if (and bq (not (idlwave-in-comment)))
        (let ((delim (char-after bq)))
          (insert inq)
          (if (eq inq delim)
              (save-excursion
                (goto-char bq)
                (sit-for 1))))
      ;; Not the end of a string
      (insert inq))))

(defun idlwave-show-begin-check ()
  "Ensure that the previous word was a token before `idlwave-show-begin'.
An END token must be preceded by whitespace."
  (if (not (idlwave-quoted))
      (if
	  (save-excursion
	    (backward-word 1)
	    (backward-char 1)
	    (looking-at "[ \t\n\f]"))
	  (idlwave-show-begin))))

(defun idlwave-show-begin ()
  "Finds the start of current block and blinks to it for a second.
Also checks if the correct end statement has been used."
  ;; All end statements are reserved words
  ;; Re-indent end line
  (insert-char ?\ 1) ;; So indent, etc. work well
  (backward-char 1)
  (let* ((pos (point-marker))
	 (last-abbrev-marker (copy-marker last-abbrev-location))
	 (eol-pos (save-excursion (end-of-line) (point)))
	 begin-pos end-pos end end1 )
    (if idlwave-reindent-end  (idlwave-indent-line))
    
    (when (and (idlwave-check-abbrev 0 t)
	       idlwave-show-block)
      (save-excursion
	;; Move inside current block
	(goto-char last-abbrev-marker)
	(idlwave-block-jump-out -1 'nomark)
	(setq begin-pos (point))
	(idlwave-block-jump-out 1 'nomark)
	(setq end-pos (point))
	(if (> end-pos eol-pos)
	    (setq end-pos pos))
	(goto-char end-pos)
	(setq end (buffer-substring 
		   (progn
		     (skip-chars-backward "a-zA-Z")
		     (point))
		   end-pos))
	(goto-char begin-pos)
	(when (setq end1 (cdr (idlwave-block-master)))
	  (cond
	   ((null end1)) ; no-operation
	   ((string= (downcase end) (downcase end1))
	    (sit-for 1))
	   ((string= (downcase end) "end")
	    ;; A generic end
	    (if idlwave-expand-generic-end
		(save-excursion
		  (goto-char pos)
		  (backward-char 3)
		  (insert (if (string= end "END") (upcase end1) end1))
		  (delete-char 3)))
	    (sit-for 1))
	   (t
	    (beep)
	    (message "Warning: Shouldn't this be \"%s\" instead of \"%s\"?" 
		     end1 end)
	    (sit-for 1)))))))
  (delete-char 1))

(defun idlwave-block-master ()
  (let ((case-fold-search t))
    (save-excursion
      (cond
       ((looking-at "pro\\|case\\|switch\\|function\\>")
	(assoc (downcase (match-string 0)) idlwave-block-matches))
       ((looking-at "begin\\>")
	(let ((limit (save-excursion 
		       (idlwave-beginning-of-statement) 
		       (point))))
	  (cond
	   ((re-search-backward idlwave-block-match-regexp limit t)
	    (assoc (downcase (match-string 1))
		   idlwave-block-matches))
	   ;;((re-search-backward ":[ \t]*\\=" limit t)
	   ;; ;; seems to be a case thing
	   ;; '("begin" . "end"))
	   (t
	    ;; Just a nromal block
	    '("begin" . "end")))))
       (t nil)))))

(defun idlwave-close-block ()
  "Terminate the current block with the correct END statement."
  (interactive)

  ;; Start new line if we are not in a new line
  (unless (save-excursion
	    (skip-chars-backward " \t")
	    (bolp))
    (let ((idlwave-show-block nil))
      (newline-and-indent)))
  (let ((last-abbrev-location (point)))  ; for upcasing
    (insert "end")
    (idlwave-show-begin)))

(defun idlwave-gtr-pad-hook (char) 
  "Let the > symbol expand around -> if present.  The new token length
is returned."  
  2)

(defun idlwave-surround (&optional before after escape-chars length ec-hook)
  "Surround the LENGTH characters before point with blanks.
LENGTH defaults to 1.
Optional arguments BEFORE and AFTER affect the behavior before and
after the characters (see also description of `idlwave-make-space'):

nil            do nothing
0              force no spaces
integer > 0    force exactly n spaces
integer < 0    at least |n| spaces

The function does nothing if any of the following conditions is true:
- `idlwave-surround-by-blank' is nil
- the character before point is inside a string or comment
- the char preceeding the string to be surrounded is a member of ESCAPE-CHARS.
  This hack is used to avoid padding of `>' when it is part of
  the '->' operator.  In this case, ESCAPE-CHARS would be '(?-).

If a function is passed in EC-HOOK, and an ESCAPE-CHARS match occurs,
the named function will be called with a single argument of the
preceeding character.  Then idlwave-surround will run as usual if
EC-HOOK returns non-nil, and a new length will be taken from the
return value."
  (when (and idlwave-surround-by-blank (not (idlwave-quoted)))
    (let* ((length (or length 1)) ; establish a default for LENGTH
	   (prev-char (char-after (- (point) (1+ length)))))
      (when (or (not (memq prev-char escape-chars))
		(and (fboundp ec-hook) 
		     (setq length 
			   (save-excursion (funcall ec-hook prev-char)))))
	(backward-char length)
	(save-restriction
	  (let ((here (point)))
	    (skip-chars-backward " \t")
	    (if (bolp)
		;; avoid clobbering indent
		(progn
		  (move-to-column (idlwave-calculate-indent))
		  (if (<= (point) here)
		      (narrow-to-region (point) here))
		  (goto-char here)))
	    (idlwave-make-space before))
	  (skip-chars-forward " \t"))
	(forward-char length)
	(idlwave-make-space after)
	;; Check to see if the line should auto wrap
	(if (and (equal (char-after (1- (point))) ?\ )
		 (> (current-column) fill-column))
	    (funcall auto-fill-function))))))

(defun idlwave-make-space (n)
  "Make space at point.
The space affected is all the spaces and tabs around point.
If n is non-nil then point is left abs(n) spaces from the beginning of
the contiguous space.
The amount of space at point is determined by N.
If the value of N is:
nil   - do nothing.
> 0   - exactly N spaces.
< 0   - a minimum of -N spaces, i.e., do not change if there are
        already -N spaces.
0     - no spaces (i.e. remove any existing space)."
  (if (integerp n)
      (let
          ((start-col (progn (skip-chars-backward " \t") (current-column)))
           (left (point))
           (end-col (progn (skip-chars-forward " \t") (current-column))))
        (delete-horizontal-space)
        (cond
         ((> n 0)
          (idlwave-indent-to (+ start-col n))
          (goto-char (+ left n)))
         ((< n 0)
          (idlwave-indent-to end-col (- n))
          (goto-char (- left n)))
         ;; n = 0, done
         ))))

(defun idlwave-newline ()
  "Inserts a newline and indents the current and previous line."
  (interactive)
  ;;
  ;; Handle unterminated single and double quotes
  ;; If not in a comment and in a string then insertion of a newline
  ;; will mean unbalanced quotes.
  ;;
  (if (and (not (idlwave-in-comment)) (idlwave-in-quote))
      (progn (beep)
             (message "Warning: unbalanced quotes?")))
  (newline)
  ;;
  ;; The current line is being split, the cursor should be at the
  ;; beginning of the new line skipping the leading indentation.
  ;;
  ;; The reason we insert the new line before indenting is that the
  ;; indenting could be confused by keywords (e.g. END) on the line
  ;; after the split point.  This prevents us from just using
  ;; `indent-for-tab-command' followed by `newline-and-indent'.
  ;;
  (beginning-of-line 0)
  (idlwave-indent-line)
  (forward-line)
  (idlwave-indent-line))

;;
;;  Use global variable 'comment-column' to set parallel comment
;;
;; Modeled on lisp.el
;; Emacs Lisp and IDL (Wave CL) have identical comment syntax
(defun idlwave-comment-hook ()
  "Compute indent for the beginning of the IDL comment delimiter."
  (if (or (looking-at idlwave-no-change-comment)
          (if idlwave-begin-line-comment
              (looking-at idlwave-begin-line-comment)
	    (looking-at "^;")))
      (current-column)
    (if (looking-at idlwave-code-comment)
        (if (save-excursion (skip-chars-backward " \t") (bolp))
            ;; On line by itself, indent as code
            (let ((tem (idlwave-calculate-indent)))
              (if (listp tem) (car tem) tem))
          ;; after code - do not change
          (current-column))
      (skip-chars-backward " \t")
      (max (if (bolp) 0 (1+ (current-column)))
           comment-column))))

(defun idlwave-split-line ()
  "Continue line by breaking line at point and indent the lines.
For a code line insert continuation marker. If the line is a line comment
then the new line will contain a comment with the same indentation.
Splits strings with the IDL operator `+' if `idlwave-split-line-string' is
non-nil."
  (interactive)
  ;; Expand abbreviation, just like normal RET would.
  (and abbrev-mode (expand-abbrev))
  (let (beg)
    (if (not (idlwave-in-comment))
        ;; For code line add continuation.
        ;; Check if splitting a string.
        (progn
          (if (setq beg (idlwave-in-quote))
              (if idlwave-split-line-string
                  ;; Split the string.
                  (progn (insert (setq beg (char-after beg)) " + "
                                 idlwave-continuation-char beg)
                         (backward-char 1)
			 (newline-and-indent)
			 (forward-char 1))
                ;; Do not split the string.
                (beep)
                (message "Warning: continuation inside string!!")
                (insert " " idlwave-continuation-char))
            ;; Not splitting a string.
	    (if (not (member (char-before) '(?\  ?\t)))
		(insert " "))
            (insert idlwave-continuation-char)
	    (newline-and-indent)))
      (indent-new-comment-line))
    ;; Indent previous line
    (setq beg (- (point-max) (point)))
    (forward-line -1)
    (idlwave-indent-line)
    (goto-char (- (point-max) beg))
    ;; Reindent new line
    (idlwave-indent-line)))

(defun idlwave-beginning-of-subprogram ()
  "Moves point to the beginning of the current program unit."
  (interactive)
  (idlwave-find-key idlwave-begin-unit-reg -1))

(defun idlwave-end-of-subprogram ()
  "Moves point to the start of the next program unit."
  (interactive)
  (idlwave-end-of-statement)
  (idlwave-find-key idlwave-end-unit-reg 1))

(defun idlwave-mark-statement ()
  "Mark current IDL statement."
  (interactive)
  (idlwave-end-of-statement)
  (let ((end (point)))
    (idlwave-beginning-of-statement)
    (idlwave-push-mark end nil t)))

(defun idlwave-mark-block ()
  "Mark containing block."
  (interactive)
  (idlwave-end-of-statement)
  (idlwave-backward-up-block -1)
  (idlwave-end-of-statement)
  (let ((end (point)))
    (idlwave-backward-block)
    (idlwave-beginning-of-statement)
    (idlwave-push-mark end nil t)))


(defun idlwave-mark-subprogram ()
  "Put mark at beginning of program, point at end.
The marks are pushed."
  (interactive)
  (idlwave-end-of-statement)
  (idlwave-beginning-of-subprogram)
  (let ((beg (point)))
    (idlwave-forward-block)
    (idlwave-push-mark beg nil t))
  (exchange-point-and-mark))

(defun idlwave-backward-up-block (&optional arg)
  "Move to beginning of enclosing block if prefix ARG >= 0.
If prefix ARG < 0 then move forward to enclosing block end."
  (interactive "p")
  (idlwave-block-jump-out (- arg) 'nomark))

(defun idlwave-beginning-of-block ()
  "Go to the beginning of the current block."
  (interactive)
  (idlwave-block-jump-out -1 'nomark)
  (forward-word 1))

(defun idlwave-end-of-block ()
  "Go to the beginning of the current block."
  (interactive)
  (idlwave-block-jump-out 1 'nomark)
  (backward-word 1))

(defun idlwave-forward-block ()
  "Move across next nested block."
  (interactive)
  (if (idlwave-down-block 1)
      (idlwave-block-jump-out 1 'nomark)))

(defun idlwave-backward-block ()
  "Move backward across previous nested block."
  (interactive)
  (if (idlwave-down-block -1)
      (idlwave-block-jump-out -1 'nomark)))

(defun idlwave-down-block (&optional arg)
  "Go down a block.
With ARG: ARG >= 0 go forwards, ARG < 0 go backwards.
Returns non-nil if successfull."
  (interactive "p")
  (let (status)
    (if (< arg 0)
        ;; Backward
        (let ((eos (save-excursion
                     (idlwave-block-jump-out -1 'nomark)
                     (point))))
          (if (setq status (idlwave-find-key 
			    idlwave-end-block-reg -1 'nomark eos))
              (idlwave-beginning-of-statement)
            (message "No nested block before beginning of containing block.")))
      ;; Forward
      (let ((eos (save-excursion
                   (idlwave-block-jump-out 1 'nomark)
                   (point))))
        (if (setq status (idlwave-find-key 
			  idlwave-begin-block-reg 1 'nomark eos))
            (idlwave-end-of-statement)
          (message "No nested block before end of containing block."))))
    status))

(defun idlwave-mark-doclib ()
  "Put point at beginning of doc library header, mark at end.
The marks are pushed."
  (interactive)
  (let (beg
        (here (point)))
    (goto-char (point-max))
    (if (re-search-backward idlwave-doclib-start nil t)
        (progn 
	  (setq beg (progn (beginning-of-line) (point)))
	  (if (re-search-forward idlwave-doclib-end nil t)
	      (progn
		(forward-line 1)
		(idlwave-push-mark beg nil t)
		(message "Could not find end of doc library header.")))
	  (message "Could not find doc library header start.")
	  (goto-char here)))))


(defun idlwave-current-routine ()
  "Return (NAME TYPE CLASS) of current routine."
  (idlwave-routines)
  (save-excursion
    (idlwave-beginning-of-subprogram)
    (if (looking-at "[ \t]*\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)")
	(let* ((type (if (string= (downcase (match-string 1)) "pro")
			 'pro 'function))
	       (class (idlwave-sintern-class (match-string 3)))
	       (name (idlwave-sintern-routine-or-method (match-string 4) class)))
	  (list name type class)))))

(defvar idlwave-shell-prompt-pattern)
(defun idlwave-beginning-of-statement ()
  "Move to beginning of the current statement.
Skips back past statement continuations.
Point is placed at the beginning of the line whether or not this is an
actual statement."
  (interactive)
  (cond
   ((eq major-mode 'idlwave-shell-mode)
    (if (re-search-backward idlwave-shell-prompt-pattern nil t)
	(goto-char (match-end 0))))
   (t	
    (if (save-excursion (forward-line -1) (idlwave-is-continuation-line))
	(idlwave-previous-statement)
      (beginning-of-line)))))

(defun idlwave-previous-statement ()
  "Moves point to beginning of the previous statement.
Returns t if the current line before moving is the beginning of
the first non-comment statement in the file, and nil otherwise."
  (interactive)
  (let (first-statement)
    (if (not (= (forward-line -1) 0))
        ;; first line in file
        t
      ;; skip blank lines, label lines, include lines and line comments
      (while (and
              ;; The current statement is the first statement until we
              ;; reach another statement.
              (setq first-statement
                    (or
                     (looking-at idlwave-comment-line-start-skip)
                     (looking-at "[ \t]*$")
                     (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
                     (looking-at "^@")))
              (= (forward-line -1) 0)))
      ;; skip continuation lines
      (while (and
              (save-excursion
                (forward-line -1)
                (idlwave-is-continuation-line))
              (= (forward-line -1) 0)))
      first-statement)))

(defun idlwave-end-of-statement ()
  "Moves point to the end of the current IDL statement.
If not in a statement just moves to end of line.  Returns position."
  (interactive)
  (while (and (idlwave-is-continuation-line)
              (= (forward-line 1) 0))
    (while (and (idlwave-is-comment-or-empty-line)
		(= (forward-line 1) 0))))
  (end-of-line)
  (point))

(defun idlwave-end-of-statement0 ()
  "Moves point to the end of the current IDL statement.
If not in a statement just moves to end of line. Returns position."
  (interactive)
  (while (and (idlwave-is-continuation-line)
              (= (forward-line 1) 0)))
  (end-of-line)
  (point))

(defun idlwave-next-statement ()
  "Moves point to beginning of the next IDL statement.
 Returns t if that statement is the last
 non-comment IDL statement in the file, and nil otherwise."
  (interactive)
  (let (last-statement)
    (idlwave-end-of-statement)
    ;; skip blank lines, label lines, include lines and line comments
    (while (and (= (forward-line 1) 0)
                ;; The current statement is the last statement until
                ;; we reach a new statement.
                (setq last-statement
                      (or
                       (looking-at idlwave-comment-line-start-skip)
                       (looking-at "[ \t]*$")
                       (looking-at (concat "[ \t]*" idlwave-label "[ \t]*$"))
                       (looking-at "^@")))))
    last-statement))

(defun idlwave-skip-multi-commands (&optional lim)
  "Skip past multiple commands on a line (with `&')."
  (let ((save-point (point)))
    (when (re-search-forward ".*&" lim t)
      (goto-char (match-end 0))
      (if (idlwave-in-quote) (goto-char save-point)))
    (point)))

(defun idlwave-skip-label-or-case ()
  "Skip label or case statement element.
Returns position after label.
If there is no label point is not moved and nil is returned."
  ;; Case expressions and labels are terminated by a colon.
  ;; So we find the first colon in the line and make sure
  ;; - no `?' is before it (might be a ? b : c)
  ;; - it is not in a comment
  ;; - not in a string constant
  ;; - not in parenthesis (like a[0:3])
  ;; - not followed by another ":" in explicit class, ala a->b::c
  ;; As many in this mode, this function is heuristic and not an exact
  ;; parser. 
  (let* ((start (point))
	 (eos (save-excursion (idlwave-end-of-statement) (point)))
	 (end (idlwave-find-key ":" 1 'nomark eos)))
    (if (and end
             (= (nth 0 (parse-partial-sexp start end)) 0)
	     (not (string-match "\\?" (buffer-substring start end)))
	     (not (string-match "^::" (buffer-substring end eos))))
        (progn
          (forward-char)
          (point))
      (goto-char start)
      nil)))

(defun idlwave-start-of-substatement (&optional pre)
  "Move to start of next IDL substatement after point.
Uses the type of the current IDL statement to determine if the next
statement is on a new line or is a subpart of the current statement.
Returns point at start of substatement modulo whitespace.
If optional argument is non-nil move to beginning of current
substatement."
  (let ((orig (point))
        (eos (idlwave-end-of-statement))
        (ifnest 0)
        st nst last)
    (idlwave-beginning-of-statement)
    (idlwave-skip-label-or-case)
    (idlwave-skip-multi-commands orig)
    (setq last (point))
    ;; Continue looking for substatements until we are past orig
    (while (and (<= (point) orig) (not (eobp)))
      (setq last (point))
      (setq nst (nth 1 (cdr (setq st (car (idlwave-statement-type))))))
      (if (equal (car st) 'if) (setq ifnest (1+ ifnest)))
      (cond ((and nst
                  (idlwave-find-key nst 1 'nomark eos))
             (goto-char (match-end 0)))
            ((and (> ifnest 0) (idlwave-find-key "\\<else\\>" 1 'nomark eos))
             (setq ifnest (1- ifnest))
             (goto-char (match-end 0)))
            (t (setq ifnest 0)
               (idlwave-next-statement))))
    (if pre (goto-char last))
    ;; If a continuation line starts here, move to next line
    (if (looking-at "[ \t]*\\$\\([ \t]*\\(;\\|$\\)\\)")
	(beginning-of-line 2))
    (point)))

(defun idlwave-statement-type ()
  "Return the type of the current IDL statement.
Uses `idlwave-statement-match' to return a cons of (type . point) with
point the ending position where the type was determined. Type is the
association from `idlwave-statement-match', i.e. the cons cell from the
list not just the type symbol. Returns nil if not an identifiable
statement."
  (save-excursion
    ;; Skip whitespace within a statement which is spaces, tabs, continuations
    ;; and possibly comments
    (while (looking-at "[ \t]*\\$")
      (forward-line 1))
    (skip-chars-forward " \t")
    (let ((st idlwave-statement-match)
          (case-fold-search t))
      (while (and (not (looking-at (nth 0 (cdr (car st)))))
                  (setq st (cdr st))))
      (if st
          (append st (match-end 0))))))

(defun idlwave-expand-equal (&optional before after)
  "Pad '=' with spaces.
Two cases: Assignment statement, and keyword assignment.
The case is determined using `idlwave-start-of-substatement' and
`idlwave-statement-type'.
The equal sign will be surrounded by BEFORE and AFTER blanks.
If `idlwave-pad-keyword' is t then keyword assignment is treated just
like assignment statements.  When nil, spaces are removed for keyword
assignment.  Any other value keeps the current space around the `='.
Limits in for loops are treated as keyword assignment.
See `idlwave-surround'. "
  ;; Even though idlwave-surround checks `idlwave-surround-by-blank' this
  ;; check saves the time of finding the statement type.
  (if idlwave-surround-by-blank
      (let ((st (save-excursion
                  (idlwave-start-of-substatement t)
                  (idlwave-statement-type))))

        (cond ((or (and (equal (car (car st)) 'assign)
			(equal (cdr st) (point)))
		   (eq t idlwave-pad-keyword))
	       ;; An assignment statement or keywor and we need padding
	       (idlwave-surround before after))
	      ((null idlwave-pad-keyword)
	       ;; Spaces should be removed at a keyword
	       (idlwave-surround 0 0))
	      (t)))))	       

(defun idlwave-indent-and-action (&optional arg)
  "Call `idlwave-indent-line' and do expand actions.
With prefix ARG non-nil, indent the entire sub-statement."
  (interactive "p")
  (save-excursion
    (if	(and idlwave-expand-generic-end 
	     (re-search-backward "\\<\\(end\\)\\s-*\\=" 
				 (max 0 (- (point) 10)) t)
	     (looking-at "\\(end\\)\\([ \n\t]\\|\\'\\)"))
	(progn (goto-char (match-end 1))
	       ;;Expand the END abbreviation, just as RET or Space would have.
	       (if abbrev-mode (expand-abbrev)
		 (idlwave-show-begin)))))
  (if arg 
      (idlwave-indent-statement)
    (idlwave-indent-line t)))

(defun idlwave-indent-line (&optional expand)
  "Indents current IDL line as code or as a comment.
The actions in `idlwave-indent-action-table' are performed.
If the optional argument EXPAND is non-nil then the actions in
`idlwave-indent-expand-table' are performed."
  (interactive)
  ;; Move point out of left margin.
  (if (save-excursion
        (skip-chars-backward " \t")
        (bolp))
      (skip-chars-forward " \t"))
  (let ((mloc (point-marker)))
    (save-excursion
      (beginning-of-line)
      (if (looking-at idlwave-comment-line-start-skip)
          ;; Indentation for a line comment
          (progn
            (skip-chars-forward " \t")
            (idlwave-indent-left-margin (idlwave-comment-hook)))
        ;;
        ;; Code Line
        ;;
        ;; Before indenting, run action routines.
        ;;
        (if (and expand idlwave-do-actions)
            (mapcar 'idlwave-do-action idlwave-indent-expand-table))
        ;;
        (if idlwave-do-actions
            (mapcar 'idlwave-do-action idlwave-indent-action-table))
        ;;
        ;; No longer expand abbrevs on the line.  The user can do this
        ;; manually using expand-region-abbrevs.
        ;;
        ;; Indent for code line
        ;;
        (beginning-of-line)
        (if (or
             ;; a label line
             (looking-at (concat "^" idlwave-label "[ \t]*$"))
             ;; a batch command
             (looking-at "^[ \t]*@"))
            ;; leave flush left
            nil
          ;; indent the line
          (idlwave-indent-left-margin (idlwave-calculate-indent)))
        ;; Adjust parallel comment
	(end-of-line)
	(if (idlwave-in-comment)
	    ;; Emacs 21 is too smart with fill-column on comment indent
	    (let ((fill-column (if (fboundp 'comment-indent-new-line)
				   (1- (frame-width))
				 fill-column)))
	      (indent-for-comment)))))
    (goto-char mloc)
    ;; Get rid of marker
    (set-marker mloc nil)))

(defun idlwave-do-action (action)
  "Perform an action repeatedly on a line.
ACTION is a list (REG . FUNC).  REG is a regular expression.  FUNC is
either a function name to be called with `funcall' or a list to be
evaluated with `eval'.  The action performed by FUNC should leave point
after the match for REG - otherwise an infinite loop may be entered."
  (let ((action-key (car action))
        (action-routine (cdr action)))
    (beginning-of-line)
    (while (idlwave-look-at action-key)
      (if (listp action-routine)
          (eval action-routine)
        (funcall action-routine)))))

(defun idlwave-indent-to (col &optional min)
  "Indent from point with spaces until column COL.
Inserts space before markers at point."
  (if (not min) (setq min 0))
  (insert-before-markers
   (make-string (max min (- col (current-column))) ?\ )))

(defun idlwave-indent-left-margin (col)
  "Indent the current line to column COL.
Indents such that first non-whitespace character is at column COL
Inserts spaces before markers at point."
  (save-excursion
    (beginning-of-line)
    (delete-horizontal-space)
    (idlwave-indent-to col)))

(defun idlwave-indent-subprogram ()
  "Indents program unit which contains point."
  (interactive)
  (save-excursion
    (idlwave-end-of-statement)
    (idlwave-beginning-of-subprogram)
    (let ((beg (point)))
      (idlwave-forward-block)
      (message "Indenting subprogram...")
      (indent-region beg (point) nil))
    (message "Indenting subprogram...done.")))

(defun idlwave-indent-statement ()
  "Indent current statement, including all continuation lines."
  (interactive)
  (save-excursion
    (idlwave-beginning-of-statement)
    (let ((beg (point)))
      (idlwave-end-of-statement)
      (indent-region beg (point) nil))))

(defun idlwave-calculate-indent ()
  "Return appropriate indentation for current line as IDL code."
  (save-excursion
    (beginning-of-line)
    (cond
     ;; Check for beginning of unit - main (beginning of buffer), pro, or
     ;; function
     ((idlwave-look-at idlwave-begin-unit-reg)
      0)
     ;; Check for continuation line
     ((save-excursion
        (and (= (forward-line -1) 0)
             (idlwave-is-continuation-line)))
      (idlwave-calculate-cont-indent))
     ;; calculate indent based on previous and current statements
     (t (let ((the-indent
               ;; calculate indent based on previous statement
               (save-excursion
		 (cond
                  ((idlwave-previous-statement)
                   0)
                  ;; Main block
                  ((idlwave-look-at idlwave-begin-unit-reg t)
                   (+ (idlwave-current-statement-indent)
		      idlwave-main-block-indent))
                  ;; Begin block
                  ((idlwave-look-at idlwave-begin-block-reg t)
                   (+ (idlwave-current-statement-indent)
		      idlwave-block-indent))
                  ((idlwave-look-at idlwave-end-block-reg t)
                   (- (idlwave-current-statement-indent)
		      idlwave-end-offset
		      idlwave-block-indent))
                  ((idlwave-current-statement-indent))))))
          ;; adjust the indentation based on the current statement
          (cond
           ;; End block
           ((idlwave-look-at idlwave-end-block-reg)
	    (+ the-indent idlwave-end-offset))
           (the-indent)))))))

;;
;; Parentheses balacing/indent
;;

(defun idlwave-calculate-paren-indent (beg-reg end-reg close-exp)
  "Calculate the continuation indent inside a paren group.
Returns a cons-cell with (open . indent), where open is the 
location of the open paren"
  (let ((open (nth 1 (parse-partial-sexp beg-reg end-reg))))
    ;; Found an innermost open paren.
    (when open
      (goto-char open)
      ;; Line up with next word unless this is a closing paren.
      (cons open
	    (cond
	     ;; This is a closed paren - line up under open paren.
	     (close-exp
	      (current-column))
	     ;; Empty (or just comment) - just line up next to paren
	     ((progn
		;; Skip paren
		(forward-char 1)
		(looking-at "[ \t$]*\\(;.*\\)?$"))
	      (current-column))
	     ;; Line up with first word after blank space
	     ((progn
		(skip-chars-forward " \t")
		(current-column))))))))

(defun idlwave-calculate-cont-indent ()
  "Calculates the IDL continuation indent column from the previous statement.
Note that here previous statement means the beginning of the current
statement if this statement is a continuation of the previous line."
  (save-excursion
    (let* (open
           (case-fold-search t)
           (end-reg (progn (beginning-of-line) (point)))
           (close-exp (progn (skip-chars-forward " \t") (looking-at "\\s)")))
;           (beg-reg (progn (idlwave-previous-statement) (point)))
           (beg-reg (progn ;; Use substatement indent unless it's this line
		      (idlwave-start-of-substatement 'pre) 
		      (if (eq (line-beginning-position) end-reg)
			  (idlwave-previous-statement))
		      (point)))
	   (cur-indent (idlwave-current-indent))
	   (else-cont (and (goto-char end-reg) (looking-at "[ \t]*else")))
	   (basic-indent 	   ;; The basic, non-fancy indent
	    (+ cur-indent idlwave-continuation-indent))
	   (fancy-nonparen-indent  ;; A smarter indent for routine/assignments
	    ;; Try without parens first:
	    (progn
	      (goto-char beg-reg)
	      (while (idlwave-look-at "&"))  ; skip over continued statements
	      (cond
	       ;; A continued Procedure call or definition
	       ((progn
		  (idlwave-look-at "^[ \t]*\\(pro\\|function\\)") ;skip over
		  (looking-at "[ \t]*\\([a-zA-Z0-9$_]+[ \t]*->[ \t]*\\)?[a-zA-Z][:a-zA-Z0-9$_]*[ \t]*\\(,\\)[ \t]*"))
		(goto-char (match-end 0))
		;; Comment only, or blank line with "$"?  Align with ,
		(if (save-match-data (looking-at "[ \t$]*\\(;.*\\)?$"))
		    (goto-char (match-end 2)))
		(current-column))

	       ;; Continued assignment (with =), 
	       ((looking-at "[ \t]*[][().a-zA-Z0-9$_]+[ \t]*\\(=\\)[ \t]*")
		(goto-char (match-end 0))
		;; Comment only?  Align with =
		(if (save-match-data (looking-at "[ \t$]*\\(;.*\\)?$"))
		    (progn 
		      (goto-char (match-end 1))
		      (if idlwave-surround-by-blank 
			  (1+ (current-column))
			(current-column)))
		  (current-column))))))
	   (fancy-nonparen-indent-allowed
 	    (and fancy-nonparen-indent
		 (< (- fancy-nonparen-indent basic-indent)
		    idlwave-max-extra-continuation-indent)))
	   (fancy-paren-indent-cons     ;; A smarter indent for paren groups
	    ;; Look for any enclosing parens
	    (idlwave-calculate-paren-indent beg-reg end-reg close-exp))
	   (fancy-paren-open (car fancy-paren-indent-cons))
	   (fancy-paren-indent (cdr fancy-paren-indent-cons))
	   (fancy-paren-indent-allowed
	    (and fancy-paren-indent
		 (or idlwave-indent-to-open-paren ;; override
		     (< (- fancy-paren-indent basic-indent)
			idlwave-max-extra-continuation-indent))))
	    fancy-enclosing-parent-indent)
      (cond 
       ;; else continuations are always standard
       (else-cont 
	cur-indent)

       ;; an allowed parenthesis-indent
       (fancy-paren-indent-allowed 
	fancy-paren-indent)

       ;; a disallowed paren indent nested inside one or more other
       ;; parens: indent relative to the first allowed enclosing paren
       ;; set, if any... if it's actually a greater indent, just use
       ;; the fancy-paren-indent anyway.
       ((and fancy-paren-indent
	     (not fancy-paren-indent-allowed)
	     (setq fancy-enclosing-paren-indent
		   (let ((enclose-open fancy-paren-open)
			 enclose-indent-cons
			 enclose-indent)
		     (catch 'loop
		       (while (setq enclose-indent-cons
				    (idlwave-calculate-paren-indent 
				     beg-reg (max (1- enclose-open) beg-reg)
				     nil)
				    enclose-open   (car enclose-indent-cons)
				    enclose-indent (cdr enclose-indent-cons))
			 (if (< (- enclose-indent basic-indent)
				idlwave-max-extra-continuation-indent)
			     (throw 'loop enclose-indent)))))))
	(min fancy-paren-indent
	     (+ fancy-enclosing-paren-indent idlwave-continuation-indent)))
	       	
       ;; a disallowed paren indent inside another type: indent relative
       ((and fancy-paren-indent 	
	     (not fancy-paren-indent-allowed)
	     fancy-nonparen-indent-allowed )
	(+ fancy-nonparen-indent idlwave-continuation-indent))

       ;; an allowed nonparen-only indent
       (fancy-nonparen-indent-allowed
	fancy-nonparen-indent)

       ;; everything else
       (t 
	basic-indent)))))

(defun idlwave-find-key (key-re &optional dir nomark limit)
  "Move to next match of the regular expression KEY-RE.
Matches inside comments or string constants will be ignored.
If DIR is negative, the search will be backwards.
At a successful match, the mark is pushed unless NOMARK is non-nil.
Searches are limited to LIMIT.
Searches are case-insensitive and use a special syntax table which
treats `$' and `_' as word characters.
Return value is the beginning of the match or (in case of failure) nil."
  (setq dir (or dir 0))
  (let ((case-fold-search t)
	(search-func (if (> dir 0) 're-search-forward 're-search-backward))
	found)
    (idlwave-with-special-syntax
     (save-excursion
       (catch 'exit
	 (while (funcall search-func key-re limit t)
	   (if (not (idlwave-quoted))
	       (throw 'exit (setq found (match-beginning 0))))))))
    (if found
	(progn
	  (if (not nomark) (push-mark))
	  (goto-char found)
	  found)
      nil)))

(defun idlwave-block-jump-out (&optional dir nomark)
  "When optional argument DIR is non-negative, move forward to end of
current block using the `idlwave-begin-block-reg' and `idlwave-end-block-reg'
regular expressions. When DIR is negative, move backwards to block beginning.
Recursively calls itself to skip over nested blocks. DIR defaults to
forward. Calls `push-mark' unless the optional argument NOMARK is
non-nil. Movement is limited by the start of program units because of
possibility of unbalanced blocks."
  (interactive "P")
  (or dir (setq dir 0))
  (let* ((here (point))
         (case-fold-search t)
         (limit (if (>= dir 0) (point-max) (point-min)))
         (block-limit (if (>= dir 0) 
			  idlwave-begin-block-reg
			idlwave-end-block-reg))
         found
         (block-reg (concat idlwave-begin-block-reg "\\|"
			    idlwave-end-block-reg))
         (unit-limit (or (save-excursion
			   (if (< dir 0)
			       (idlwave-find-key
				idlwave-begin-unit-reg dir t limit)
			     (end-of-line)
			     (idlwave-find-key 
			      idlwave-end-unit-reg dir t limit)))
			 limit)))
    (if (>= dir 0) (end-of-line)) ;Make sure we are in current block
    (if (setq found (idlwave-find-key  block-reg dir t unit-limit))
        (while (and found (looking-at block-limit))
          (if (>= dir 0) (forward-word 1))
          (idlwave-block-jump-out dir t)
          (setq found (idlwave-find-key block-reg dir t unit-limit))))
    (if (not nomark) (push-mark here))
    (if (not found) (goto-char unit-limit)
      (if (>= dir 0) (forward-word 1)))))

(defun idlwave-current-statement-indent ()
  "Return indentation of the current statement.
If in a statement, moves to beginning of statement before finding indent."
  (idlwave-beginning-of-statement)
  (idlwave-current-indent))

(defun idlwave-current-indent ()
  "Return the column of the indentation of the current line.
Skips any whitespace. Returns 0 if the end-of-line follows the whitespace."
  (save-excursion
    (beginning-of-line)
    (skip-chars-forward " \t")
    ;; if we are at the end of blank line return 0
    (cond ((eolp) 0)
          ((current-column)))))

(defun idlwave-is-continuation-line ()
  "Tests if current line is continuation line.
Blank or comment-only lines following regular continuation lines (with
`$') count as continuations too."
  (save-excursion
    (or 
     (idlwave-look-at "\\<\\$")
     (catch 'loop
       (while (and (looking-at "^[ \t]*\\(;.*\\)?$") 
		   (eq (forward-line -1) 0))
	 (if (idlwave-look-at "\\<\\$") (throw 'loop t)))))))

(defun idlwave-is-comment-line ()
  "Tests if the current line is a comment line."
  (save-excursion
    (beginning-of-line 1)
    (looking-at "[ \t]*;")))

(defun idlwave-is-comment-or-empty-line ()
  "Tests if the current line is a comment line."
  (save-excursion
    (beginning-of-line 1)
    (looking-at "[ \t]*[;\n]")))

(defun idlwave-look-at (regexp &optional cont beg)
  "Searches current line from current point for REGEXP.
If optional argument CONT is non-nil, searches to the end of
the current statement.
If optional arg BEG is non-nil, search starts from the beginning of the
current statement.
Ignores matches that end in a comment or inside a string expression.
Returns point if successful, nil otherwise.
This function produces unexpected results if REGEXP contains quotes or
a comment delimiter. The search is case insensitive.
If successful leaves point after the match, otherwise, does not move point."
  (let ((here (point))
        (case-fold-search t)
        (eos (save-excursion
	       (if cont (idlwave-end-of-statement) (end-of-line))
	       (point)))
        found)
    (idlwave-with-special-syntax
     (if beg (idlwave-beginning-of-statement))
     (while (and (setq found (re-search-forward regexp eos t))
		 (idlwave-quoted))))
    (if (not found) (goto-char here))
    found))

(defun idlwave-fill-paragraph (&optional nohang)
  "Fills paragraphs in comments.
A paragraph is made up of all contiguous lines having the same comment
leader (the leading whitespace before the comment delimiter and the
comment delimiter).  In addition, paragraphs are separated by blank
line comments. The indentation is given by the hanging indent of the
first line, otherwise by the minimum indentation of the lines after
the first line. The indentation of the first line does not change.
Does not effect code lines. Does not fill comments on the same line
with code.  The hanging indent is given by the end of the first match
matching `idlwave-hang-indent-regexp' on the paragraph's first line . If the
optional argument NOHANG is non-nil then the hanging indent is
ignored."
  (interactive "P")
  ;; check if this is a line comment
  (if (save-excursion
        (beginning-of-line)
        (skip-chars-forward " \t")
        (looking-at comment-start))
      (let
          ((indent 999)
           pre here diff fill-prefix-reg bcl first-indent
           hang start end)
        ;; Change tabs to spaces in the surrounding paragraph.
        ;; The surrounding paragraph will be the largest containing block of
        ;; contiguous line comments. Thus, we may be changing tabs in
        ;; a much larger area than is needed, but this is the easiest
        ;; brute force way to do it.
        ;;
        ;; This has the undesirable side effect of replacing the tabs
        ;; permanently without the user's request or knowledge.
        (save-excursion
          (backward-paragraph)
          (setq start (point)))
        (save-excursion
          (forward-paragraph)
          (setq end (point)))
        (untabify start end)
        ;;
        (setq here (point))
        (beginning-of-line)
        (setq bcl (point))
        (re-search-forward
         (concat "^[ \t]*" comment-start "+")
         (save-excursion (end-of-line) (point))
         t)
        ;; Get the comment leader on the line and its length
        (setq pre (current-column))
        ;; the comment leader is the indentation plus exactly the
        ;; number of consecutive ";".
        (setq fill-prefix-reg
              (concat
               (setq fill-prefix
                     (regexp-quote
                      (buffer-substring (save-excursion
                                          (beginning-of-line) (point))
                                        (point))))
               "[^;]"))
	
        ;; Mark the beginning and end of the paragraph
        (goto-char bcl)
        (while (and (looking-at fill-prefix-reg)
                    (not (looking-at paragraph-separate))
                    (not (bobp)))
          (forward-line -1))
        ;; Move to first line of paragraph
        (if (/= (point) bcl)
            (forward-line 1))
        (setq start (point))
        (goto-char bcl)
        (while (and (looking-at fill-prefix-reg)
                    (not (looking-at paragraph-separate))
                    (not (eobp)))
          (forward-line 1))
        (beginning-of-line)
        (if (or (not (looking-at fill-prefix-reg))
                (looking-at paragraph-separate))
            (forward-line -1))
        (end-of-line)
        ;; if at end of buffer add a newline (need this because
        ;; fill-region needs END to be at the beginning of line after
        ;; the paragraph or it will add a line).
        (if (eobp)
            (progn (insert ?\n) (backward-char 1)))
        ;; Set END to the beginning of line after the paragraph
        ;; END is calculated as distance from end of buffer
        (setq end (- (point-max) (point) 1))
        ;;
        ;; Calculate the indentation for the paragraph.
        ;;
        ;; In the following while statements, after one iteration
        ;; point will be at the beginning of a line in which case
        ;; the while will not be executed for the
        ;; the first paragraph line and thus will not affect the
        ;; indentation.
        ;;
        ;; First check to see if indentation is based on hanging indent.
        (if (and (not nohang) idlwave-hanging-indent
                 (setq hang
                       (save-excursion
                         (goto-char start)
                         (idlwave-calc-hanging-indent))))
            ;; Adjust lines of paragraph by inserting spaces so that
            ;; each line's indent is at least as great as the hanging
            ;; indent. This is needed for fill-paragraph to work with
            ;; a fill-prefix.
            (progn
              (setq indent hang)
              (beginning-of-line)
              (while (> (point) start)
                (re-search-forward comment-start-skip
                                   (save-excursion (end-of-line) (point))
                                   t)
                (if (> (setq diff (- indent (current-column))) 0)
                    (progn
                      (if (>= here (point))
                          ;; adjust the original location for the
                          ;; inserted text.
                          (setq here (+ here diff)))
                      (insert (make-string diff ?\ ))))
                (forward-line -1))
              )
	  
          ;; No hang. Instead find minimum indentation of paragraph
          ;; after first line.
          ;; For the following while statement, since START is at the
          ;; beginning of line and END is at the end of line
          ;; point is greater than START at least once (which would
          ;; be the case for a single line paragraph).
          (while (> (point) start)
            (beginning-of-line)
            (setq indent
                  (min indent
                       (progn
                         (re-search-forward
                          comment-start-skip
                          (save-excursion (end-of-line) (point))
                          t)
                         (current-column))))
            (forward-line -1))
          )
        (setq fill-prefix (concat fill-prefix
                                  (make-string (- indent pre)
                                               ?\ )))
        ;; first-line indent
        (setq first-indent
              (max
               (progn
                 (re-search-forward
                  comment-start-skip
                  (save-excursion (end-of-line) (point))
                  t)
                 (current-column))
               indent))
	
        ;; try to keep point at its original place
        (goto-char here)

        ;; In place of the more modern fill-region-as-paragraph, a hack
        ;; to keep whitespace untouched on the first line within the
        ;; indent length and to preserve any indent on the first line
        ;; (first indent).
        (save-excursion
          (setq diff
                (buffer-substring start (+ start first-indent -1)))
          (subst-char-in-region start (+ start first-indent -1) ?\  ?~ nil)
          (fill-region-as-paragraph
           start
           (- (point-max) end)
           (current-justification)
           nil)
          (delete-region start (+ start first-indent -1))
          (goto-char start)
          (insert diff))
        ;; When we want the point at the beginning of the comment
        ;; body fill-region will put it at the beginning of the line.
        (if (bolp) (skip-chars-forward (concat " \t" comment-start)))
        (setq fill-prefix nil))))

(defun idlwave-calc-hanging-indent ()
  "Calculate the position of the hanging indent for the comment
paragraph.  The hanging indent position is given by the first match
with the `idlwave-hang-indent-regexp'.  If `idlwave-use-last-hang-indent' is
non-nil then use last occurrence matching `idlwave-hang-indent-regexp' on
the line.
If not found returns nil."
  (if idlwave-use-last-hang-indent
      (save-excursion
        (end-of-line)
        (if (re-search-backward
             idlwave-hang-indent-regexp
             (save-excursion (beginning-of-line) (point))
             t)
            (+ (current-column) (length idlwave-hang-indent-regexp))))
    (save-excursion
      (beginning-of-line)
      (if (re-search-forward
           idlwave-hang-indent-regexp
           (save-excursion (end-of-line) (point))
           t)
          (current-column)))))

(defun idlwave-auto-fill ()
  "Called to break lines in auto fill mode.
Only fills comment lines if `idlwave-fill-comment-line-only' is non-nil.
Places a continuation character at the end of the line
if not in a comment.  Splits strings with IDL concatenation operator
`+' if `idlwave-auto-fill-split-string is non-nil."
  (if (<= (current-column) fill-column)
      nil                             ; do not to fill
    (if (or (not idlwave-fill-comment-line-only)
	    (save-excursion
	      ;; Check for comment line
	      (beginning-of-line)
	      (looking-at idlwave-comment-line-start-skip)))
	(let (beg)
	  (idlwave-indent-line)
	  ;; Prevent actions do-auto-fill which calls indent-line-function.
	  (let (idlwave-do-actions
		(paragraph-start ".")
		(paragraph-separate "."))
	    (do-auto-fill))
	  (save-excursion
	    (end-of-line 0)
	    ;; Indent the split line
	    (idlwave-indent-line)
	    )
	  (if (save-excursion
		(beginning-of-line)
		(looking-at idlwave-comment-line-start-skip))
	      ;; A continued line comment
	      ;; We treat continued line comments as part of a comment
	      ;; paragraph. So we check for a hanging indent.
	      (if idlwave-hanging-indent
		  (let ((here (- (point-max) (point)))
			(indent
			 (save-excursion
			   (forward-line -1)
			   (idlwave-calc-hanging-indent))))
		    (if indent
			(progn
			  ;; Remove whitespace between comment delimiter and
			  ;; text, insert spaces for appropriate indentation.
			  (beginning-of-line)
			  (re-search-forward
			   comment-start-skip
			   (save-excursion (end-of-line) (point)) t)
			  (delete-horizontal-space)
			  (idlwave-indent-to indent)
			  (goto-char (- (point-max) here)))
		      )))
	    ;; Split code or comment?
	    (if (save-excursion
		  (end-of-line 0)
		  (idlwave-in-comment))
		;; Splitting a non-line comment.
		;; Insert the comment delimiter from split line
		(progn
		  (save-excursion
		    (beginning-of-line)
		    (skip-chars-forward " \t")
		    ;; Insert blank to keep off beginning of line
		    (insert " "
			    (save-excursion
			      (forward-line -1)
			      (buffer-substring (idlwave-goto-comment)
						(progn
						  (skip-chars-forward "; ")
						  (point))))))
		  (idlwave-indent-line))
	      ;; Split code line - add continuation character
	      (save-excursion
		(end-of-line 0)
		;; Check to see if we split a string
		(if (and (setq beg (idlwave-in-quote))
			 idlwave-auto-fill-split-string)
		    ;; Split the string and concatenate.
		    ;; The first extra space is for the space
		    ;; the line was split. That space was removed.
		    (insert " " (char-after beg) " +"))
		(insert " $"))
	      (if beg
		  (if idlwave-auto-fill-split-string
		      ;; Make the second part of continued string
		      (save-excursion
			(beginning-of-line)
			(skip-chars-forward " \t")
			(insert (char-after beg)))
		    ;; Warning
		    (beep)
		    (message "Warning: continuation inside a string.")))
	      ;; Although do-auto-fill (via indent-new-comment-line) calls
	      ;; idlwave-indent-line for the new line, re-indent again
	      ;; because of the addition of the continuation character.
	      (idlwave-indent-line))
	    )))))

(defun idlwave-auto-fill-mode (arg)
  "Toggle auto-fill mode for IDL mode.
With arg, turn auto-fill mode on if arg is positive.
In auto-fill mode, inserting a space at a column beyond `fill-column'
automatically breaks the line at a previous space."
  (interactive "P")
  (prog1 (set idlwave-fill-function
              (if (if (null arg)
                      (not (symbol-value idlwave-fill-function))
                    (> (prefix-numeric-value arg) 0))
                  'idlwave-auto-fill
                nil))
    ;; update mode-line
    (set-buffer-modified-p (buffer-modified-p))))

(defun idlwave-doc-header (&optional nomark )
  "Insert a documentation header at the beginning of the unit.
Inserts the value of the variable idlwave-file-header. Sets mark before
moving to do insertion unless the optional prefix argument NOMARK
is non-nil."
  (interactive "P")
  (or nomark (push-mark))
  ;; make sure we catch the current line if it begins the unit
  (if idlwave-header-to-beginning-of-file
      (goto-char (point-min))
    (end-of-line)
    (idlwave-beginning-of-subprogram)
    (beginning-of-line)
    ;; skip function or procedure line
    (if (idlwave-look-at "\\<\\(pro\\|function\\)\\>")
	(progn
	  (idlwave-end-of-statement)
	  (if (> (forward-line 1) 0) (insert "\n")))))
  (let ((pos (point)))
    (if idlwave-file-header
	(cond ((car idlwave-file-header)
	       (insert-file (car idlwave-file-header)))
	      ((stringp (car (cdr idlwave-file-header)))
	       (insert (car (cdr idlwave-file-header))))))
    (goto-char pos)))

(defun idlwave-default-insert-timestamp ()
  "Default timestamp insertion function"
  (insert (current-time-string))
  (insert ", " (user-full-name))
  (if (boundp 'user-mail-address)
      (insert " <" user-mail-address ">") 
    (insert " <" (user-login-name) "@" (system-name) ">"))
  ;; Remove extra spaces from line
  (idlwave-fill-paragraph)
  ;; Insert a blank line comment to separate from the date entry -
  ;; will keep the entry from flowing onto date line if re-filled.
  (insert "\n;\n;\t\t"))

(defun idlwave-doc-modification ()
  "Insert a brief modification log at the beginning of the current program.
Looks for an occurrence of the value of user variable
`idlwave-doc-modifications-keyword' if non-nil. Inserts time and user name
and places the point for the user to add a log. Before moving, saves
location on mark ring so that the user can return to previous point."
  (interactive)
  (push-mark)
  (let* (beg end)
    (if (and (or (re-search-backward idlwave-doclib-start nil t)
		 (progn
		   (goto-char (point-min))
		   (re-search-forward idlwave-doclib-start nil t)))
	     (setq beg (match-beginning 0))
	     (re-search-forward idlwave-doclib-end nil t)
	     (setq end (match-end 0)))
	(progn
	  (goto-char beg)
	  (if (re-search-forward 
	       (concat idlwave-doc-modifications-keyword ":")
	       end t)
	      (end-of-line)
	    (goto-char end)
	    (end-of-line -1)
	    (insert "\n" comment-start "\n")
	    (insert comment-start " " idlwave-doc-modifications-keyword ":"))
	  (insert "\n;\n;\t")
	  (run-hooks 'idlwave-timestamp-hook))
      (error "No valid DOCLIB header"))))

;;; CJC 3/16/93
;;; Interface to expand-region-abbrevs which did not work when the
;;; abbrev hook associated with an abbrev moves point backwards
;;; after abbrev expansion, e.g., as with the abbrev '.n'.
;;; The original would enter an infinite loop in attempting to expand
;;; .n (it would continually expand and unexpand the abbrev without expanding
;;; because the point would keep going back to the beginning of the
;;; abbrev instead of to the end of the abbrev). We now keep the
;;; abbrev hook from moving backwards.
;;;
(defun idlwave-expand-region-abbrevs (start end)
  "Expand each abbrev occurrence in the region.
Calling from a program, arguments are START END."
  (interactive "r")
  (save-excursion
    (goto-char (min start end))
    (let ((idlwave-show-block nil)          ;Do not blink
          (idlwave-abbrev-move nil))        ;Do not move
      (expand-region-abbrevs start end 'noquery))))

(defun idlwave-quoted ()
  "Returns t if point is in a comment or quoted string.
nil otherwise."
  (or (idlwave-in-comment) (idlwave-in-quote)))

(defun idlwave-in-quote ()
  "Returns location of the opening quote
if point is in a IDL string constant, nil otherwise.
Ignores comment delimiters on the current line.
Properly handles nested quotation marks and octal
constants - a double quote followed by an octal digit."
;;; Treat an octal inside an apostrophe to be a normal string. Treat a
;;; double quote followed by an octal digit to be an octal constant
;;; rather than a string. Therefore, there is no terminating double
;;; quote.
  (save-excursion
    ;; Because single and double quotes can quote each other we must
    ;; search for the string start from the beginning of line.
    (let* ((start (point))
           (eol (progn (end-of-line) (point)))
           (bq (progn (beginning-of-line) (point)))
           (endq (point))
           (data (match-data))
           delim
           found)
      (while  (< endq start)
	;; Find string start
	;; Don't find an octal constant beginning with a double quote
	(if (re-search-forward "\"[^0-7]\\|'\\|\"$" eol 'lim)
	    ;; Find the string end.
	    ;; In IDL, two consecutive delimiters after the start of a
	    ;; string act as an
	    ;; escape for the delimiter in the string.
	    ;; Two consecutive delimiters alone (i.e., not after the
	    ;; start of a string) is the null string.
	    (progn
	      ;; Move to position after quote
	      (goto-char (1+ (match-beginning 0)))
	      (setq bq (1- (point)))
	      ;; Get the string delimiter
	      (setq delim (char-to-string (preceding-char)))
	      ;; Check for null string
	      (if (looking-at delim)
		  (progn (setq endq (point)) (forward-char 1))
		;; Look for next unpaired delimiter
		(setq found (search-forward delim eol 'lim))
		(while (looking-at delim)
		  (forward-char 1)
		  (setq found (search-forward delim eol 'lim)))
		(if found
		    (setq endq (- (point) 1))
		  (setq endq (point)))
		))
	  (progn (setq bq (point)) (setq endq (point)))))
      (store-match-data data)
      ;; return string beginning position or nil
      (if (> start bq) bq))))

(defun idlwave-is-pointer-dereference (&optional limit)
  "Determines if the character after point is a pointer dereference *."
  (let ((pos (point)))
    (and
     (eq (char-after) ?\*)
     (not (idlwave-in-quote))
     (save-excursion
       (forward-char)
       (re-search-backward (concat "\\(" idlwave-idl-keywords 
				   "\\|[[(*+-/=,^><]\\)\\s-*\\*") limit t)))))


;; Statement templates

;; Replace these with a general template function, something like
;; expand.el (I think there was also something with a name similar to
;; dmacro.el)

(defun idlwave-template (s1 s2 &optional prompt noindent)
  "Build a template with optional prompt expression.

Opens a line if point is not followed by a newline modulo intervening
whitespace.  S1 and S2 are strings.  S1 is inserted at point followed
by S2.  Point is inserted between S1 and S2.  The case of S1 and S2 is
adjusted according to `idlwave-abbrev-change-case'.  If optional argument
PROMPT is a string then it is displayed as a message in the
minibuffer.  The PROMPT serves as a reminder to the user of an
expression to enter.

The lines containing S1 and S2 are reindented using `indent-region'
unless the optional second argument NOINDENT is non-nil."
  (if (eq major-mode 'idlwave-shell-mode)
      ;; This is a gross hack to avoit template abbrev expansion
      ;; in the shell.  FIXME: This is a dirty hack.
      (if (and (eq this-command 'self-insert-command)
	       (equal last-abbrev-location (point)))
	  (insert last-abbrev-text)
	(error "No templates in idlwave-shell"))
    (cond ((eq idlwave-abbrev-change-case 'down)
	   (setq s1 (downcase s1) s2 (downcase s2)))
	  (idlwave-abbrev-change-case
	   (setq s1 (upcase s1) s2 (upcase s2))))
    (let ((beg (save-excursion (beginning-of-line) (point)))
	  end)
      (if (not (looking-at "\\s-*\n"))
	  (open-line 1))
      (insert s1)
      (save-excursion
	(insert s2)
	(setq end (point)))
      (if (not noindent)
	  (indent-region beg end nil))
      (if (stringp prompt)
	  (message prompt)))))
  
(defun idlwave-rw-case (string)
  "Make STRING have the case required by `idlwave-reserved-word-upcase'."
  (if idlwave-reserved-word-upcase
      (upcase string)
    string))

(defun idlwave-elif ()
  "Build skeleton IDL if-else block."
  (interactive)
  (idlwave-template
   (idlwave-rw-case "if")
   (idlwave-rw-case " then begin\n\nendif else begin\n\nendelse")
   "Condition expression"))

(defun idlwave-case ()
  "Build skeleton IDL case statement."
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "case")
   (idlwave-rw-case " of\n\nendcase")
   "Selector expression"))

(defun idlwave-switch ()
  "Build skeleton IDL switch statement."
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "switch")
   (idlwave-rw-case " of\n\nendswitch")
   "Selector expression"))

(defun idlwave-for ()
  "Build skeleton for loop statment."
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "for")
   (idlwave-rw-case " do begin\n\nendfor")
   "Loop expression"))

(defun idlwave-if ()
  "Build skeleton for loop statment."
  (interactive)
  (idlwave-template
   (idlwave-rw-case "if")
   (idlwave-rw-case " then begin\n\nendif")
   "Scalar logical expression"))

(defun idlwave-procedure ()
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "pro")
   (idlwave-rw-case "\n\nreturn\nend")
   "Procedure name"))

(defun idlwave-function ()
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "function")
   (idlwave-rw-case "\n\nreturn\nend")
   "Function name"))

(defun idlwave-repeat ()
  (interactive)
  (idlwave-template
   (idlwave-rw-case "repeat begin\n\nendrep until")
   (idlwave-rw-case "")
   "Exit condition"))

(defun idlwave-while ()
  (interactive)
  (idlwave-template 
   (idlwave-rw-case "while")
   (idlwave-rw-case " do begin\n\nendwhile")
   "Entry condition"))

(defun idlwave-split-string (string &optional pattern)
  "Return a list of substrings of STRING which are separated by PATTERN.
If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
  (or pattern
      (setq pattern "[ \f\t\n\r\v]+"))
  (let (parts (start 0))
    (while (string-match pattern string start)
      (setq parts (cons (substring string start (match-beginning 0)) parts)
	    start (match-end 0)))
    (nreverse (cons (substring string start) parts))))

(defun idlwave-replace-string (string replace_string replace_with)
  (let* ((start 0)
	 (last (length string))
	 (ret_string "")
	 end)
    (while (setq end (string-match replace_string string start))
      (setq ret_string
	    (concat ret_string (substring string start end) replace_with))
      (setq start (match-end 0)))
    (setq ret_string (concat ret_string (substring string start last)))))

(defun idlwave-get-buffer-visiting (file)
  ;; Return the buffer currently visiting FILE
  (cond
   ((boundp 'find-file-compare-truenames) ; XEmacs
    (let ((find-file-compare-truenames t))
      (get-file-buffer file)))
   ((fboundp 'find-buffer-visiting)       ; Emacs
    (find-buffer-visiting file))
   (t (error "This should not happen (idlwave-get-buffer-visiting)"))))

(defvar idlwave-outlawed-buffers nil
  "List of buffer pulled up by idlwave for special reasons.
Buffers in this list may be killed by `idlwave-kill-autoloaded-buffers'.")

(defun idlwave-find-file-noselect (file &optional why)
  ;; Return a buffer visiting file.
  (or (idlwave-get-buffer-visiting file)
      (let ((buf (find-file-noselect file)))
	(if why (add-to-list 'idlwave-outlawed-buffers (cons buf why)))
	buf)))

(defun idlwave-kill-autoloaded-buffers ()
  "Cleanup by killing buffers created automatically by IDLWAVE.
Function prompts for a letter to identify the buffers to kill.
Possible letters are:

f    Buffers created by the command \\[idlwave-find-module] or mouse
     clicks in the routine info window.
s    Buffers created by the IDLWAVE Shell to display where execution
     stopped or an error was found.
a    Both of the above.

Buffer containing unsaved changes require confirmation before they are killed."
  (interactive)
  (if (null idlwave-outlawed-buffers)
      (error "No IDLWAVE-created buffers available")
    (princ (format "Kill IDLWAVE-created buffers: [f]ind source(%d), [s]hell display(%d), [a]ll ? "
		   (idlwave-count-outlawed-buffers 'find)
		   (idlwave-count-outlawed-buffers 'shell)))
    (let ((c (read-char)))
      (cond
       ((member c '(?f ?\C-f))
	(idlwave-do-kill-autoloaded-buffers 'find))
       ((member c '(?s ?\C-s))
	(idlwave-do-kill-autoloaded-buffers 'shell))
       ((member c '(?a ?\C-a))
	(idlwave-do-kill-autoloaded-buffers t))
       (t (error "Abort"))))))

(defun idlwave-count-outlawed-buffers (tag)
  "How many outlawed buffers have tag TAG?"
  (length (delq nil
		(mapcar 
		 (lambda (x) (eq (cdr x) tag)) 
		 idlwave-outlawed-buffers))))

(defun idlwave-do-kill-autoloaded-buffers (&rest reasons)
  "Kill all buffers pulled up by IDLWAVE matching REASONS."
  (let* ((list (copy-sequence idlwave-outlawed-buffers))
	 (cnt 0)
	 entry)
    (while (setq entry (pop list))
      (if (buffer-live-p (car entry))
	  (and (or (memq t reasons)
		   (memq (cdr entry) reasons))
	       (kill-buffer (car entry))
	       (incf cnt)
	       (setq idlwave-outlawed-buffers 
		     (delq entry idlwave-outlawed-buffers)))
	(setq idlwave-outlawed-buffers 
	      (delq entry idlwave-outlawed-buffers))))
    (message "%d buffer%s killed" cnt (if (= cnt 1) "" "s"))))

(defun idlwave-revoke-license-to-kill ()
  "Remove BUFFER from the buffers which may be killed.
Killing would be done by `idlwave-do-kill-autoloaded-buffers'.
Intended for `after-save-hook'."
  (let* ((buf (current-buffer))
	 (entry (assq buf idlwave-outlawed-buffers)))
    ;; Revoke license
    (if entry
	(setq idlwave-outlawed-buffers 
	      (delq entry idlwave-outlawed-buffers)))
    ;; Remove this function from the hook.
    (remove-hook 'after-save-hook 'idlwave-revoke-license-to-kill 'local)))

(defvar idlwave-path-alist)
(defun idlwave-locate-lib-file (file)
  ;; Find FILE on the scanned lib path and return a buffer visiting it
  (let* ((dirs idlwave-path-alist)
	 dir efile)
    (catch 'exit
      (while (setq dir (car (pop dirs)))
	(if (file-regular-p
	     (setq efile (expand-file-name file dir)))
	    (throw 'exit efile))))))
(defun idlwave-expand-lib-file-name (file)
  ;; Find FILE on the scanned lib path and return a buffer visiting it
  (cond 
   ((null file) nil)
   ((string-match "\\`\\({\\([0-9]+\\)}/\\)\\(.*\\)" file)
    (expand-file-name (match-string 3 file)
		      (car (nth (1- (string-to-int (match-string 2 file)))
				idlwave-path-alist))))
   ((file-name-absolute-p file) file)
   (t (idlwave-locate-lib-file file))))

(defun idlwave-make-tags ()
  "Creates the IDL tags file IDLTAGS in the current directory from
the list of directories specified in the minibuffer. Directories may be
for example: . /usr/local/rsi/idl/lib. All the subdirectories of the
specified top directories are searched if the directory name is prefixed
by @. Specify @ directories with care, it may take a long, long time if
you specify /."
  (interactive)
  (let (directory directories cmd append status numdirs dir getsubdirs
		  buffer save_buffer files numfiles item errbuf)
    
    ;;
    ;; Read list of directories
    (setq directory (read-string "Tag Directories: " "."))
    (setq directories (idlwave-split-string directory "[ \t]+"))
    ;;
    ;; Set etags command, vars
    (setq cmd "etags --output=IDLTAGS --language=none --regex='/[
\\t]*[pP][Rr][Oo][ \\t]+\\([^ \\t,]+\\)/' --regex='/[
\\t]*[Ff][Uu][Nn][Cc][Tt][Ii][Oo][Nn][ \\t]+\\([^ \\t,]+\\)/' ")
    (setq append " ")
    (setq status 0)
    ;;
    ;; For each directory
    (setq numdirs 0)
    (setq dir (nth numdirs directories))
    (while (and dir)
      ;;
      ;; Find the subdirectories
      (if (string-match "^[@]\\(.+\\)$" dir)
	  (setq getsubdirs t) (setq getsubdirs nil))
      (if (and getsubdirs) (setq dir (substring dir 1 (length dir))))
      (setq dir (expand-file-name dir))
      (if (file-directory-p dir)
	  (progn
	    (if (and getsubdirs)
		(progn
		  (setq buffer (get-buffer-create "*idltags*"))
		  (call-process "sh" nil buffer nil "-c"
				(concat "find " dir " -type d -print"))
		  (setq save_buffer (current-buffer))
		  (set-buffer buffer)
		  (setq files (idlwave-split-string
			       (idlwave-replace-string
				(buffer-substring 1 (point-max))
				"\n" "/*.pro ")
			       "[ \t]+"))
		  (set-buffer save_buffer)
		  (kill-buffer buffer))
	      (setq files (list (concat dir "/*.pro"))))
	    ;;
	    ;; For each subdirectory
	    (setq numfiles 0)
	    (setq item (nth numfiles files))
	    (while (and item)
	      ;;
	      ;; Call etags
	      (if (not (string-match "^[ \\t]*$" item))
		  (progn
		    (message (concat "Tagging " item "..."))
		    (setq errbuf (get-buffer-create "*idltags-error*"))
		    (setq status (+ status
				    (call-process "sh" nil errbuf nil "-c"
						  (concat cmd append item))))
		    ;;
		    ;; Append additional tags
		    (setq append " --append ")
		    (setq numfiles (1+ numfiles))
		    (setq item (nth numfiles files)))
		(progn
		  (setq numfiles (1+ numfiles))
		  (setq item (nth numfiles files))
		  )))
	    
	    (setq numdirs (1+ numdirs))
	    (setq dir (nth numdirs directories)))
	(progn
	  (setq numdirs (1+ numdirs))
	  (setq dir (nth numdirs directories)))))
    
    (setq errbuf (get-buffer-create "*idltags-error*"))
    (if (= status 0)
	(kill-buffer errbuf))
    (message "")
    ))

(defun idlwave-toggle-comment-region (beg end &optional n)
  "Comment the lines in the region if the first non-blank line is
commented, and conversely, uncomment region. If optional prefix arg
N is non-nil, then for N positive, add N comment delimiters or for N
negative, remove N comment delimiters.
Uses `comment-region' which does not place comment delimiters on
blank lines."
  (interactive "r\nP")
  (if n
      (comment-region beg end (prefix-numeric-value n))
    (save-excursion
      (goto-char beg)
      (beginning-of-line)
      ;; skip blank lines
      (skip-chars-forward " \t\n")
      (if (looking-at (concat "[ \t]*\\(" comment-start "+\\)"))
          (comment-region beg end
                          (- (length (buffer-substring
                                      (match-beginning 1)
                                      (match-end 1)))))
        (comment-region beg end)))))


;; ----------------------------------------------------------------------------
;; ----------------------------------------------------------------------------
;; ----------------------------------------------------------------------------
;; ----------------------------------------------------------------------------
;;
;; Completion and Routine Info
;;

;; String "intern" functions

;; For the completion and routine info function, we want to normalize
;; the case of procedure names etc.  We do this by "interning" these
;; string is a hand-crafted way.  Hashes are used to map the downcase
;; version of the strings to the cased versions.  Since these cased
;; versions are really lisp objects, we can use `eq' to search, which
;; is a large performance boost.
;; All new strings need to be "sinterned".  We do this as early as
;; possible after getting these strings from completion or buffer
;; substrings.  So most of the code can simply assume to deal with
;; "sinterned" strings.  The only exception is that the functions
;; which scan whole buffers for routine information do not intern the
;; grabbed strings.  This is only done afterwards.  Therefore in these 
;; functions it is *not* safe to assume the strings can be compared
;; with `eq' and be fed into the routine assq functions.

;; Here we define the hashing functions.

;; The variables which hold the hashes.
(defvar idlwave-sint-routines '(nil))
(defvar idlwave-sint-keywords '(nil))
(defvar idlwave-sint-methods  '(nil))
(defvar idlwave-sint-classes  '(nil))
(defvar idlwave-sint-files    '(nil))

(defun idlwave-reset-sintern (&optional what)
  "Reset all sintern hashes."
  ;; Make sure the hash functions are accessible.
  (if (or (not (fboundp 'gethash))
	  (not (fboundp 'puthash)))
      (progn 
	(require 'cl)
	(or (fboundp 'puthash)
	    (defalias 'puthash 'cl-puthash))))
  (let ((entries '((idlwave-sint-routines 1000 10)
		   (idlwave-sint-keywords 1000 10)
		   (idlwave-sint-methods   100 10)
		   (idlwave-sint-classes    10 10))))

    ;; Make sure these are lists
    (loop for entry in entries
      for var = (car entry)
      do (if (not (consp (symbol-value var))) (set var (list nil))))

    (when (or (eq what t) (eq what 'syslib)
	      (null (cdr idlwave-sint-routines)))
      ;; Reset the system & library hash
      (loop for entry in entries
	for var = (car entry) for size = (nth 1 entry)
	do (setcdr (symbol-value var) 
		   (make-hash-table ':size size ':test 'equal)))
      (setq idlwave-sint-files nil))

    (when (or (eq what t) (eq what 'bufsh)
	      (null (car idlwave-sint-routines)))
      ;; Reset the buffer & shell hash
      (loop for entry in entries
	for var = (car entry) for size = (nth 1 entry)
	do (setcar (symbol-value var) 
		   (make-hash-table ':size size ':test 'equal))))))

(defun idlwave-sintern-routine-or-method (name &optional class set)
  (if class
      (idlwave-sintern-method name set)
    (idlwave-sintern-routine name set)))

(defun idlwave-sintern (stype &rest args)
  (apply (intern (concat "idlwave-sintern-" (symbol-name stype))) args))

;;(defmacro idlwave-sintern (type var)
;;  `(cond ((not (stringp name)) name)
;;	 ((gethash (downcase name) (cdr ,var)))
;;	 ((gethash (downcase name) (car ,var)))
;;	 (set (idlwave-sintern-set name ,type ,var set))
;;	 (name)))

(defun idlwave-sintern-routine (name &optional set)
  (cond ((not (stringp name)) name)
	((gethash (downcase name) (cdr idlwave-sint-routines)))
	((gethash (downcase name) (car idlwave-sint-routines)))
	(set (idlwave-sintern-set name 'routine idlwave-sint-routines set))
	(name)))
(defun idlwave-sintern-keyword (name &optional set)
  (cond ((not (stringp name)) name)
	((gethash (downcase name) (cdr idlwave-sint-keywords)))
	((gethash (downcase name) (car idlwave-sint-keywords)))
	(set (idlwave-sintern-set name 'keyword idlwave-sint-keywords set))
	(name)))
(defun idlwave-sintern-method (name &optional set)
  (cond ((not (stringp name)) name)
	((gethash (downcase name) (cdr idlwave-sint-methods)))
	((gethash (downcase name) (car idlwave-sint-methods)))
	(set (idlwave-sintern-set name 'method idlwave-sint-methods set))
	(name)))
(defun idlwave-sintern-class (name &optional set)
  (cond ((not (stringp name)) name)
	((gethash (downcase name) (cdr idlwave-sint-classes)))
	((gethash (downcase name) (car idlwave-sint-classes)))
	(set (idlwave-sintern-set name 'class idlwave-sint-classes set))
	(name)))

(defun idlwave-sintern-file (name &optional set)
  (car (or (member name idlwave-sint-files)
	   (setq idlwave-sint-files (cons name idlwave-sint-files)))))

(defun idlwave-sintern-set (name type tables set)
  (let* ((func (or (cdr (assq type idlwave-completion-case))
		   'identity))
	 (iname (funcall (if (eq func 'preserve) 'identity func) name))
	 (table (if (eq set 'sys) (cdr tables) (car tables))))
    (puthash (downcase name) iname table)
    iname))

(defun idlwave-sintern-rinfo-list (list &optional set)
  "Sintern all strings in the rinfo LIST.  With optional parameter SET:
also set new patterns.  Probably this will always have to be t."
  (let (entry name type class kwds res source call olh new)
    (while list
      (setq entry (car list)
	    list (cdr list)
	    name (car entry)
	    type (nth 1 entry)
	    class (nth 2 entry)
	    source (nth 3 entry)
	    call (nth 4 entry)
	    kwds (nth 5 entry)
	    olh (nth 6 entry))
      (setq kwds (mapcar (lambda (x)
			   (list (idlwave-sintern-keyword (car x) set)))
			 kwds))
      (if class
	  (progn
	    (if (symbolp class) (setq class (symbol-name class)))
	    (setq class (idlwave-sintern-class class set))
	    (setq name (idlwave-sintern-method name set)))
	(setq name (idlwave-sintern-routine name set)))
      (if (stringp (cdr source))
	  (setcdr source (idlwave-sintern-file (cdr source) t)))
      (setq new (if olh
		    (list name type class source call kwds olh)
		  (list name type class source call kwds)))
      (setq res (cons new res)))
    (nreverse res)))

;; Creating new sintern tables

(defun idlwave-new-sintern-type (tag)
  "Define a variable and a function to sintern the new type TAG.
This defines the function `idlwave-sintern-TAG' and the variable
`idlwave-sint-TAGs'."
  (let* ((name (symbol-name tag))
	 (names (concat name "s"))
	 (var (intern (concat "idlwave-sint-" names)))
	 (func (intern (concat "idlwave-sintern-" name))))
    (set var nil) ; initial value of the association list
    (fset func    ; set the function
	  `(lambda (name &optional set)
	     (cond ((not (stringp name)) name)
		   ((cdr (assoc (downcase name) ,var)))
		   (set
		    (setq ,var (cons (cons (downcase name) name) ,var))
		    name)
		   (name))))))

(defun idlwave-reset-sintern-type (tag)
  "Reset the sintern variable associated with TAG."
  (set (intern (concat "idlwave-sint-" (symbol-name tag) "s")) nil))

;;---------------------------------------------------------------------------


;; The variables which hold the information
(defvar idlwave-system-routines nil
  "Holds the routine-info obtained by scanning buffers.")
(defvar idlwave-buffer-routines nil
  "Holds the routine-info obtained by scanning buffers.")
(defvar idlwave-compiled-routines nil
  "Holds the routine-info obtained by asking the shell.")
(defvar idlwave-unresolved-routines nil
  "Holds the unresolved routine-info obtained by asking the shell.")
(defvar idlwave-library-routines nil
  "Holds the procedure routine-info from the library scan.")
(defvar idlwave-path-alist nil
  "Alist with !PATH directories and a flag if the dir has been scanned.")
(defvar idlwave-true-path-alist nil
  "Like `idlwave-path-alist', but with true filenames.")
(defvar idlwave-routines nil
  "Holds the combinded procedure routine-info.")
(defvar idlwave-class-alist nil
  "Holds the class names known to IDLWAVE.")
(defvar idlwave-class-history nil
  "The history of classes selected with the minibuffer.")
(defvar idlwave-force-class-query nil)
(defvar idlwave-before-completion-wconf nil
  "The window configuration just before the completion buffer was displayed.")
(defvar idlwave-last-system-routine-info-cons-cell nil
  "The last cons cell in the system routine info.")

;;
;; The code to get routine info from different sources.

(defvar idlwave-system-routines)
(defvar idlwave-catalog-process nil
  "The background process currently updating the catalog.")

(defun idlwave-routines ()
  "Provide a list of IDL routines.
This routine loads the builtin routines on the first call.  Later it
only returns the value of the variable."
  (if (and idlwave-catalog-process
	   (processp idlwave-catalog-process))
      (progn
	(cond
	 ((equal (process-status idlwave-catalog-process) 'exit)
	  (message "updating........")
	  (setq idlwave-catalog-process nil)
	  (idlwave-update-routine-info '(4)))
	 ((equal (process-status idlwave-catalog-process) 'run)
	  ;; Keep it running...
	  )
	 (t
	  ;; Something is wrong, get rid of the process
	  (message "Problem with catalog process") (beep)
	  (condition-case nil
	      (kill-process idlwave-catalog-process)
	    (error nil))
	  (setq idlwave-catalog-process nil)))))
  (or idlwave-routines
      (progn
	(idlwave-update-routine-info)
	;; return the current value
	idlwave-routines)))

(defvar idlwave-update-rinfo-hook nil
  "List of functions which should run after a global rinfo update.
Does not run after automatic updates of buffer or the shell.")

(defun idlwave-rescan-catalog-directories ()
  "Rescan the previously selected directories. For batch processing."
  (idlwave-update-routine-info '(16)))

(defun idlwave-rescan-asynchronously ()
  "Dispatch another emacs instance to update the idlwave catalog.
After the process finishes normally, the first access to routine info
will re-read the catalog."
  (interactive)
  (if (processp idlwave-catalog-process)
      (if (eq (process-status idlwave-catalog-process) 'run)
	  (if (yes-or-no-p "A catalog-updating process is running.  Kill it? ")
	      (progn
		(condition-case nil
		    (kill-process idlwave-catalog-process)
		  (error nil))
		(error "Process killed, no new process started"))
	    (error "Quit"))
	(condition-case nil
	    (kill-process idlwave-catalog-process)
	  (error nil))))
  (if (or (not idlwave-libinfo-file)
	  (not (stringp idlwave-libinfo-file))
	  (not (file-regular-p idlwave-libinfo-file)))
      (error "No catalog has been produced yet"))
  (let* ((emacs (expand-file-name (invocation-name) (invocation-directory)))
	 (args (list "-batch"
		     "-l" (expand-file-name "~/.emacs")
		     "-l" "idlwave"
		     "-f" "idlwave-rescan-catalog-directories"))
	 (process (apply 'start-process "idlcat" 
			 nil emacs args)))
    (setq idlwave-catalog-process process)
    (set-process-sentinel 
     process
     (lambda (pro why)
       (when (string-match "finished" why)
	 (setq idlwave-routines nil
	       idlwave-system-routines nil
	       idlwave-catalog-process nil)
	 (or (idlwave-start-load-rinfo-timer)
	     (idlwave-update-routine-info '(4))))))
    (message "Background job started to update catalog file")))


(defvar idlwave-load-rinfo-idle-timer)
(defun idlwave-update-routine-info (&optional arg)
  "Update the internal routine-info lists.
These lists are used by `idlwave-routine-info' (\\[idlwave-routine-info])
and by `idlwave-complete' (\\[idlwave-complete]) to provide information
about individual routines.

The information can come from 4 sources:
1. IDL programs in the current editing session
2. Compiled modules in an IDL shell running as Emacs subprocess
3. A list which covers the IDL system routines.
4. A list which covers the prescanned library files.

Scans all IDLWAVE-mode buffers of the current editing session (see
`idlwave-scan-all-buffers-for-routine-info').
When an IDL shell is running, this command also queries the IDL program
for currently compiled routines.

With prefix ARG, also reload the system and library lists.
With two prefix ARG's, also rescans the library tree.
With three prefix args, dispatch asynchronous process to do the update."
  (interactive "P")
  ;; Stop any idle processing
  (if (or (and (fboundp 'itimerp)
	       (itimerp idlwave-load-rinfo-idle-timer))
	  (and (fboundp 'timerp)
	       (timerp idlwave-load-rinfo-idle-timer)))
      (cancel-timer idlwave-load-rinfo-idle-timer))
  (cond
   ((equal arg '(64))
    ;; Start a background process which updates the catalog.
    (idlwave-rescan-asynchronously))
   ((equal arg '(16))
    ;; Update the catalog now, and wait for it.
    (idlwave-create-libinfo-file t))
   (t
    (let* ((load (or arg
		     idlwave-buffer-case-takes-precedence
		     (null idlwave-routines)))
	   ;; The override-idle means, even if the idle timer has done some
	   ;; preparing work, load and renormalize everything anyway.
	   (override-idle (or arg idlwave-buffer-case-takes-precedence)))
      
      (setq idlwave-buffer-routines nil
	    idlwave-compiled-routines nil
	    idlwave-unresolved-routines nil)
      ;; Reset the appropriate hashes
      (if (get 'idlwave-reset-sintern 'done-by-idle)
	  ;; reset was already done in idle time, so skip this step now once
	  (put 'idlwave-reset-sintern 'done-by-idle nil)
	(idlwave-reset-sintern (cond (load t)
				     ((null idlwave-system-routines) t)
				     (t 'bufsh))))
      
      (if idlwave-buffer-case-takes-precedence
	  ;; We can safely scan the buffer stuff first
	  (progn
	    (idlwave-update-buffer-routine-info)
	    (and load (idlwave-load-system-rinfo override-idle)))
	;; We first do the system info, and then the buffers
	(and load (idlwave-load-system-rinfo override-idle))
	(idlwave-update-buffer-routine-info))

      ;; Let's see if there is a shell
      (let* ((shell-is-running (and (fboundp 'idlwave-shell-is-running)
				    (idlwave-shell-is-running)))
	     (ask-shell (and shell-is-running
			     idlwave-query-shell-for-routine-info)))
      
	(if (or (not ask-shell)
		(not (interactive-p)))
	    ;; 1. If we are not going to ask the shell, we need to do the
	    ;;    concatenation now.
	    ;; 2. When this function is called non-interactively, it means
	    ;;    that someone needs routine info *now*.  The shell update
	    ;;    causes the concatenation *delayed*, so not in time for
	    ;;    the current command.  Therefore, we do a concatenation
	    ;;    now, even though the shell might do it again.
	    (idlwave-concatenate-rinfo-lists nil t))
      
	(when ask-shell
	  ;; Ask the shell about the routines it knows.
	  (message "Querying the shell")
	  (idlwave-shell-update-routine-info nil t)))))))

(defvar idlwave-load-rinfo-steps-done (make-vector 5 nil))
(defvar idlwave-load-rinfo-idle-timer nil)
(defun idlwave-start-load-rinfo-timer ()
  (if (or (and (fboundp 'itimerp)
	       (itimerp idlwave-load-rinfo-idle-timer))
	  (and (fboundp 'timerp)
	       (timerp idlwave-load-rinfo-idle-timer)))
      (cancel-timer idlwave-load-rinfo-idle-timer))
  (setq idlwave-load-rinfo-steps-done (make-vector 5 nil))
  (setq idlwave-load-rinfo-idle-timer nil)
  (if (and idlwave-init-rinfo-when-idle-after
	   (numberp idlwave-init-rinfo-when-idle-after)
	   (not (equal 0 idlwave-init-rinfo-when-idle-after))
	   (not idlwave-routines))
      (condition-case nil
	  (progn
	    (setq idlwave-load-rinfo-idle-timer
		  (run-with-idle-timer
		   idlwave-init-rinfo-when-idle-after
		   nil 'idlwave-load-rinfo-next-step)))
	(error nil))))



(defun idlwave-load-rinfo-next-step ()
  (let ((inhibit-quit t)
	(arr idlwave-load-rinfo-steps-done))
    (if	(catch 'exit
	  (when (not (aref arr 0))
	    (message "Loading idlw-rinfo.el in idle time...")
	    (load "idlw-rinfo" 'noerror 'nomessage)
	    (message "Loading idlw-rinfo.el in idle time...done")
	    (aset arr 0 t)
	    (throw 'exit t))
	  (when (not (aref arr 1))
	    (message "Normalizing idlwave-system-routines in idle time...")
	    (idlwave-reset-sintern t)
	    (put 'idlwave-reset-sintern 'done-by-idle t)
	    (setq idlwave-system-routines
		  (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
	    (message "Normalizing idlwave-system-routines in idle time...done")
	    (aset arr 1 t)
	    (throw 'exit t))
	  (when (not (aref arr 2))
	    (when (and (stringp idlwave-libinfo-file)
		       (file-regular-p idlwave-libinfo-file))
	      (condition-case nil
		  (progn 
		    (message "Loading library catalog in idle time...")
		    (load-file idlwave-libinfo-file)
		    (message "Loading library catalog in idle time...done")
		    (aset arr 2 t)
		    (throw 'exit t))
		(error (throw 'exit nil)))))
	  (when (not (aref arr 3))
	    (when idlwave-library-routines
	      (message "Normalizing idlwave-library-routines in idle time...")
	      (setq idlwave-library-routines (idlwave-sintern-rinfo-list
					      idlwave-library-routines 'sys))
	      (message "Normalizing idlwave-library-routines in idle time...done"))
	    (aset arr 3 t)
	    (throw 'exit t))
	  (when (not (aref arr 4))
	    (message "Finishing initialization in idle time...")
	    (idlwave-routines)
	    (message "Finishing initialization in idle time...done")
	    (throw 'exit nil)))
	(progn
	  ;; restart the timer
	  (if (sit-for 1)
	      (idlwave-load-rinfo-next-step)
	    (setq idlwave-load-rinfo-idle-timer
		  (run-with-idle-timer
		   idlwave-init-rinfo-when-idle-after
		   nil 'idlwave-load-rinfo-next-step)))
	  ))))

(defun idlwave-load-system-rinfo (&optional force)
  ;; Load and case-treat the system and lib info files.
  (when (or force (not (aref idlwave-load-rinfo-steps-done 0)))
    (load "idlw-rinfo" 'noerror 'nomessage))
  (when (or force (not (aref idlwave-load-rinfo-steps-done 1)))
    (message "Normalizing idlwave-system-routines...")
    (setq idlwave-system-routines
	  (idlwave-sintern-rinfo-list idlwave-system-routines 'sys))
    (message "Normalizing idlwave-system-routines...done"))
  (setq idlwave-routines (copy-sequence idlwave-system-routines))
  (setq idlwave-last-system-routine-info-cons-cell
	(nthcdr (1- (length idlwave-routines)) idlwave-routines))
  (when (and (stringp idlwave-libinfo-file)
	     (file-regular-p idlwave-libinfo-file))
    (condition-case nil
	(progn
	  (when (or force (not (aref idlwave-load-rinfo-steps-done 2)))
	    (load-file idlwave-libinfo-file))
	  (setq idlwave-true-path-alist nil)
	  (when (or force (not (aref idlwave-load-rinfo-steps-done 3)))
	    (message "Normalizing idlwave-library-routines...")
	    (setq idlwave-library-routines (idlwave-sintern-rinfo-list
					    idlwave-library-routines 'sys))
	    (message "Normalizing idlwave-library-routines...done")))
      (error nil)))

  (run-hooks 'idlwave-after-load-rinfo-hook))


(defun idlwave-update-buffer-routine-info ()
  (let (res)
    (cond 
     ((eq idlwave-scan-all-buffers-for-routine-info t)
      ;; Scan all buffers, current buffer last
      (message "Scanning all buffers...")
      (setq res (idlwave-get-routine-info-from-buffers 
		 (reverse (buffer-list)))))
     ((null idlwave-scan-all-buffers-for-routine-info)
      ;; Don't scan any buffers
      (setq res nil))
     (t
      ;; Just scan this buffer
      (if (eq major-mode 'idlwave-mode)
	  (progn
	    (message "Scanning current buffer...")
	    (setq res (idlwave-get-routine-info-from-buffers
		       (list (current-buffer))))))))
    ;; Put the result into the correct variable
    (setq idlwave-buffer-routines 
	  (idlwave-sintern-rinfo-list res t))))

(defun idlwave-concatenate-rinfo-lists (&optional quiet run-hook)
  "Put the different sources for routine information together."
  ;; The sequence here is important because earlier definitions shadow 
  ;; later ones.  We assume that if things in the buffers are newer
  ;; then in the shell of the system, it is meant to be different.

  (setcdr idlwave-last-system-routine-info-cons-cell
	  (append idlwave-buffer-routines
		  idlwave-compiled-routines
		  idlwave-library-routines))
  (setq idlwave-class-alist nil)

  ;; Give a message with information about the number of routines we have.
  (unless quiet
    (message 
     "Routine info updated:  buffer(%d)  compiled(%d)  catalog(%d)  system(%d)"
     (length idlwave-buffer-routines)
     (length idlwave-compiled-routines)
     (length idlwave-library-routines)
     (length idlwave-system-routines)))
  (if run-hook
      (run-hooks 'idlwave-update-rinfo-hook)))

(defun idlwave-class-alist ()
  "Return the class alist - make it if necessary."
  (or idlwave-class-alist
      (let (class)
	(loop for x in idlwave-routines do
	  (when (and (setq class (nth 2 x))
		     (not (assq class idlwave-class-alist)))
	    (push (list class) idlwave-class-alist)))
	idlwave-class-alist)))      

;; Three functions for the hooks
(defun idlwave-save-buffer-update ()
  (idlwave-update-current-buffer-info 'save-buffer))
(defun idlwave-kill-buffer-update ()
  (idlwave-update-current-buffer-info 'kill-buffer))
(defun idlwave-new-buffer-update ()
  (idlwave-update-current-buffer-info 'find-file))

(defun idlwave-update-current-buffer-info (why)
  "Undate idlwave-routines for current buffer.  Can run from after-save-hook."
  (when (and (eq major-mode 'idlwave-mode)
	     (or (eq t idlwave-auto-routine-info-updates)
		 (memq why idlwave-auto-routine-info-updates))
	     idlwave-scan-all-buffers-for-routine-info
	     idlwave-routines)
    (condition-case nil
	(let (routines)
	  (idlwave-replace-buffer-routine-info
	   (buffer-file-name)
	   (if (eq why 'kill-buffer)
	       nil
	     (setq routines
		   (idlwave-sintern-rinfo-list
		    (idlwave-get-routine-info-from-buffers
		     (list (current-buffer))) 'set))))
	  (idlwave-concatenate-rinfo-lists 'quiet)
	  routines)
      (error nil))))

(defun idlwave-replace-buffer-routine-info (file new)
  "Cut the part from FILE out of `idlwave-buffer-routines' and add NEW."
  (let ((list idlwave-buffer-routines) 
	found)
    (while list
      ;; The following test uses eq to make sure it works correctly
      ;; when two buffers visit the same file.  Then the file names
      ;; will be equal, but not eq.
      (if (eq (cdr (nth 3 (car list))) file)
	  (progn
	    (setcar list nil)
	    (setq found t))
	(if found
	    ;; End of that section reached. Jump. 
	    (setq list nil)))
      (setq list (cdr list)))
    (setq idlwave-buffer-routines
	  (append new (delq nil idlwave-buffer-routines)))))

;;----- Scanning buffers -------------------

(defun idlwave-get-routine-info-from-buffers (buffers)
  "Call `idlwave-get-buffer-routine-info' on idlwave-mode buffers in BUFFERS."
  (let (buf routine-lists res)
    (save-excursion
      (while (setq buf (pop buffers))
	(set-buffer buf)
	(if (and (eq major-mode 'idlwave-mode)
		 buffer-file-name)
	    ;; yes, this buffer has the right mode.
	    (progn (setq res (condition-case nil
				 (idlwave-get-buffer-routine-info)
			       (error nil)))
		   (push res routine-lists)))))
    ;; Concatenate the individual lists and return the result
    (apply 'nconc routine-lists)))

(defun idlwave-get-buffer-routine-info ()
  "Scan the current buffer for routine info.  Return (PRO-LIST FUNC-LIST)."
  (let* ((case-fold-search t)
	 routine-list string entry)
    (save-excursion
      (save-restriction
	(widen)
	(goto-char (point-min))
	(while (re-search-forward 
		"^[ \t]*\\(pro\\|function\\)[ \t]" nil t)
	  (setq string (buffer-substring-no-properties
			(match-beginning 0)
			(progn 
			  (idlwave-end-of-statement)
			  (point))))
	  (setq entry (idlwave-parse-definition string))
	  (push entry routine-list))))
    routine-list))

(defvar idlwave-scanning-lib-dir)
(defun idlwave-parse-definition (string)
  "Parse a module definition."
  (let ((case-fold-search t)
	start name args type keywords class)
    ;; Remove comments
    (while (string-match ";.*" string)
      (setq string (replace-match "" t t string)))
    ;; Remove the continuation line stuff
    (while (string-match "\\([^a-zA-Z0-9$_]\\)\\$[ \t]*\n" string)
      (setq string (replace-match "\\1 " t nil string)))
    (while (string-match "\n" string)
      (setq string (replace-match " " t nil string)))
    ;; Match the name and type.
    (when (string-match
	   "\\<\\(pro\\|function\\)\\>\\s-+\\(\\([a-zA-Z0-9$_]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)" string)
      (setq start (match-end 0))
      (setq type (downcase (match-string 1 string)))
      (if (match-beginning 3)
	  (setq class (match-string 3 string)))
      (setq name (match-string 4 string)))
    ;; Match normal args and keyword args
    (while (string-match
	    ",\\s-*\\([a-zA-Z][a-zA-Z0-9$_]*\\|\\(_ref\\)?_extra\\)\\s-*\\(=\\)?"
	    string start)
      (setq start (match-end 0))
      (if (match-beginning 3)
	  (push (match-string 1 string) keywords)
	(push (match-string 1 string) args)))
    ;; Normalize and sort.
    (setq args (nreverse args))
    (setq keywords (sort keywords (lambda (a b) 
				    (string< (downcase a) (downcase b)))))
    ;; Make and return the entry
    ;; We don't know which argument are optional, so this information
    ;; will not be contained in the calling sequence.
    (list name
	  (if (equal type "pro") 'pro 'fun)
	  class
	  (cond ((not (boundp 'idlwave-scanning-lib))
		 (cons 'buffer (buffer-file-name)))
;		((string= (downcase 
;			   (file-name-sans-extension
;			    (file-name-nondirectory (buffer-file-name))))
;			  (downcase name))
;		 (list 'lib))
;		(t (cons 'lib (file-name-nondirectory (buffer-file-name))))
		(t (cons 'lib (concat idlwave-scanning-lib-dir
				      (file-name-nondirectory (buffer-file-name))))))
	  (concat 
	   (if (string= type "function") "Result = " "")
	   (if class "Obj ->[%s::]" "")
	   "%s"
	   (if args
	       (concat
		(if (string= type "function") "(" ", ")
		(mapconcat 'identity args ", ")
		(if (string= type "function") ")" ""))))
	  (if keywords
	      (mapcar 'list keywords)
	    nil))))

;;----- Scanning the library -------------------

(defvar idlwave-sys-dir nil
  "Internal variable.")

(defun idlwave-sys-dir ()
  "Return the syslib directory, or a dummy that never matches."
  (or idlwave-sys-dir
      "@@@@@@@@"))

(defvar idlwave-shell-path-query)
(defun idlwave-create-libinfo-file (&optional arg)
  "Scan all files on selected dirs of IDL search path for routine information.
A widget checklist will allow you to choose the directories.
Write the result as a file `idlwave-libinfo-file'.  When this file exists,
will be automatically loaded to give routine information about library
routines.
With ARG, just rescan the same directories as last time - so no widget
will pop up."
  (interactive "P")
  ;; Make sure the file is loaded if it exists.
  (if (and (stringp idlwave-libinfo-file)
	   (file-regular-p idlwave-libinfo-file))
      (condition-case nil
	  (load-file idlwave-libinfo-file)
	(error nil)))
  ;; Make sure the file name makes sense
  (unless (and (stringp idlwave-libinfo-file)
	       (> (length idlwave-libinfo-file) 0)
	       (file-accessible-directory-p
		(file-name-directory idlwave-libinfo-file))
	       (not (string= "" (file-name-nondirectory 
				 idlwave-libinfo-file))))
    (error "`idlwave-libinfo-file' does not point to file in accessible directory"))
  
  (cond
   ((and arg idlwave-path-alist
	 (consp (car idlwave-path-alist))
	 idlwave-sys-dir)
    ;; Rescan the known directories
    (idlwave-scan-lib-files
     idlwave-sys-dir
      idlwave-path-alist))
   (idlwave-library-path
    ;; Get the directories from that variable
    (idlwave-display-libinfo-widget
     idlwave-system-directory
     (idlwave-expand-path idlwave-library-path)
     (delq nil (mapcar (lambda (x) (if (consp x) (if (cdr x) (car x) nil) x))
		       idlwave-path-alist))))
   (t
    ;; Ask the shell for the path and run the widget
    (message "Asking the shell for IDL path...")
    (require 'idlw-shell)
    (idlwave-shell-send-command idlwave-shell-path-query
				'(idlwave-libinfo-command-hook nil)
				'hide))))

(defun idlwave-libinfo-command-hook (&optional arg)
  ;; Command hook used by `idlwave-create-libinfo-file'.
  (if arg
      ;; Scan immediately
      (idlwave-scan-lib-files
       idlwave-sys-dir
       idlwave-path-alist)
    ;; Display the widget
    (let* ((rpl (idlwave-shell-path-filter))
	   (sysdir (car rpl))
	   (dirs (cdr rpl)))
      (idlwave-display-libinfo-widget 
       sysdir dirs
       (delq nil (mapcar (lambda (x) (if (cdr x) (car x) nil))
			 idlwave-path-alist))))))

(defconst idlwave-libinfo-widget-help-string 
  "This is the front-end to the creation of IDLWAVE library catalog.
Please select below the directories on IDL's search path from which you
would like to extract routine information, which will be stored in the file

             %s

If this is not the correct file, first set variable `idlwave-libinfo-file'.
Then call this command again.

For writing code, you need to include the directories which contain the
routines you use.  If IDLWAVE should be able to analyse routine shadowing
it is best to scan all directories.

After selecting the directories, choose [Scan & Save] to scan the library
directories and save the routine info.
\n")

(defvar idlwave-widget)
(defvar widget-keymap)
(defun idlwave-display-libinfo-widget (sysdir dirs selected-dirs)
  "Create the widget to select IDL search path directories for scanning."
  (interactive)
  (require 'widget)
  (require 'wid-edit)
  (unless dirs
      (error "Don't know IDL's search path"))

  ;; Allow only those directories to be selected which are in the path.
  (setq selected-dirs (delq nil (mapcar (lambda (x)
					  (if (member x dirs) x nil))
					selected-dirs)))
  (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
  (switch-to-buffer (get-buffer-create "*IDLWAVE Widget*"))
  (kill-all-local-variables)
  (make-local-variable 'idlwave-widget)
  (widget-insert (format idlwave-libinfo-widget-help-string
			 idlwave-libinfo-file))
  
  (widget-create 'push-button
		 :notify 'idlwave-widget-scan-lib-files
		 "Scan & Save")
  (widget-insert "  ")
  (widget-create 'push-button
		 :notify (lambda (&rest ignore)
			   (kill-buffer (current-buffer)))
		 "Quit")
  (widget-insert "  ")
  (widget-create 'push-button
		 :notify 'idlwave-delete-libinfo-file
		 "Delete File")
  (widget-insert "  ")
  (widget-create 'push-button
		 :notify '(lambda (&rest ignore)
			    (idlwave-display-libinfo-widget
			     (widget-get idlwave-widget :sysdir)
			     (widget-get idlwave-widget :path-dirs)
			     (widget-get idlwave-widget :path-dirs)))
		 "Select All")
  (widget-insert "  ")
  (widget-create 'push-button
		 :notify '(lambda (&rest ignore)
			    (idlwave-display-libinfo-widget
			     (widget-get idlwave-widget :sysdir)
			     (widget-get idlwave-widget :path-dirs)
			     nil))
		 "Deselect All")
  (widget-insert "\n\n")

  (widget-insert "Select Directories\n")
  
  (setq idlwave-widget
	(apply 'widget-create
	       'checklist
	       :value selected-dirs
	       :greedy t
	       :tag "List of directories"
	       (mapcar (lambda (x) (list 'item x)) dirs)))
  (widget-put idlwave-widget :path-dirs dirs)
  (widget-put idlwave-widget :sysdir sysdir)
  (widget-insert "\n")
  (use-local-map widget-keymap)
  (widget-setup)
  (goto-char (point-min))
  (delete-other-windows))
  
(defun idlwave-delete-libinfo-file (&rest ignore)
  (if (yes-or-no-p
       (format "Delete file %s " idlwave-libinfo-file))
      (progn
	(delete-file idlwave-libinfo-file)
	(message "%s has been deleted" idlwave-libinfo-file))))

(defun idlwave-widget-scan-lib-files (&rest ignore)
  ;; Call `idlwave-scan-lib-files' with data taken from the widget.
  (let* ((widget idlwave-widget)
	 (selected-dirs (widget-value widget))
	 (sysdir (widget-get widget :sysdir))
	 (path-dirs (widget-get widget :path-dirs))
	 (path-dir-alist
	  (mapcar (lambda (x) (cons x (if (member x selected-dirs) t nil)))
		  path-dirs)))
    (idlwave-scan-lib-files sysdir path-dir-alist)))

(defvar font-lock-mode)
(defun idlwave-scan-lib-files (sysdir path-alist)
  ;; Scan the files in PATH-ALIST and store the info in a file
  (let* ((idlwave-scanning-lib t)
	 (idlwave-scanning-lib-dir "")
	 (dircnt (1+ (length path-alist)))
	 (idlwave-completion-case nil)
	 dirs-alist dir files file)
    (setq idlwave-library-routines nil)
    (setq idlwave-path-alist path-alist)
    (setq idlwave-true-path-alist nil)
    (setq idlwave-sys-dir sysdir)
    (save-excursion
      (set-buffer (get-buffer-create "*idlwave-scan.pro*"))
      (idlwave-mode)
      (setq dirs-alist (reverse path-alist))
      (while (setq dir (pop dirs-alist))
	(decf dircnt)
	(when (cdr dir)
	  ;; Has the flag of scanned directories
	  (setq dir (car dir))
	  (setq idlwave-scanning-lib-dir (format "{%d}/" dircnt))
	  (when (file-directory-p dir)
	    (setq files (directory-files dir 'full "\\.[pP][rR][oO]\\'"))
	    (while (setq file (pop files))
	      (when (file-regular-p file)
		(if (not (file-readable-p file))
		    (message "Skipping %s (no read permission)" file)
		  (message "Scanning %s..." file)
		  (erase-buffer)
		  (insert-file-contents file 'visit)
		  (setq idlwave-library-routines
			(append (idlwave-get-routine-info-from-buffers
				 (list (current-buffer)))
				idlwave-library-routines)))
		))))))
    ;; Sorting is not necessary since we sort each time before a routine
    ;; is used.  So we don't do it here - the catalog file looks nicer
    ;; when it is unsorted.
    ;;(message "Sorting...")
    ;;(setq idlwave-library-routines 
    ;;(sort idlwave-library-routines 'idlwave-routine-entry-compare))
    ;;(message "Sorting...done")
    (message "Creating libinfo file...")
    (kill-buffer "*idlwave-scan.pro*")
    (kill-buffer (get-buffer-create "*IDLWAVE Widget*"))
    (let ((font-lock-maximum-size 0)
	  (auto-mode-alist nil))
      (find-file idlwave-libinfo-file))
    (if (and (boundp 'font-lock-mode)
	     font-lock-mode)
	(font-lock-mode 0))
    (erase-buffer)
    (insert ";; IDLWAVE libinfo file\n")
    (insert (format ";; Created %s\n\n" (current-time-string)))

    ;; Define the variable which knows the value of "!DIR"
    (insert (format "\n(setq idlwave-sys-dir \"%s\")\n"
		    idlwave-sys-dir))

    ;; Define the variable which contains a list of all scanned directories
    (insert "\n(setq idlwave-path-alist\n    '(")
    (mapcar (lambda (x)
	      (insert (format "\n      (\"%s\" . %s)" (car x) (cdr x))))
	    path-alist)
    (insert "))\n")

    ;; Define the routine info list
    (insert "\n(setq idlwave-library-routines\n    '(")
    (let ((standard-output (current-buffer)))
      (mapcar (lambda (x)
		(insert "\n    ")
		(prin1 x)
		(goto-char (point-max)))
;		(insert (with-output-to-string (prin1 x))))
	      idlwave-library-routines))
    (insert (format "))\n\n;;; %s ends here\n"
		    (file-name-nondirectory idlwave-libinfo-file)))
    (goto-char (point-min))
    ;; Save the buffer
    (save-buffer 0)
    (kill-buffer (current-buffer)))
  (message "Creating libinfo file...done")
  (message "Info for %d routines saved in %s"
	   (length idlwave-library-routines)
	   idlwave-libinfo-file)
  (sit-for 2)
  (idlwave-update-routine-info t))

(defun idlwave-expand-path (path &optional default-dir)
  ;; Expand parts of path starting with '+' recursively into directory list.
  ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
  (message "Expanding path...")
  (let (path1 dir recursive)
    (while (setq dir (pop path))
      (if (setq recursive (string= (substring dir 0 1) "+"))
	  (setq dir (substring dir 1)))
      (if (and recursive
	       (not (file-name-absolute-p dir)))
	  (setq dir (expand-file-name dir default-dir)))
      (if recursive
	  ;; Expand recursively
	  (setq path1 (append (idlwave-recursive-directory-list dir) path1))
	;; Keep unchanged
	(push dir path1)))
    (message "Expanding path...done")
    (nreverse path1)))

(defun idlwave-recursive-directory-list (dir)
  ;; Return a list of all directories below DIR, including DIR itself
  (let ((path (list dir)) path1 file files)
    (while (setq dir (pop path))
      (when (file-directory-p dir)
	(setq files (nreverse (directory-files dir t "[^.]")))
	(while (setq file (pop files))
	  (if (file-directory-p file) 
	      (push (file-name-as-directory file) path)))
	(push dir path1)))
    path1))

;;----- Asking the shell -------------------

;; First, here is the idl program which can be used to query IDL for
;; defined routines. 
(defconst idlwave-routine-info.pro
  "
;; START OF IDLWAVE SUPPORT ROUTINES
pro idlwave_print_info_entry,name,func=func,separator=sep
  ;; See if it's an object method
  if name eq '' then return
  func    = keyword_set(func) 
  methsep = strpos(name,'::')
  meth    = methsep ne -1
  
  ;; Get routine info
  pars   = routine_info(name,/parameters,functions=func)
  source = routine_info(name,/source,functions=func)
  nargs  = pars.num_args
  nkw    = pars.num_kw_args
  if nargs gt 0 then args = pars.args
  if nkw   gt 0 then kwargs = pars.kw_args
  
  ;; Trim the class, and make the name
  if meth then begin 
      class = strmid(name,0,methsep)
      name  = strmid(name,methsep+2,strlen(name)-1)
      if nargs gt 0 then begin 
          ;; remove the self argument
          wh = where(args ne 'SELF',nargs)
          if nargs gt 0 then args = args(wh)
      endif
  endif else begin
      ;; No class, just a normal routine.
      class = \"\"
  endelse
   
  ;; Calling sequence
  cs = \"\"
  if func then cs = 'Result = '
  if meth then cs = cs + 'Obj -> [' + '%s' + '::]'
  cs = cs + '%s'
  if func then cs = cs + '(' else if nargs gt 0 then cs = cs + ', '
  if nargs gt 0 then begin
      for j=0,nargs-1 do begin
          cs = cs + args(j)
          if j lt nargs-1 then cs = cs + ', '
      endfor
  end
  if func then cs = cs + ')'
  ;; Keyword arguments
  kwstring = ''
  if nkw gt 0 then begin
      for j=0,nkw-1 do begin
          kwstring = kwstring + ' ' + kwargs(j)
      endfor
  endif
  
  ret=(['IDLWAVE-PRO','IDLWAVE-FUN'])(func)
  
  print,ret + ': ' + name + sep + class + sep + source(0).path  $
    + sep + cs + sep + kwstring
end

pro idlwave_routine_info
  sep = '<@>'
  print,'>>>BEGIN OF IDLWAVE ROUTINE INFO (\"' + sep + '\" IS THE SEPARATOR)'
  all = routine_info()
  for i=0,n_elements(all)-1 do $
    idlwave_print_info_entry,all(i),separator=sep
  all = routine_info(/functions)
  for i=0,n_elements(all)-1 do $
    idlwave_print_info_entry,all(i),/func,separator=sep
  print,'>>>END OF IDLWAVE ROUTINE INFO'
end

pro idlwave_get_sysvars
  forward_function strjoin,strtrim,strsplit
  catch,error_status
  if error_status ne 0 then begin
      print, 'Cannot get info about system variables'
  endif else begin
      help,/brief,output=s,/system_variables  ; ? unsafe use of OUTPUT=
      s = strtrim(strjoin(s,' ',/single),2)   ; make one line
      v = strsplit(s,' +',/regex,/extract)    ; get variables
      for i=0,n_elements(v)-1 do begin
          t = ['']                            ; get tag list
          a=execute('if n_tags('+v[i]+') gt 0 then t=tag_names('+v[i]+')')
          print, 'IDLWAVE-SYSVAR: '+v[i]+' '+strjoin(t,' ',/single)
      endfor
  endelse
end

pro idlwave_get_class_tags, class
  res = execute('tags=tag_names({'+class+'})')
  if res then print,'IDLWAVE-CLASS-TAGS: '+class+' '+strjoin(tags,' ',/single)
end
;; END OF IDLWAVE SUPPORT ROUTINES
" 
  "The idl programs to get info from the shell.")

(defvar idlwave-idlwave_routine_info-compiled nil
  "Remembers if the routine info procedure is already compiled.")

(defvar idlwave-shell-temp-pro-file)
(defvar idlwave-shell-temp-rinfo-save-file)
(defun idlwave-shell-update-routine-info (&optional quiet run-hooks preempt)
  "Query the shell for routine_info of compiled modules and update the lists."
  ;; Save and compile the procedure.  The compiled procedure is then
  ;; saved into an IDL SAVE file, to allow for fast RESTORE.
  ;; We need to RESTORE the procedure each time we use it, since
  ;; the user may have killed or redefined it.  In particular,
  ;; .RESET_SESSION will kill all user procedures.
  (unless (and idlwave-idlwave_routine_info-compiled
	       (file-readable-p (idlwave-shell-temp-file 'rinfo)))
    (save-excursion
      (set-buffer (idlwave-find-file-noselect
		   (idlwave-shell-temp-file 'pro)))
      (erase-buffer)
      (insert idlwave-routine-info.pro)
      (save-buffer 0))
    (idlwave-shell-send-command 
     (concat ".run " idlwave-shell-temp-pro-file)
     nil 'hide)
;    (message "SENDING SAVE") ; ????????????????????????
    (idlwave-shell-send-command
     (format "save,'idlwave_routine_info','idlwave_print_info_entry',FILE='%s',/ROUTINES" 
	     (idlwave-shell-temp-file 'rinfo))
     nil 'hide))

  ;; Restore and execute the procedure, analyze the output
;  (message "SENDING RESTORE & EXECUTE") ; ????????????????????????
  (idlwave-shell-send-command
   (format "RESTORE, '%s' & idlwave_routine_info"
	   idlwave-shell-temp-rinfo-save-file)
   `(progn
      (idlwave-shell-routine-info-filter)
      (idlwave-concatenate-rinfo-lists ,quiet ,run-hooks))
   'hide preempt))

;; ---------------------------------------------------------------------------
;;
;; Completion and displaying routine calling sequences

(defvar idlwave-completion-help-info nil)
(defvar idlwave-current-obj_new-class nil)
(defvar idlwave-complete-special nil)

(defun idlwave-complete (&optional arg module class)
  "Complete a function, procedure or keyword name at point.
This function is smart and figures out what can be legally completed
at this point.
- At the beginning of a statement it completes procedure names.
- In the middle of a statement it completes function names.
- after a `(' or `,' in the argument list of a function or procedure,
  it completes a keyword of the relevant function or procedure.
- In the first arg of `OBJ_NEW', it completes a class name.

When several completions are possible, a list will be displayed in the
*Completions* buffer.  If this list is too long to fit into the
window, scrolling can be achieved by repeatedly pressing
\\[idlwave-complete].

The function also knows about object methods.  When it needs a class
name, the action depends upon `idlwave-query-class', which see.  You
can force IDLWAVE to ask you for a class name with a
\\[universal-argument] prefix argument to this command.

See also the variables `idlwave-keyword-completion-adds-equal' and
`idlwave-function-completion-adds-paren'.

The optional ARG can be used to specify the completion type in order
to override IDLWAVE's idea of what should be completed at point.
Possible values are:

0  <=>  query for the completion type
1  <=>  'procedure
2  <=>  'procedure-keyword
3  <=>  'function
4  <=>  'function-keyword
5  <=>  'procedure-method
6  <=>  'procedure-method-keyword
7  <=>  'function-method
8  <=>  'function-method-keyword
9  <=>  'class

As a special case, the universal argument C-u forces completion of
function names in places where the default would be a keyword.

For Lisp programmers only:
When we force a keyword, optional argument MODULE can contain the module name.
When we force a method or a method keyword, CLASS can specify the class."
  (interactive "P")
  (idlwave-routines)
  (let* ((where-list
	  (if (and arg
		   (or (integerp arg)
		       (symbolp arg)))
	      (idlwave-make-force-complete-where-list arg module class)
	    (idlwave-where)))
	 (what (nth 2 where-list))
	 (idlwave-force-class-query (equal arg '(4))))

    (if (and module (string-match "::" module))
	(setq class (substring module 0 (match-beginning 0))
	      module (substring module (match-end 0))))

    (cond

     ((and (null arg)
	   (eq (car-safe last-command) 'idlwave-display-completion-list)
	   (get-buffer-window "*Completions*"))
      (setq this-command last-command)
      (idlwave-scroll-completions))

     ;; Check for any special completion functions
     ((and idlwave-complete-special
	   (idlwave-call-special idlwave-complete-special)))

     ((and (idlwave-in-quote)
	   (not (eq what 'class)))
      (idlwave-complete-filename))

     ((null what)
      (error "Nothing to complete here"))

     ((eq what 'class)
      (setq idlwave-completion-help-info '(class))
      (idlwave-complete-class))

     ((eq what 'procedure)
      ;; Complete a procedure name
      (let* ((cw-list (nth 3 where-list))
	     (class-selector (idlwave-determine-class cw-list 'pro))
	     (super-classes (unless (idlwave-explicit-class-listed cw-list)
			      (idlwave-all-class-inherits class-selector)))
	     (isa (concat "procedure" (if class-selector "-method" "")))
	     (type-selector 'pro))
	(setq idlwave-completion-help-info 
	      (list 'routine nil type-selector class-selector nil super-classes))
	(idlwave-complete-in-buffer
	 'procedure (if class-selector 'method 'routine)
	 (idlwave-routines) 'idlwave-selector
	 (format "Select a %s name%s"
		 isa
		 (if class-selector
		     (format " (class is %s)" 
			     (if (eq class-selector t) 
				 "unknown" class-selector))
		   ""))
	 isa
	 'idlwave-attach-method-classes)))

     ((eq what 'function)
      ;; Complete a function name
      (let* ((cw-list (nth 3 where-list))
	     (class-selector (idlwave-determine-class cw-list 'fun))
	     (super-classes (unless (idlwave-explicit-class-listed cw-list)
			      (idlwave-all-class-inherits class-selector)))
	     (isa (concat "function" (if class-selector "-method" "")))
	     (type-selector 'fun))
	(setq idlwave-completion-help-info 
	      (list 'routine nil type-selector class-selector nil super-classes))
	(idlwave-complete-in-buffer
	 'function (if class-selector 'method 'routine)
	 (idlwave-routines) 'idlwave-selector
	 (format "Select a %s name%s"
		 isa
		 (if class-selector
		     (format " (class is %s)" 
			     (if (eq class-selector t)
				 "unknown" class-selector))
		   ""))
	 isa
	 'idlwave-attach-method-classes)))

     ((and (memq what '(procedure-keyword function-keyword))
	   (equal arg '(4)))
      (idlwave-complete 3))

     ((eq what 'procedure-keyword)
      ;; Complete a procedure keyword
      (let* ((where (nth 3 where-list))
	     (name  (car where))
	     (method-selector name)
	     (type-selector 'pro)
	     (class (idlwave-determine-class where 'pro))
	     (class-selector class)
	     (super-classes (idlwave-all-class-inherits class-selector))
	     (isa (format "procedure%s-keyword" (if class "-method" "")))
	     (entry (idlwave-best-rinfo-assq
		     name 'pro class (idlwave-routines)))
	     (list (nth 5 entry)))
	(unless (or entry (eq class t))
	  (error "Nothing known about procedure %s"
		 (idlwave-make-full-name class name)))
	(setq list (idlwave-fix-keywords name 'pro class list))
	(unless list (error (format "No keywords available for procedure %s"
				    (idlwave-make-full-name class name))))
	(setq idlwave-completion-help-info 
	      (list 'keyword name type-selector class-selector nil super-classes))
	(idlwave-complete-in-buffer
	 'keyword 'keyword list nil
	 (format "Select keyword for procedure %s%s"
		 (idlwave-make-full-name class name)
		 (if (or (member '("_EXTRA") list)
			 (member '("_REF_EXTRA") list))			 
		     " (note _EXTRA)" ""))
	 isa
	 'idlwave-attach-keyword-classes)))

     ((eq what 'function-keyword)
      ;; Complete a function keyword
      (let* ((where (nth 3 where-list))
	     (name  (car where))
	     (method-selector name)
	     (type-selector 'fun)
	     (class (idlwave-determine-class where 'fun))
	     (class-selector class)
	     (super-classes (idlwave-all-class-inherits class-selector))
	     (isa (format "function%s-keyword" (if class "-method" "")))
	     (entry (idlwave-best-rinfo-assq
		     name 'fun class (idlwave-routines)))
	     (list (nth 5 entry))
	     msg-name)
	(unless (or entry (eq class t))
	  (error "Nothing known about function %s"
		 (idlwave-make-full-name class name)))
	(setq list (idlwave-fix-keywords name 'fun class list))
	;; OBJ_NEW: Messages mention the proper Init method
	(setq msg-name (if (and (null class)
				(string= (upcase name) "OBJ_NEW"))
			   (concat idlwave-current-obj_new-class
				   "::Init (via OBJ_NEW)")
			 (idlwave-make-full-name class name)))
	(unless list (error (format "No keywords available for function %s"
				    msg-name)))
	(setq idlwave-completion-help-info 
	      (list 'keyword name type-selector class-selector nil super-classes))
	(idlwave-complete-in-buffer
	 'keyword 'keyword list nil
	 (format "Select keyword for function %s%s" msg-name
		 (if (or (member '("_EXTRA") list)
			 (member '("_REF_EXTRA") list))			 
		     " (note _EXTRA)" ""))
	 isa
	 'idlwave-attach-keyword-classes)))

     (t (error "This should not happen (idlwave-complete)")))))

(defvar idlwave-complete-special nil
  "List of special completion functions.
These functions are called for each completion.  Each function must check
if its own special completion context is present.  If yes, it should
use `idlwave-complete-in-buffer' to do some completion and return `t'.
If such a function returns `t', *no further* attempts to complete
other contexts will be done.  If the function returns `nil', other completions
will be tried.")

(defun idlwave-call-special (functions &rest args)
  (let ((funcs functions)
	fun ret)
    (catch 'exit
      (while (setq fun (pop funcs))
	(if (setq ret (apply fun args))
	    (throw 'exit ret)))
      nil)))

(defun idlwave-make-force-complete-where-list (what &optional module class)
  ;; Return an artificial WHERE specification to force the completion
  ;; routine to complete a specific item independent of context.
  ;; WHAT is the prefix arg of `idlwave-complete', see there for details.
  ;; MODULE and CLASS can be used to specify the routine name and class.
  ;; The class name will also be found in MODULE if that is like "class::mod".
  (let* ((what-list '(("procedure") ("procedure-keyword")
		      ("function") ("function-keyword")
		      ("procedure-method") ("procedure-method-keyword")
		      ("function-method") ("function-method-keyword")
		      ("class")))
	 (module (idlwave-sintern-routine-or-method module class))
	 (class (idlwave-sintern-class class))
	 (what (cond 
		((equal what 0)
		 (setq what
		       (intern (completing-read 
				"Complete what? " what-list nil t))))
		((integerp what)
		 (setq what (intern (car (nth (1- what) what-list)))))
		((and what
		      (symbolp what)
		      (assoc (symbol-name what) what-list))
		 what)
		(t (error "Illegal WHAT"))))
	 (nil-list '(nil nil nil nil))
	 (class-list (list nil nil (or class t) nil)))

    (cond

     ((eq what 'procedure)
      (list nil-list nil-list 'procedure nil-list nil))

     ((eq what 'procedure-keyword)
      (let* ((class-selector nil)
	     (super-classes nil)
	     (type-selector 'pro)
	     (pro (or module
		      (idlwave-completing-read 
		       "Procedure: " (idlwave-routines) 'idlwave-selector))))
	(setq pro (idlwave-sintern-routine pro))
	(list nil-list nil-list 'procedure-keyword
	      (list pro nil nil nil) nil)))

     ((eq what 'function)
      (list nil-list nil-list 'function nil-list nil))

     ((eq what 'function-keyword)
      (let* ((class-selector nil)
	     (super-classes nil)
	     (type-selector 'fun)
	     (func (or module
		       (idlwave-completing-read 
			"Function: " (idlwave-routines) 'idlwave-selector))))
	(setq func (idlwave-sintern-routine func))
	(list nil-list nil-list 'function-keyword
	      (list func nil nil nil) nil)))

     ((eq what 'procedure-method)
      (list nil-list nil-list 'procedure class-list nil))

     ((eq what 'procedure-method-keyword)
      (let* ((class (idlwave-determine-class class-list 'pro))
	     (class-selector class)
	     (super-classes (idlwave-all-class-inherits class-selector))
	     (type-selector 'pro)
	     (pro (or module
		      (idlwave-completing-read
		       (format "Procedure in %s class: " class-selector)
		       (idlwave-routines) 'idlwave-selector))))
	(setq pro (idlwave-sintern-method pro))
	(list nil-list nil-list 'procedure-keyword
	      (list pro nil class nil) nil)))

     ((eq what 'function-method)
      (list nil-list nil-list 'function class-list nil))

     ((eq what 'function-method-keyword)
      (let* ((class (idlwave-determine-class class-list 'fun))
	     (class-selector class)
	     (super-classes (idlwave-all-class-inherits class-selector))
	     (type-selector 'fun)
	     (func (or module
		       (idlwave-completing-read
			(format "Function in %s class: " class-selector)
			(idlwave-routines) 'idlwave-selector))))
	(setq func (idlwave-sintern-method func))
	(list nil-list nil-list 'function-keyword
	      (list func nil class nil) nil)))

     ((eq what 'class)
      (list nil-list nil-list 'class nil-list nil))
     
     (t (error "Illegal value for WHAT")))))

(defun idlwave-completing-read (&rest args)
  ;; Completing read, case insensitive
  (let ((old-value (default-value 'completion-ignore-case)))
    (unwind-protect
	(progn
	  (setq-default completion-ignore-case t)
	  (apply 'completing-read args))
      (setq-default completion-ignore-case old-value))))

(defvar idlwave-shell-default-directory)
(defun idlwave-complete-filename ()
  "Use the comint stuff to complete a file name."
  (require 'comint)
  (let* ((comint-file-name-chars "~/A-Za-z0-9+@:_.$#%={}\\-")
	 (comint-completion-addsuffix nil)
	 (default-directory
	   (if (and (boundp 'idlwave-shell-default-directory)
		    (stringp idlwave-shell-default-directory)
		    (file-directory-p idlwave-shell-default-directory))
	       idlwave-shell-default-directory
	     default-directory)))	   
    (comint-dynamic-complete-filename)))

(defun idlwave-make-full-name (class name)
  ;; Make a fully qualified module name including the class name
  (concat (if class (format "%s::" class) "") name))

(defun idlwave-rinfo-assoc (name type class list)
  "Like `idlwave-rinfo-assq', but sintern strings first."
  (idlwave-rinfo-assq 
   (idlwave-sintern-routine-or-method name class)
   type (idlwave-sintern-class class) list))

(defun idlwave-rinfo-assq (name type class list)
  ;; Works like assq, but also checks type and class
  (catch 'exit
    (let (match)
      (while (setq match (assq name list))
	(and (or (eq type t)
		 (eq (nth 1 match) type))
	     (eq (nth 2 match) class)
	     (throw 'exit match))
	(setq list (cdr (memq match list)))))))

(defun idlwave-rinfo-assq-any-class (name type class list)
  (let* ((classes (cons class (idlwave-all-class-inherits class)))
	 class rtn)
    (while classes
      (if (setq rtn (idlwave-rinfo-assq name type (pop classes) list))
	  (setq classes nil)))
    rtn))

(defun idlwave-best-rinfo-assq (name type class list)
  "Like `idlwave-rinfo-assq', but get all twins and sort, then return first."
  (let ((twins (idlwave-routine-twins
		(idlwave-rinfo-assq-any-class name type class list)
		list))
	syslibp)
    (when (> (length twins) 1)
      (setq twins (sort twins 'idlwave-routine-entry-compare-twins))
      (if (and (eq 'system (car (nth 3 (car twins))))
	       (setq syslibp (idlwave-any-syslib (cdr twins)))
	       (not (equal 1 syslibp)))
	  ;; Its a syslib, so we need to remove the system entry
	  (setq twins (cdr twins))))
    (car twins)))

(defun idlwave-best-rinfo-assoc (name type class list)
  "Like `idlwave-best-rinfo-assq', but sintern strings first."
  (idlwave-best-rinfo-assq
   (idlwave-sintern-routine-or-method name class)
   type (idlwave-sintern-class class) list))

(defun idlwave-any-syslib (entries)
  "Does the entry list ENTRIES contain a syslib entry?
If yes, return the index (>=1)."
  (let (file (cnt 0))
    (catch 'exit
      (while entries
	(incf cnt)
	(setq file (cdr (nth 3 (car entries))))
	(if (and file
		 (idlwave-syslib-p
		  (idlwave-expand-lib-file-name file)))
	    (throw 'exit cnt)
	  (setq entries (cdr entries))))
      nil)))

(defun idlwave-all-assq (key list)
  "Return a list of all associations of Key in LIST."
  (let (rtn elt)
    (while (setq elt (assq key list))
      (push elt rtn)
      (setq list (cdr (memq elt list))))
    (nreverse rtn)))

(defun idlwave-all-method-classes (method &optional type)
  "Return all classes which have a method METHOD.  TYPE is 'fun or 'pro.
When TYPE is not specified, both procedures and functions will be considered."
  (if (null method)
      (mapcar 'car (idlwave-class-alist))
    (let (rtn)
      (mapcar (lambda (x)
		(and (nth 2 x)
		     (or (not type)
			 (eq type (nth 1 x)))
		     (push (nth 2 x) rtn)))
	      (idlwave-all-assq method (idlwave-routines)))
      (idlwave-uniquify rtn))))

(defun idlwave-all-method-keyword-classes (method keyword &optional type)
  "Return all classes which have a method METHOD with keyword KEYWORD.
TYPE is 'fun or 'pro.
When TYPE is not specified, both procedures and functions will be considered."
  (if (or (null method)
	  (null keyword))
      nil
    (let (rtn)
      (mapcar (lambda (x)
		(and (nth 2 x)
		     (or (not type)
			 (eq type (nth 1 x)))
		     (assoc keyword (nth 5 x))
		     (push (nth 2 x) rtn)))
	      (idlwave-all-assq method (idlwave-routines)))
      (idlwave-uniquify rtn))))

(defun idlwave-members-only (list club)
  "Return list of all elements in LIST which are also in CLUB."
  (let (rtn)
    (while list
      (if (member (car list) club)
	  (setq rtn (cons (car list) rtn)))
      (setq list (cdr list)))
    (nreverse rtn)))

(defun idlwave-nonmembers-only (list club)
  "Return list of all elements in LIST which are not in CLUB."
  (let (rtn)
    (while list
      (if (member (car list) club)
	  nil
	(setq rtn (cons (car list) rtn)))
      (setq list (cdr list)))
    (nreverse rtn)))

(defun idlwave-explicit-class-listed (info)
  "Return whether or not the class is listed explicitly, ala a->b::c.
INFO is as returned by idlwave-what-function or -procedure."
  (let ((apos (nth 3 info)))
    (if apos
	(save-excursion (goto-char apos)
			(looking-at "->[a-zA-Z][a-zA-Z0-9$_]*::")))))

(defvar idlwave-determine-class-special nil
  "List of special functions for determining class.
Must accept two arguments: `apos' and `info'")

(defun idlwave-determine-class (info type)
  ;; Determine the class of a routine call.  
  ;; INFO is the `cw-list' structure as returned by idlwave-where.
  ;; The second element in this structure is the class.  When nil, we
  ;; return nil.  When t, try to get the class from text properties at
  ;; the arrow.  When the object is "self", we use the class of the
  ;; current routine.  otherwise prompt the user for a class name.
  ;; Also stores the selected class as a text property at the arrow.
  ;; TYPE is 'fun or 'pro.
  (let* ((class (nth 2 info))
	 (apos (nth 3 info))
	 (nassoc (assoc (if (stringp (car info))
			    (upcase (car info))
			  (car info))
			idlwave-query-class))
	 (dassoc (assq (if (car info) 'keyword-default 'method-default)
		       idlwave-query-class))
	 (query (cond (nassoc (cdr nassoc))
		      (dassoc (cdr dassoc))
		      (t t)))
	 (arrow (and apos (string= (buffer-substring apos (+ 2 apos)) "->")))
	 (is-self 
	  (and arrow
	       (save-excursion (goto-char apos)
			       (forward-word -1)
			       (let ((case-fold-search t))
				 (looking-at "self\\>")))))
	 (force-query idlwave-force-class-query)
	 store special-class class-alist)
    (cond
     ((null class) nil)
     ((eq t class)
      ;; There is an object which would like to know its class
      (if (and arrow (get-text-property apos 'idlwave-class)
	       idlwave-store-inquired-class
	       (not force-query))
	  (setq class (get-text-property apos 'idlwave-class)
		class (idlwave-sintern-class class)))
      (if (and (eq t class) is-self)
	  (setq class (or (nth 2 (idlwave-current-routine)) class)))

      ;; Before prompting, try any special class determination routines
      (when (and (eq t class) 
		 idlwave-determine-class-special
		 (not force-query))
	(setq special-class 
	      (idlwave-call-special idlwave-determine-class-special apos))
	(if special-class 
	    (setq class (idlwave-sintern-class special-class)
		  store idlwave-store-inquired-class)))
      
      ;; Prompt for a class, if we need to
      (when (and (eq class t)
		 (or force-query query))
	(setq class-alist 
	      (mapcar 'list (idlwave-all-method-classes (car info) type)))
	(setq class
	      (idlwave-sintern-class
	       (cond
		((and (= (length class-alist) 0) (not force-query))
		 (error "No classes available with method %s" (car info)))
		((and (= (length class-alist) 1) (not force-query))
		 (car (car class-alist)))
		(t 
		 (setq store idlwave-store-inquired-class)
		 (idlwave-completing-read 
		  (format "Class%s: " (if (stringp (car info))
					  (format " for %s method %s"
						  type (car info))
					""))
		  class-alist nil nil nil 'idlwave-class-history))))))

      ;; Store it, if requested
      (when (and class (not (eq t class)))
	;; We have a real class here
	(when (and store arrow)
	  (condition-case ()
	      (add-text-properties 
	       apos (+ apos 2) 
	       `(idlwave-class ,class face ,idlwave-class-arrow-face 
			       rear-nonsticky t))
	    (error nil)))
	(setf (nth 2 info) class))
      ;; Return the class
      class)
     ;; Default as fallback
     (t class))))

(defvar type-selector)
(defvar class-selector)
(defvar method-selector)
(defvar super-classes)
(defun idlwave-selector (a)
  (and (eq (nth 1 a) type-selector)
       (or (and (nth 2 a) (eq class-selector t))
	   (eq (nth 2 a) class-selector)
	   (memq (nth 2 a) super-classes)
	   )))

(defun idlwave-where ()
  "Find out where we are. 
The return value is a list with the following stuff:
\(PRO-LIST FUNC-LIST COMPLETE-WHAT CW-LIST LAST-CHAR)

PRO-LIST       (PRO POINT CLASS ARROW)
FUNC-LIST      (FUNC POINT CLASS ARROW)
COMPLETE-WHAT  a symbol indicating what kind of completion makes sense here
CW-LIST        (PRO-OR-FUNC POINT CLASS ARROW)  Like PRO-LIST, for what can 
               be completed here.
LAST-CHAR      last relevant character before point (non-white non-comment,
               not part of current identifier or leading slash).

In the lists, we have these meanings:
PRO:    Procedure name
FUNC:   Function name
POINT:  Where is this
CLASS:  What class has the routine (nil=no, t=is method, but class unknown)
ARROW:  Location of the arrow"
  (idlwave-routines)
  (let* (;(bos (save-excursion (idlwave-beginning-of-statement) (point))) 
         (bos (save-excursion (idlwave-start-of-substatement 'pre) (point)))
 	 (func-entry (idlwave-what-function bos))
         (func (car func-entry))
         (func-class (nth 1 func-entry))
         (func-arrow (nth 2 func-entry))
	 (func-point (or (nth 3 func-entry) 0))
	 (func-level (or (nth 4 func-entry) 0))
	 (pro-entry (idlwave-what-procedure bos))
	 (pro (car pro-entry))
         (pro-class (nth 1 pro-entry))
         (pro-arrow (nth 2 pro-entry))
	 (pro-point (or (nth 3 pro-entry) 0))
	 (last-char (idlwave-last-valid-char))
         (case-fold-search t)
	 cw cw-mod cw-arrow cw-class cw-point)
    (if (< func-point pro-point) (setq func nil))
    (cond
     ((string-match "\\`[ \t]*\\(pro\\|function\\)[ \t]+[a-zA-Z0-9_]*\\'"
                    (buffer-substring bos (point)))
      (setq cw 'class))
     ((string-match 
       "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)?\\'" 
       (buffer-substring (if (> pro-point 0) pro-point bos) (point)))
      (setq cw 'procedure cw-class pro-class cw-point pro-point
	    cw-arrow pro-arrow))
     ((string-match "\\`[ \t]*\\(pro\\|function\\)\\>"
		    (buffer-substring bos (point)))
      nil)
     ((string-match "OBJ_NEW([ \t]*['\"]\\([a-zA-Z0-9$_]*\\)?\\'"
		    (buffer-substring bos (point)))
      (setq cw 'class))                    
     ((string-match "\\<inherits\\s-+\\([a-zA-Z0-9$_]*\\)?\\'"
		    (buffer-substring bos (point)))
      (setq cw 'class))                    
     ((and func 
	   (> func-point pro-point)
	   (= func-level 1)
	   (memq last-char '(?\( ?,)))
      (setq cw 'function-keyword cw-mod func cw-point func-point
	    cw-class func-class cw-arrow func-arrow))
     ((and pro (eq last-char ?,))
      (setq cw 'procedure-keyword cw-mod pro cw-point pro-point
	    cw-class pro-class cw-arrow pro-arrow))
;     ((member last-char '(?\' ?\) ?\] ?!))
;      ;; after these chars, a function makes no sense
;      ;; FIXME: I am sure there can be more in this list
;      ;; FIXME: Do we want to do this at all?
;      nil)
     ;; Everywhere else we try a function.
     (t
      (setq cw 'function)
      (save-excursion
	(if (re-search-backward "->[ \t]*\\(\\([$a-zA-Z0-9_]+\\)::\\)?[$a-zA-Z0-9_]*\\=" bos t)
	    (setq cw-arrow (copy-marker (match-beginning 0))
		  cw-class (if (match-end 2)
			       (idlwave-sintern-class (match-string 2))
			     t))))))
    (list (list pro pro-point pro-class pro-arrow)
          (list func func-point func-class func-arrow)
          cw
	  (list cw-mod cw-point cw-class cw-arrow)
	  last-char)))

(defun idlwave-this-word (&optional class)
  ;; Grab the word around point.  CLASS is for the `skip-chars=...' functions
  (setq class (or class "a-zA-Z0-9$_"))
  (save-excursion
    (buffer-substring-no-properties
     (progn (skip-chars-backward class) (point))
     (progn (skip-chars-forward  class) (point)))))

(defun idlwave-what-function (&optional bound)
  ;; Find out if point is within the argument list of a function.
  ;; The return value is ("function-name" class arrow-start (point) level).
  ;; Level is 1 on the top level parentheses, higher further down.

  ;; If the optional BOUND is an integer, bound backwards directed
  ;;    searches to this point.

  (catch 'exit
    (let (pos 
	  func-point
	  (cnt 0)
	  func arrow-start class)
      (idlwave-with-special-syntax
       (save-restriction
	 (save-excursion
	   (narrow-to-region (max 1 (or bound 0)) (point-max))
	   ;; move back out of the current parenthesis
	   (while (condition-case nil
		      (progn (up-list -1) t)
		    (error nil))
	     (setq pos (point))
	     (incf cnt)
	     (when (and (= (following-char) ?\()
			(re-search-backward 
			 "\\(::\\|\\<\\)\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\="
			 bound t))
	       (setq func (match-string 2)
		     func-point (goto-char (match-beginning 2))
		     pos func-point)
	       (if (re-search-backward 
		    "->[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\=" bound t)
		   (setq arrow-start (copy-marker (match-beginning 0))
			 class (or (match-string 2) t)))
	       (throw 
		'exit 
		(list
		 (idlwave-sintern-routine-or-method func class)
		 (idlwave-sintern-class class)
		 arrow-start func-point cnt)))
	     (goto-char pos))
	   (throw 'exit nil)))))))

(defun idlwave-what-procedure (&optional bound)
  ;; Find out if point is within the argument list of a procedure.
  ;; The return value is ("procedure-name" class arrow-pos (point)).

  ;; If the optional BOUND is an integer, bound backwards directed
  ;;    searches to this point.
  (let ((pos (point)) pro-point
	pro class arrow-start string)
    (save-excursion 
      ;;(idlwave-beginning-of-statement)
      (idlwave-start-of-substatement 'pre)
      (setq string (buffer-substring (point) pos))
      (if (string-match 
	   "\\`[ \t]*\\([a-zA-Z][a-zA-Z0-9$_]*\\)[ \t]*\\(,\\|\\'\\)" string)
	  (setq pro (match-string 1 string)
		pro-point (+ (point) (match-beginning 1)))
	(if (and (idlwave-skip-object)
		 (setq string (buffer-substring (point) pos))
		 (string-match 
		  "\\`[ \t]*\\(->\\)[ \t]*\\(\\([a-zA-Z][a-zA-Z0-9$_]*\\)::\\)?\\([a-zA-Z][a-zA-Z0-9$_]*\\)?[ \t]*\\(,\\|\\'\\)" string))
	    (setq pro (if (match-beginning 4)
			  (match-string 4 string))
		  pro-point (if (match-beginning 4)
			        (+ (point) (match-beginning 4))
			pos)
		  arrow-start (copy-marker (+ (point) (match-beginning 1)))
		  class (or (match-string 3 string) t)))))
    (list (idlwave-sintern-routine-or-method pro class)
	  (idlwave-sintern-class class)
	  arrow-start
	  pro-point)))

(defun idlwave-skip-object ()
  ;; If there is an object at point, move over it and return t.
  (let ((pos (point)))
    (if (catch 'exit
	  (save-excursion
	    (skip-chars-forward " 	")  ; white space
	    (skip-chars-forward "*")        ; de-reference
	    (cond
	     ((looking-at idlwave-identifier)
	      (goto-char (match-end 0)))
	     ((eq (following-char) ?\()
	      nil)
	     (t (throw 'exit nil)))
	    (catch 'endwhile
	      (while t
		(cond ((eq (following-char) ?.)
		       (forward-char 1)
		       (if (not (looking-at idlwave-identifier))
			   (throw 'exit nil))
		       (goto-char (match-end 0)))
		      ((memq (following-char) '(?\( ?\[))
		       (condition-case nil
			   (forward-list 1)
			 (error (throw 'exit nil))))
		      (t (throw 'endwhile t)))))
	    (if (looking-at "[ \t]*->")
		(throw 'exit (setq pos (match-beginning 0)))
	      (throw 'exit nil))))
	(goto-char pos)
      nil)))
  
(defun idlwave-last-valid-char ()
  "Return the last character before point which is not white or a comment
and also not part of the current identifier.  Since we do this in
order to identify places where keywords are, we consider the initial
`/' of a keyword as part of the identifier.
This function is not general, can only be used for completion stuff."
  (catch 'exit
    (save-excursion
      ;; skip the current identifier
      (skip-chars-backward "a-zA-Z0-9_$")
      ;; also skip a leading slash which might be belong to the keyword
      (if (eq (preceding-char) ?/)
	  (backward-char 1))
      ;; FIXME: does not check if this is a valid identifier
      (while t
	(skip-chars-backward " \t")
	(cond
	 ((memq (preceding-char) '(?\; ?\$)) (throw 'exit nil))
	 ((eq (preceding-char) ?\n)
	  (beginning-of-line 0)
	  (if (looking-at "\\([^;\n]*\\)\\$[ \t]*\\(;[^\n]*\\)?\n")
	      ;; continuation line
	      (goto-char (match-end 1))
	    (throw 'exit nil)))
	 (t (throw 'exit (preceding-char))))))))

(defvar idlwave-complete-after-success-form nil
  "A form to evaluate after successful completion.")
(defvar idlwave-complete-after-success-form-force nil
  "A form to evaluate after completion selection in *Completions* buffer.")
(defconst idlwave-completion-mark (make-marker)
  "A mark pointing to the beginning of the completion string.")

(defun idlwave-complete-in-buffer (type stype list selector prompt isa
					&optional prepare-display-function)
  "Perform TYPE completion of word before point against LIST.
SELECTOR is the PREDICATE argument for the completion function.  Show
PROMPT in echo area.  TYPE is one of 'function, 'procedure,
'class-tag, or 'keyword."
  (let* ((completion-ignore-case t)
	 beg (end (point)) slash part spart completion all-completions
	 dpart dcompletion)

    (unless list
      (error (concat prompt ": No completions available")))

    ;; What is already in the buffer?
    (save-excursion
      (skip-chars-backward "a-zA-Z0-9_$")
      (setq slash (eq (preceding-char) ?/)
	    beg (point)
	    idlwave-complete-after-success-form
	    (list 'idlwave-after-successful-completion
		  (list 'quote type) slash beg)
	    idlwave-complete-after-success-form-force
	    (list 'idlwave-after-successful-completion
		  (list 'quote type) slash (list 'quote 'force))))

    ;; Try a completion
    (setq part (buffer-substring beg end)
	  dpart (downcase part)
	  spart (idlwave-sintern stype part)
	  completion (try-completion part list selector)
	  dcompletion (if (stringp completion) (downcase completion)))
    (cond
     ((null completion)
      ;; nothing available.
      (error (concat prompt ": no completion for \"%s\"") part))
     ((and (not (equal dpart dcompletion))
	   (not (eq t completion)))
      ;; We can add something
      (delete-region beg end)
      (if (and (string= part dpart)
	       (or (not (string= part ""))
		   idlwave-complete-empty-string-as-lower-case)
	       (not idlwave-completion-force-default-case))
	  (insert dcompletion)
	(insert completion))
      (if (eq t (try-completion completion list selector))
	  ;; Now this is a unique match
	  (idlwave-after-successful-completion type slash beg))
      t)
     ((or (eq completion t)
	  (and (equal dpart dcompletion)
	       (= 1 (length (setq all-completions
				  (idlwave-uniquify
				   (all-completions part list selector)))))))
      ;; This is already complete
      (idlwave-after-successful-completion type slash beg)
      (message "%s is already the complete %s" part isa)
      nil)
     (t
      ;; We cannot add something - offer a list.
      (message "Making completion list...")
      (let* ((list all-completions)
	     ;; "complete" means, this is already a valid completion
	     (complete (memq spart all-completions))
	     (completion-highlight-first-word-only t) ; XEmacs
	     (completion-fixup-function               ; Emacs
	      (lambda () (and (eq (preceding-char) ?>)
			      (re-search-backward " <" beg t)))))
	(setq list (sort list (lambda (a b)
				(string< (downcase a) (downcase b)))))
	(if prepare-display-function
	    (setq list (funcall prepare-display-function list)))
	(if (and (string= part dpart)
		 (or (not (string= part ""))
		     idlwave-complete-empty-string-as-lower-case)
		 (not idlwave-completion-force-default-case))
	    (setq list (mapcar (lambda (x)
				 (if (listp x) 
				     (setcar x (downcase (car x)))
				   (setq x (downcase x)))
				 x)
			       list)))
	(idlwave-display-completion-list list prompt beg complete))
      t))))

(defun idlwave-complete-class ()
  "Complete a class at point."
  (interactive)
  ;; Call `idlwave-routines' to make sure the class list will be available
  (idlwave-routines)
  ;; Check for the special case of completing empty string after pro/function
  (if (let ((case-fold-search t))
	(save-excursion
	  (and
	   (re-search-backward "\\<\\(pro\\|function\\)[ \t]+\\="
			       (- (point) 15) t)
	   (goto-char (point-min))
	   (re-search-forward 
	    "^[ \t]*\\(pro\\|function\\)[ \t]+\\([a-zA-Z0-9_]+::\\)" nil t))))
      ;; Yank the full class specification
      (insert (match-string 2))
    ;; Do the completion
    (idlwave-complete-in-buffer 'class 'class (idlwave-class-alist) nil 
				"Select a class" "class")))

(defun idlwave-attach-classes (list type show-classes)
  ;; Attach the proper class list to a LIST of completion items.
  ;; TYPE, when 'kwd, shows classes for method keywords, when
  ;; 'class-tag, for class tags, and otherwise for methods.
  ;; SHOW-CLASSES is the value of `idlwave-completion-show-classes'.
  (if (or (null show-classes)           ; don't want to see classes
	  (null class-selector)         ; not a method call
	  (and 
	   (stringp class-selector) ; the class is already known
	   (not super-classes)))    ; no possibilities for inheritance
      ;; In these cases, we do not have to do anything
      list
    (let* ((do-prop (and (>= show-classes 0)
			 (>= emacs-major-version 21)))
	   (do-buf (not (= show-classes 0)))
	   ;; (do-dots (featurep 'xemacs))
	   (do-dots t)
	   (inherit (if (and (not (eq type 'class-tag)) super-classes)
			(cons class-selector super-classes)))
	   (max (abs show-classes))
	   (lmax (if do-dots (apply 'max (mapcar 'length list))))
	  classes nclasses class-info space)
      (mapcar 
       (lambda (x)
	 ;; get the classes
	 (if (eq type 'class-tag)
	     ;; Just one class for tags
	     (setq classes
		   (list 
		    (idlwave-class-or-superclass-with-tag class-selector x)))
	   ;; Multiple classes for method of method-keyword
	   (setq classes
		 (if (eq type 'kwd)
		     (idlwave-all-method-keyword-classes
		      method-selector x type-selector)
		   (idlwave-all-method-classes x type-selector)))
	   (if inherit
	       (setq classes 
		     (delq nil
			   (mapcar (lambda (x) (if (memq x inherit) x nil))
				   classes)))))
	 (setq nclasses (length classes))
	 ;; Make the separator between item and class-info
	 (if do-dots
	     (setq space (concat " " (make-string (- lmax (length x)) ?.)))
	   (setq space " "))
	 (if  do-buf
	     ;; We do want info in the buffer
	     (if (<= nclasses max)
		 (setq class-info (concat
				   space
				   "<" (mapconcat 'identity classes ",") ">"))
	       (setq class-info (format "%s<%d classes>" space nclasses)))
	   (setq class-info nil))
	 (when do-prop
	   ;; We do want properties
	   (setq x (copy-sequence x))
	   (put-text-property 0 (length x)
			      'help-echo (mapconcat 'identity classes " ")
			      x))
	 (if class-info
	     (list x class-info)
	   x))
       list))))

(defun idlwave-attach-method-classes (list)
  ;; Call idlwave-attach-classes with method parameters
  (idlwave-attach-classes list 'method idlwave-completion-show-classes))
(defun idlwave-attach-keyword-classes (list)
  ;; Call idlwave-attach-classes with keyword parameters
  (idlwave-attach-classes list 'kwd idlwave-completion-show-classes))
(defun idlwave-attach-class-tag-classes (list)
  ;; Call idlwave-attach-classes with class structure tags
  (idlwave-attach-classes list 'class-tag idlwave-completion-show-classes))
					

;;----------------------------------------------------------------------
;;----------------------------------------------------------------------
;;----------------------------------------------------------------------
;;----------------------------------------------------------------------
;;----------------------------------------------------------------------
(defvar rtn)
(defun idlwave-pset (item)
  (set 'rtn item))

(defun idlwave-popup-select (ev list title &optional sort)
  "Select an item in LIST with a popup menu.
TITLE is the title to put atop the popup.  If SORT is non-nil,
sort the list before displaying"
  (let ((maxpopup idlwave-max-popup-menu-items)
	rtn menu resp)
    (cond ((null list))
	  ((= 1 (length list))
	   (setq rtn (car list)))
	  ((featurep 'xemacs)
	   (if sort (setq list (sort list (lambda (a b) 
					    (string< (upcase a) (upcase b))))))
	   (setq menu
		 (append (list title)
			 (mapcar (lambda (x) (vector x (list 'idlwave-pset
							     x)))
				 list)))
	   (setq menu (idlwave-split-menu-xemacs menu maxpopup))
	   (setq resp (get-popup-menu-response menu))
	   (funcall (event-function resp) (event-object resp)))
	  (t
	   (if sort (setq list (sort list (lambda (a b) 
					    (string< (upcase a) (upcase b))))))
	   (setq menu (cons title
			    (list
			     (append (list "")
				     (mapcar (lambda(x) (cons x x)) list)))))
	   (setq menu (idlwave-split-menu-emacs menu maxpopup))
	   (setq rtn (x-popup-menu ev menu))))
    rtn))

(defun idlwave-split-menu-xemacs (menu N)
  "Split the MENU into submenus of maximum length N."
  (if (<= (length menu) (1+ N))
      ;; No splitting needed
      menu
    (let* ((title (car menu))
	   (entries (cdr menu))
	   (menu (list title))
	   (cnt 0)
	   (nextmenu nil))
      (while entries
	(while (and entries (< cnt N))
	  (setq cnt (1+ cnt)
		nextmenu (cons (car entries) nextmenu)
		entries (cdr entries)))
	(setq nextmenu (nreverse nextmenu))
	(setq nextmenu (cons (format "%s...%s"
				     (aref (car nextmenu) 0)
				     (aref (nth (1- cnt) nextmenu) 0))
			     nextmenu))
	(setq menu (cons nextmenu menu)
	      nextmenu nil
	      cnt 0))
      (nreverse menu))))

(defun idlwave-split-menu-emacs (menu N)
  "Split the MENU into submenus of maximum length N."
  (if (<= (length (nth 1 menu)) (1+ N))
      ;; No splitting needed
      menu
    (let* ((title (car menu))
	   (entries (cdr (nth 1 menu)))
	   (menu nil)
	   (cnt 0)
	   (nextmenu nil))
      (while entries
	(while (and entries (< cnt N))
	  (setq cnt (1+ cnt)
		nextmenu (cons (car entries) nextmenu)
		entries (cdr entries)))
	(setq nextmenu (nreverse nextmenu))
	(prin1 nextmenu)
	(setq nextmenu (cons (format "%s...%s"
				     (car (car nextmenu))
				     (car (nth (1- cnt) nextmenu)))
			     nextmenu))
	(setq menu (cons nextmenu menu)
	      nextmenu nil
	      cnt 0))
      (setq menu (nreverse menu))
      (setq menu (cons title menu))
      menu)))

(defvar idlwave-completion-setup-hook nil)

(defun idlwave-scroll-completions (&optional message)
  "Scroll the completion window on this frame."
  (let ((cwin (get-buffer-window "*Completions*" 'visible))
	(win (selected-window)))
    (unwind-protect
	(progn
	  (select-window cwin)
	  (condition-case nil
	      (scroll-up)
	    (error (if (and (listp last-command)
			    (nth 2 last-command))
		       (progn
			 (select-window win)
			 (eval idlwave-complete-after-success-form))
		     (set-window-start cwin (point-min)))))
	  (and message (message message)))
      (select-window win))))

(defun idlwave-display-completion-list (list &optional message beg complete)
  "Display the completions in LIST in the completions buffer and echo MESSAGE."
  (unless (and (get-buffer-window "*Completions*")
	       (idlwave-local-value 'idlwave-completion-p "*Completions*"))
    (move-marker idlwave-completion-mark beg)
    (setq idlwave-before-completion-wconf (current-window-configuration)))

  (if (featurep 'xemacs)
      (idlwave-display-completion-list-xemacs 
       list)
    (idlwave-display-completion-list-emacs list))

  ;; Store a special value in `this-command'.  When `idlwave-complete'
  ;; finds this in `last-command', it will scroll the *Completions* buffer.
  (setq this-command (list 'idlwave-display-completion-list message complete))

  ;; Mark the completions buffer as created by cib
  (idlwave-set-local 'idlwave-completion-p t "*Completions*")

  ;; Fontify the classes
  (if (and idlwave-completion-fontify-classes
           (consp (car list)))
      (idlwave-completion-fontify-classes))

  ;; Run the hook
  (run-hooks 'idlwave-completion-setup-hook)

  ;; Display the message
  (message (or message "Making completion list...done")))

(defun idlwave-choose (function &rest args)
  "Call FUNCTION as a completion chooser and pass ARGS to it."
  (let ((completion-ignore-case t))	    ; install correct value
    (apply function args))
  (if (and (eq major-mode 'idlwave-shell-mode)
	   (boundp 'font-lock-mode)
	   (not font-lock-mode))
      ;; Remove the fontification of the word before point
      (let ((beg (save-excursion
		   (skip-chars-backward "a-zA-Z0-9_")
		   (point))))
	(remove-text-properties beg (point) '(face nil))))
  (eval idlwave-complete-after-success-form-force))

(defun idlwave-keyboard-quit ()
  (interactive)
  (unwind-protect
      (if (eq (car-safe last-command) 'idlwave-display-completion-list)
	  (idlwave-restore-wconf-after-completion))
    (keyboard-quit)))

(defun idlwave-restore-wconf-after-completion ()
  "Restore the old (before completion) window configuration."
  (and idlwave-completion-restore-window-configuration
       idlwave-before-completion-wconf
       (set-window-configuration idlwave-before-completion-wconf)))

(defun idlwave-set-local (var value &optional buffer)
  "Set the buffer-local value of VAR in BUFFER to VALUE."
  (save-excursion
    (set-buffer (or buffer (current-buffer)))
    (set (make-local-variable var) value)))

(defun idlwave-local-value (var &optional buffer)
  "Return the value of VAR in BUFFER, but only if VAR is local to BUFFER."
  (save-excursion
    (set-buffer (or buffer (current-buffer)))
    (and (local-variable-p var (current-buffer))
	 (symbol-value var))))

;; In XEmacs, we can use :activate-callback directly to advice the
;; choose functions.  We use the private keymap only for the online
;; help feature.

(defvar idlwave-completion-map nil
  "Keymap for completion-list-mode with idlwave-complete.")

(defun idlwave-display-completion-list-xemacs (list &rest cl-args)
  (with-output-to-temp-buffer "*Completions*"
    (apply 'display-completion-list list
	   ':activate-callback 'idlwave-default-choose-completion
	   cl-args))
  (save-excursion
    (set-buffer "*Completions*")
    (use-local-map
     (or idlwave-completion-map
	 (setq idlwave-completion-map
	       (idlwave-make-modified-completion-map-xemacs
		(current-local-map)))))))

(defun idlwave-default-choose-completion (&rest args)
  "Execute `default-choose-completion' and then restore the win-conf."
  (apply 'idlwave-choose 'default-choose-completion args))

(defun idlwave-make-modified-completion-map-xemacs (old-map)
  "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
  (let ((new-map (copy-keymap old-map)))
    (define-key new-map [button3up] 'idlwave-mouse-completion-help)
    (define-key new-map [button3] (lambda ()
				    (interactive)
				    (setq this-command last-command)))
    new-map))

;; In Emacs we also replace keybindings in the completion
;; map in order to install our wrappers.

(defun idlwave-display-completion-list-emacs (list)
  "Display completion list and install the choose wrappers."
  (with-output-to-temp-buffer "*Completions*"
    (display-completion-list list))
  (save-excursion
    (set-buffer "*Completions*")
    (use-local-map
     (or idlwave-completion-map
	 (setq idlwave-completion-map
	       (idlwave-make-modified-completion-map-emacs
		(current-local-map)))))))

(defun idlwave-make-modified-completion-map-emacs (old-map)
  "Replace `choose-completion' and `mouse-choose-completion' in OLD-MAP."
  (let ((new-map (copy-keymap old-map)))
    (substitute-key-definition 
     'choose-completion 'idlwave-choose-completion new-map)
    (substitute-key-definition
     'mouse-choose-completion 'idlwave-mouse-choose-completion new-map)
    (define-key new-map [mouse-3] 'idlwave-mouse-completion-help)
    new-map))

(defun idlwave-choose-completion (&rest args)
  "Choose the completion that point is in or next to."
  (interactive)
  (apply 'idlwave-choose 'choose-completion args))

(defun idlwave-mouse-choose-completion (&rest args)
  "Click on an alternative in the `*Completions*' buffer to choose it."
  (interactive "e")
  (apply 'idlwave-choose 'mouse-choose-completion args))

;;----------------------------------------------------------------------
;;----------------------------------------------------------------------

;;; ------------------------------------------------------------------------
;;; Sturucture parsing code, and code to manage class info

;;
;; - Go again over the documentation how to write a completion
;;   plugin.  It is in self.el, but currently still very bad.
;;   This could be in a separate file in the distribution, or 
;;   in an appendix for the manual.  

(defun idlwave-struct-tags ()
  "Return a list of all tags in the structure defined at point.
Point is expected just before the opening `{' of the struct definition."
  (save-excursion
    (let* ((borders (idlwave-struct-borders))
	   (beg (car borders))
	   (end (cdr borders))
	   tags)
      (goto-char beg)
      (while (re-search-forward "[{,][ \t]*\\(\\$.*\n\\(^[ \t]*\\(\\$[ \t]*\\)?\\(;.*\\)?\n\\)*[ \t]*\\)?\\([a-zA-Z][a-zA-Z0-9_]*\\)[ \t]*:" end t)
	;; Check if we are still on the top level of the structure.
	(if (and (condition-case nil (progn (up-list -1) t) (error nil))
		 (= (point) beg))
	    (push (match-string 5) tags))
	(goto-char (match-end 0)))
      (nreverse tags))))

(defun idlwave-find-struct-tag (tag)
  "Find a given TAG in the structure defined at point."
  (let* ((borders (idlwave-struct-borders))
	 (beg (car borders))
	 (end (cdr borders))
	 (case-fold-search t))
    (re-search-forward (concat "\\(^[ \t]*\\|[,{][ \t]*\\)" tag "[ \t]*:") 
		       end t)))

(defun idlwave-struct-inherits ()
  "Return a list of all `inherits' names in the struct at point.
Point is expected just before the opening `{' of the struct definition."
  (save-excursion
    (let* ((borders (idlwave-struct-borders))
	   (beg (car borders))
	   (end (cdr borders))
	   (case-fold-search t)
	   names)
      (goto-char beg)
      (while (re-search-forward "[{,][ \t]*\\(\\$.*\n[ \t]*\\)?inherits[ \t]*\\(\\$.*\n[ \t]*\\)?\\([a-zA-Z][a-zA-Z0-9_]*\\)" end t)
	;; Check if we are still on the top level of the structure.
	(if (and (condition-case nil (progn (up-list -1) t) (error nil))
		 (= (point) beg))
	    (push (match-string 3) names))
	(goto-char (match-end 0)))
      (nreverse names))))

(defun idlwave-in-structure ()
  "Return t if point is inside an IDL structure."
  (let ((beg (point)))
    (save-excursion
      (if (not (or (idlwave-in-comment) (idlwave-in-quote)))
	  (if (idlwave-find-structure-definition nil nil 'back)
	      (let ((borders (idlwave-struct-borders)))
		(or (= (car borders) (cdr borders)) ;; struct not yet closed...
		    (and (> beg (car borders)) (< beg (cdr borders))))))))))

(defun idlwave-struct-borders ()
  "Return the borders of the {...} after point as a cons cell."
  (let (beg)
    (save-excursion
      (skip-chars-forward "^{")
      (setq beg (point))
      (condition-case nil (forward-list 1)
	(error (goto-char beg)))
      (cons beg (point)))))

(defun idlwave-find-structure-definition (&optional var name bound)
  "Search forward for a structure definition.  
If VAR is non-nil, search for a structure assigned to variable VAR.
If NAME is non-nil, search for a named structure NAME.  If BOUND is an
integer, limit the search.  If BOUND is the symbol `all', we search
first back and then forward through the entire file.  If BOUND is the
symbol `back' we search only backward."
  (let* ((ws "[ \t]*\\(\\$.*\n[ \t]*\\)*")
	 (case-fold-search t)
	 (lim (if (integerp bound) bound nil))
	 (re (concat
	      (if var
		  (concat "\\<" (regexp-quote (downcase var)) "\\>" ws)
		"\\(\\)")
	      "=" ws "\\({\\)"
	      (if name (concat ws "\\<" (downcase name) "[^a-zA-Z0-9_$]") ""))))
    (if (or (and (or (eq bound 'all) (eq bound 'back))
		 (re-search-backward re nil t))
	    (and (not (eq bound 'back)) (re-search-forward re lim t)))
	(goto-char (match-beginning 3)))))

(defvar idlwave-class-info nil)
(defvar idlwave-system-class-info nil)
(add-hook 'idlwave-update-rinfo-hook
	  (lambda () (setq idlwave-class-info nil)))
(add-hook 'idlwave-after-load-rinfo-hook
	  (lambda () (setq idlwave-class-info nil)))

(defun idlwave-class-info (class)
  (let (list entry)
    (unless idlwave-class-info
      ;; Info is nil, put in the system stuff.
      (setq idlwave-class-info idlwave-system-class-info)
      (setq list idlwave-class-info)
      (while (setq entry (pop list))
	(idlwave-sintern-class-info entry)))
    (setq class (idlwave-sintern-class class))
    (setq entry (assq class idlwave-class-info))
    (unless entry
      (setq entry (idlwave-find-class-info class))
      (when entry
	;; Sintern and cache the info
	(idlwave-sintern-class-info entry)
	(push entry idlwave-class-info)))
    entry))

(defun idlwave-sintern-class-info (entry)
  "Sintern the class names in a class-info entry."
  (let ((taglist (assq 'tags entry))
	(inherits (assq 'inherits entry)))
    (setcar entry (idlwave-sintern-class (car entry) 'set))
    (if inherits
	(setcdr inherits (mapcar (lambda (x) (idlwave-sintern-class x 'set))
				 (cdr inherits))))))

(defun idlwave-find-class-definition (class)
  (let ((case-fold-search t))
    (if (re-search-forward
	 (concat "^[ \t]*pro[ \t]+" (downcase class) "__define" "\\>") nil t)
	;; FIXME: should we limit to end of pro here?
	(idlwave-find-structure-definition nil class))))

(defun idlwave-find-class-info (class)
  "Find the __define procedure for a class structure and return info entry."
  (let* ((pro (concat (downcase class) "__define"))
	 (class (idlwave-sintern-class class))
	 (idlwave-auto-routine-info-updates nil)
	 (file (cdr (nth 3 (idlwave-rinfo-assoc pro 'pro nil 
						(idlwave-routines)))))
	 buf)
    (if (or (not file)
	    (not (file-regular-p 
		  (setq file (idlwave-expand-lib-file-name file)))))
	nil ; Cannot get info
      (save-excursion
	(if (setq buf (idlwave-get-buffer-visiting file))
	    (set-buffer buf)
	  (set-buffer (get-buffer-create " *IDLWAVE-tmp*"))
	  (erase-buffer)
	  (unless (eq major-mode 'idlwave-mode)
	    (idlwave-mode))
	  (insert-file-contents file))
	(save-excursion
	  (goto-char 1)
	  (if (idlwave-find-class-definition class)
	      (list class
		    (cons 'tags (idlwave-struct-tags))
		    (cons 'inherits (idlwave-struct-inherits)))))))))

(defun idlwave-class-tags (class)
  "Return the native tags in CLASS."
  (cdr (assq 'tags (idlwave-class-info class))))
(defun idlwave-class-inherits (class)
  "Return the direct superclasses of CLASS."
  (cdr (assq 'inherits (idlwave-class-info class))))

(defun idlwave-all-class-tags (class)
  "Return a list of native and inherited tags in CLASS."
  (condition-case err
      (apply 'append (mapcar 'idlwave-class-tags
			     (cons class (idlwave-all-class-inherits class))))
    (error           
     (idlwave-class-tag-reset)
     (error "%s" (error-message-string err)))))


(defun idlwave-all-class-inherits (class)
  "Return a list of all superclasses of CLASS (recursively expanded).
The list is cached in `idlwave-class-info' for faster access."
  (cond
   ((not idlwave-support-inheritance) nil)
   ((eq class nil) nil)
   ((eq class t) nil)
   (t
    (let ((info (idlwave-class-info class))
	  entry)
      (if (setq entry (assq 'all-inherits info))
	  (cdr entry)
	;; Save the depth of inheritance scan to check for circular references
	(let ((inherits (mapcar (lambda (x) (cons x 0))
				(idlwave-class-inherits class)))
	      rtn all-inherits cl)
	  (while inherits
	    (setq cl (pop inherits)
		  rtn (cons (car cl) rtn)
		  inherits (append (mapcar (lambda (x)
					     (cons x (1+ (cdr cl))))
					   (idlwave-class-inherits (car cl)))
				   inherits))
	    (if (> (cdr cl) 999)
	      (error
	       "Class scan: inheritance depth exceeded. Circular inheritance?")
	      ))
	  (setq all-inherits (nreverse rtn))
	  (nconc info (list (cons 'all-inherits all-inherits)))
	  all-inherits))))))


;;==========================================================================
;;
;; Completing class structure tags.  This is a completion plugin.
;; The necessary taglist is constructed dynamically

(defvar idlwave-current-tags-class nil)
(defvar idlwave-current-class-tags nil)
(defvar idlwave-current-native-class-tags nil)
(defvar idlwave-sint-class-tags nil)
(idlwave-new-sintern-type 'class-tag)
(add-to-list 'idlwave-complete-special 'idlwave-complete-class-structure-tag)
(add-hook 'idlwave-update-rinfo-hook 'idlwave-class-tag-reset)

(defun idlwave-complete-class-structure-tag ()
  "Complete a structure tag on a `self' argument in an object method."
  (interactive)
  (let ((pos (point))
	(case-fold-search t))
    (if (save-excursion
	  ;; Check if the context is right
	  (skip-chars-backward "[a-zA-Z0-9._$]")
	  (and (< (point) (- pos 4))
	       (looking-at "self\\.")))
	(let* ((class-selector (nth 2 (idlwave-current-routine)))
	       (super-classes (idlwave-all-class-inherits class-selector)))
	  ;; Check if we are in a class routine
	  (unless class-selector
	    (error "Not in a method procedure or function"))
	  ;; Check if we need to update the "current" class
	  (if (not (equal class-selector idlwave-current-tags-class))
	      (idlwave-prepare-class-tag-completion class-selector))
	  (setq idlwave-completion-help-info 
		(list 'idlwave-complete-class-structure-tag-help
		      (idlwave-sintern-routine 
		       (concat class-selector "__define"))
		      nil))
	  (let  ((idlwave-cpl-bold idlwave-current-native-class-tags))
	    (idlwave-complete-in-buffer
	     'class-tag 'class-tag 
	     idlwave-current-class-tags nil
	     (format "Select a tag of class %s" class-selector)
	     "class tag"
	     'idlwave-attach-class-tag-classes))
	  t) ; return t to skip other completions
      nil)))

(defun idlwave-class-tag-reset ()
  (setq idlwave-current-tags-class nil))

(defun idlwave-prepare-class-tag-completion (class)
  "Find and parse the necessary class definitions for class structure tags."
  (setq idlwave-sint-class-tags nil)
  (setq idlwave-current-tags-class class)
  (setq idlwave-current-class-tags
	(mapcar (lambda (x)
		  (list (idlwave-sintern-class-tag x 'set)))
		(idlwave-all-class-tags class)))
  (setq idlwave-current-native-class-tags
	(mapcar 'downcase (idlwave-class-tags class))))

;===========================================================================
;;
;; Completing system variables and their structure fields
;; This is also a plugin.  It is a bit bigger since we support loading
;; current system variables from the shell and highlighting in the
;; completions buffer. 

(defvar idlwave-sint-sysvars nil)
(defvar idlwave-sint-sysvartags nil)
(idlwave-new-sintern-type 'sysvar)
(idlwave-new-sintern-type 'sysvartag)
(add-to-list 'idlwave-complete-special 'idlwave-complete-sysvar-or-tag)
(add-hook 'idlwave-update-rinfo-hook 'idlwave-sysvars-reset)
(add-hook 'idlwave-after-load-rinfo-hook 'idlwave-remember-builtin-sysvars)
(add-hook 'idlwave-after-load-rinfo-hook 'idlwave-sintern-sysvar-alist)

(defvar idlwave-system-variables-alist nil
  "Alist of system variables and the associated structure tags.
Gets set in `idlw-rinfo.el'.")
(defvar idlwave-builtin-system-variables nil)

(defun idlwave-complete-sysvar-or-tag ()
  "Complete a system variable."
  (interactive)
  (let ((pos (point))
	(case-fold-search t))
    (cond ((save-excursion
	     ;; Check if the context is right for system variable
	     (skip-chars-backward "[a-zA-Z0-9_$]")
	     (equal (char-before) ?!))
	   (setq idlwave-completion-help-info '(idlwave-complete-sysvar-help))
	   (idlwave-complete-in-buffer 'sysvar 'sysvar 
				       idlwave-system-variables-alist nil
				       "Select a system variable"
				       "system variable")
	   t)  ; return t to skip other completions
	  ((save-excursion
	     ;; Check if the context is right for sysvar tag
	     (skip-chars-backward "[a-zA-Z0-9_$.]")
	     (and (equal (char-before) ?!)
		  (looking-at "\\([a-zA-Z][a-zA-Z0-9_$]*\\)\\.")
		  (<= (match-end 0) pos)))
	   ;; Complete a system variable tag
	   (let* ((var (idlwave-sintern-sysvar (match-string 1)))
		  (entry (assq var idlwave-system-variables-alist))
		  (tags (cdr entry)))
	     (or entry (error "!%s is not know to be a system variable" var))
	     (or tags (error "System variable !%s is not a structure" var))
	     (setq idlwave-completion-help-info
		   (list 'idlwave-complete-sysvar-help var))
	     (idlwave-complete-in-buffer 'sysvartag 'sysvartag 
					 tags nil
					 "Select a system variable tag"
					 "system variable tag")
	     t)) ; return t to skip other completions
	  (t nil))))

;; Here we fake help using the routine "system variables" with keyword
;; set to the sysvar.  Name and kwd are global variables here.
(defvar name) 
(defvar kwd)
(defun idlwave-complete-sysvar-help (mode word)
  (cond
   ((eq mode 'test)
    (or (and (eq nil (nth 1 idlwave-completion-help-info))
	     (member (downcase word) idlwave-builtin-system-variables))
	(and (stringp (nth 1 idlwave-completion-help-info))
	     (member (downcase (nth 1 idlwave-completion-help-info))
		     idlwave-builtin-system-variables))))
   ((eq mode 'set)
    (setq name "system variables"
	  kwd (concat "!"
		      (if (stringp (nth 1 idlwave-completion-help-info))
			  (nth 1 idlwave-completion-help-info)
			word))))
   (t (error "This should not happen"))))

;; Fake help in the source buffer for class structure tags.
;; kwd and name are global-variables here.
(defvar idlwave-help-do-class-struct-tag nil)
(defun idlwave-complete-class-structure-tag-help (mode word)
  (cond
   ((eq mode 'test) ; nothing gets fontified for class tags
    nil)
   ((eq mode 'set)
    (let (class-with)
      (when (setq class-with 
		(idlwave-class-or-superclass-with-tag 
		 idlwave-current-tags-class
		 word))
	(if (assq (idlwave-sintern-class class-with) 
		  idlwave-system-class-info)
	    (error "No help available for system class tags."))
	(setq name (concat class-with "__define"))))
    (setq kwd word
	  idlwave-help-do-class-struct-tag t))
   (t (error "This should not happen"))))

(defun idlwave-class-or-superclass-with-tag (class tag)
  "Find and return the CLASS or one of its superclass with the
associated TAG, if any."
  (let ((sclasses (cons class (cdr (assq 'all-inherits 
					 (idlwave-class-info class)))))
	cl)
   (catch 'exit
     (while sclasses
       (setq cl (pop sclasses))
       (let ((tags (idlwave-class-tags cl)))
	 (while tags
	   (if (eq t (compare-strings tag 0 nil (car tags) 0 nil t))
	     (throw 'exit cl))	       
	   (setq tags (cdr tags))))))))


(defun idlwave-sysvars-reset ()
  (if (and (fboundp 'idlwave-shell-is-running)
	   (idlwave-shell-is-running))
      (idlwave-shell-send-command "idlwave_get_sysvars"
				  'idlwave-process-sysvars 'hide)))

(defun idlwave-process-sysvars ()
  (idlwave-shell-filter-sysvars)
  (setq idlwave-sint-sysvars nil
	idlwave-sint-sysvartags nil)
  (idlwave-sintern-sysvar-alist))

(defun idlwave-remember-builtin-sysvars ()
  (setq idlwave-builtin-system-variables
	(mapcar 'downcase 
		(mapcar 'car idlwave-system-variables-alist))))

(defun idlwave-sintern-sysvar-alist ()
  (let ((list idlwave-system-variables-alist) entry)
    (while (setq entry (pop list))
      (setcar entry (idlwave-sintern-sysvar (car entry) 'set))
      (setcdr entry (mapcar (lambda (x) 
			      (list (idlwave-sintern-sysvartag (car x) 'set)))
			    (cdr entry))))))

(defvar idlwave-shell-command-output)
(defun idlwave-shell-filter-sysvars ()
  "Get the system variables and structure tags."
  (let ((text idlwave-shell-command-output)
	(start 0)
	(old idlwave-system-variables-alist)
	var tags type name class)
    (setq idlwave-system-variables-alist nil)
    (while (string-match "^IDLWAVE-SYSVAR: !\\([a-zA-Z0-9_$]+\\)\\( \\(.*\\)\\)?"
			 text start)
      (setq start (match-end 0)
	    var (match-string 1 text)
	    tags (if (match-end 3) (idlwave-split-string (match-string 3 text))))
      (setq idlwave-system-variables-alist
	    (cons (cons var (mapcar 'list tags))
		  idlwave-system-variables-alist)))
    ;; Keep the old value if query was not successful
    (setq idlwave-system-variables-alist
	  (or idlwave-system-variables-alist old))))

(defun idlwave-completion-fontify-classes ()
  "Goto the *Completions* buffer and fontify the class info."
  (when (featurep 'font-lock)
    (save-excursion
      (set-buffer "*Completions*")
      (save-excursion
	(goto-char (point-min))
	(let ((buffer-read-only nil))
	  (while (re-search-forward "\\.*<[^>]+>" nil t)
	    (put-text-property (match-beginning 0) (match-end 0)
			       'face 'font-lock-string-face)))))))

(defun idlwave-uniquify (list)
  (let (nlist)
    (loop for x in list do
      (add-to-list 'nlist x))
    nlist))

(defun idlwave-after-successful-completion (type slash &optional verify)
  "Add `=' or `(' after successful completion of keyword and function.
Restore the pre-completion window configuration if possible."
  (cond
   ((eq type 'procedure)
    nil)
   ((eq type 'function)
    (cond
     ((equal idlwave-function-completion-adds-paren nil) nil)
     ((or (equal idlwave-function-completion-adds-paren t)
	  (equal idlwave-function-completion-adds-paren 1))
      (insert "("))
     ((equal idlwave-function-completion-adds-paren 2)
      (insert "()")
      (backward-char 1))
     (t nil)))
   ((eq type 'keyword)
    (if (and idlwave-keyword-completion-adds-equal
	     (not slash))
	(progn (insert "=") t)
      nil)))

  ;; Restore the pre-completion window configuration if this is safe.
  
  (if (or (eq verify 'force)                                    ; force 
	  (and 
	   (get-buffer-window "*Completions*")                  ; visible
	   (idlwave-local-value 'idlwave-completion-p 
				"*Completions*")                ; cib-buffer
	   (eq (marker-buffer idlwave-completion-mark)
	       (current-buffer))                                ; buffer OK
	   (equal (marker-position idlwave-completion-mark)
		  verify)))                                     ; pos OK
      (idlwave-restore-wconf-after-completion))
  (move-marker idlwave-completion-mark nil)
  (setq idlwave-before-completion-wconf nil))

(defun idlwave-mouse-context-help (ev &optional arg)
  "Call `idlwave-context-help' on the clicked location."
  (interactive "eP")
  (mouse-set-point ev)
  (idlwave-context-help arg))

(defvar idlwave-last-context-help-pos nil)
(defun idlwave-context-help (&optional arg)
  "Display IDL Online Help on context.
If point is on a keyword, help for that keyword will be shown.  If
point is on a routine name or in the argument list of a routine, help
for that routine will be displayed.  Works for system routines and
keywords, it pulls up text help.  For other routies and keywords,
visits the source file, finding help in the header (if
`idlwave-help-source-try-header' is non-nil) or the routine definition
itself."
  (interactive "P")
  (idlwave-require-online-help)
  (idlwave-do-context-help arg))

(defun idlwave-mouse-completion-help (ev)
  "Display online help about the completion at point."
  (interactive "eP")
  (idlwave-require-online-help)
  ;; Restore last-command for next command, to make scrolling of completions
  ;; work.
  (setq this-command last-command)
  (idlwave-do-mouse-completion-help ev))

(defvar idlwave-help-is-loaded nil
  "Is online help avaiable?")
;; The following variables will be defined by `idlw-help.el'.
(defvar idlwave-help-frame-width nil)
(defvar idlwave-help-file nil)
(defvar idlwave-help-topics nil)

(defun idlwave-help-directory ()
  "Return the help directory, or nil if that is not known."
  (or (and (stringp idlwave-help-directory)
	   (> (length idlwave-help-directory) 0)
	   idlwave-help-directory)
      (getenv "IDLWAVE_HELP_DIRECTORY")))

(defun idlwave-require-online-help ()
  (if idlwave-help-is-loaded
      t  ;; everything is OK.
    (let* ((dir (or (idlwave-help-directory)
		    (error "Online Help not installed (help directory unknown) - download at idlwave.org")))
	   (lfile1 (expand-file-name "idlw-help.elc" dir))
	   (lfile2 (expand-file-name "idlw-help.el" dir))
	   (hfile (expand-file-name "idlw-help.txt" dir)))
      (if (or (and (file-regular-p lfile1) (load-file lfile1))
	      (and (file-regular-p lfile2) (load-file lfile2)))
	  (progn 
	    (if (and idlwave-help-frame-parameters
		     (not (assoc 'width idlwave-help-frame-parameters)))
		(push (cons 'width idlwave-help-frame-width)
		      idlwave-help-frame-parameters))
	    (or idlwave-help-topics
		(error "File `%s' in help dir `%s' does not define `idlwave-help-topics'" 
			 "idlw-help.el" dir)))
	(error "No such file `%s' in help dir `%s'" "idlw-help.el" dir))
      (if (file-regular-p hfile)
	  (setq idlwave-help-is-loaded t
		idlwave-help-file hfile)
	(error "No such file `%s' in dir `%s'" "idlw-help.txt" dir)))))

(defun idlwave-routine-info (&optional arg external)
  "Display a routines calling sequence and list of keywords.
When point is on the name a function or procedure, or in the argument
list of a function or procedure, this command displays a help buffer
with the information.  When called with prefix arg, enforce class
query.

When point is on an object operator `->', display the class stored in
this arrow, if any (see `idlwave-store-inquired-class').  With a
prefix arg, the class property is cleared out."

  (interactive "P")
  (idlwave-routines)
  (if (string-match "->" (buffer-substring
			  (max (point-min) (1- (point)))
			  (min (+ 2 (point)) (point-max))))
      ;; Cursor is on an arrow
      (if (get-text-property (point) 'idlwave-class)
	  ;; arrow has class property
	  (if arg
	      ;; Remove property
	      (save-excursion
		(backward-char 1)
		(when (looking-at ".?\\(->\\)")
		  (remove-text-properties (match-beginning 1) (match-end 1)
					  '(idlwave-class nil face nil))
		  (message "Class property removed from arrow")))
	    ;; Echo class property
	    (message "Arrow has text property identifying object to be class %s"
		     (get-text-property (point) 'idlwave-class)))
	;; No property found
	(message "Arrow has no class text property"))

    ;; Not on an arrow...
    (let* ((idlwave-query-class nil)
	   (idlwave-force-class-query (equal arg '(4)))
	   (module (idlwave-what-module)))
      (if (car module)
	  (apply 'idlwave-display-calling-sequence
		 (idlwave-fix-module-if-obj_new module))
	(error "Don't know which calling sequence to show")))))

(defun idlwave-resolve (&optional arg)
  "Call RESOLVE on the module name at point.
Like `idlwave-routine-info', this looks for a routine call at point.
After confirmation in the minibuffer, it will use the shell to issue
a RESOLVE call for this routine, to attempt to make it defined and its
routine info available for IDLWAVE.  If the routine is a method call,
both `class__method' and `class__define' will be tried.
With ARG, enforce query for the class of object methods."
  (interactive "P")
  (let* ((idlwave-query-class nil)
	 (idlwave-force-class-query (equal arg '(4)))
	 (module (idlwave-what-module))
	 (name (idlwave-make-full-name (nth 2 module) (car module)))
	 (type (if (eq (nth 1 module) 'pro) "pro" "function"))
	 (resolve (read-string "Resolve: " (format "%s %s" type name)))
	 (kwd "")
	 class)
    (if (string-match "\\(pro\\|function\\)[ \t]+\\(\\(.*\\)::\\)?\\(.*\\)"
		      resolve)
	(setq type (match-string 1 resolve)
	      class (if (match-beginning 2) 
			(match-string 3 resolve)
		      nil)
	      name (match-string 4 resolve)))
    (if (string= (downcase type) "function")
	(setq kwd ",/is_function"))

    (cond
     ((null class)
      (idlwave-shell-send-command 
       (format "resolve_routine,'%s'%s" (downcase name) kwd)
       'idlwave-update-routine-info
       nil t))
     (t
      (idlwave-shell-send-command 
       (format "resolve_routine,'%s__define'%s" (downcase class) kwd)
       (list 'idlwave-shell-send-command 
	     (format "resolve_routine,'%s__%s'%s" 
		     (downcase class) (downcase name) kwd)
	     '(idlwave-update-routine-info)
	     nil t))))))

(defun idlwave-find-module (&optional arg)
  "Find the source code of an IDL module.
Works for modules for which IDLWAVE has routine info available.
The function offers as default the module name `idlwave-routine-info' would
use.  With ARG force class query for object methods."
  (interactive "P")
  (let* ((idlwave-query-class nil)
	 (idlwave-force-class-query (equal arg '(4)))
	 (module (idlwave-fix-module-if-obj_new (idlwave-what-module)))
	 (default (concat (idlwave-make-full-name (nth 2 module) (car module))
			  (if (eq (nth 1 module) 'pro) "<p>" "<f>")))
	 (list 
	  (delq nil
		(mapcar (lambda (x) 
			  (if (eq 'system (car-safe (nth 3 x)))
			      ;; Take out system routines with no source.
			      nil
			    (cons
			     (concat (idlwave-make-full-name (nth 2 x) (car x))
				     (if (eq (nth 1 x) 'pro) "<p>" "<f>"))
			     (cdr x))))
			(idlwave-routines))))
	 (name (idlwave-completing-read
		(format "Module (Default %s): " 
			(if default default "none"))
		list))
	 type class)
    (if (string-match "\\`\\s-*\\'" name)
	;; Nothing, use the default.
	(setq name default))
    (if (string-match "<[fp]>" name)
	(setq type (substring name -2 -1)
	      name (substring name 0 -3)))
    (if (string-match "\\(.*\\)::\\(.*\\)" name)
	(setq class (match-string 1 name)
	      name (match-string 2 name)))
    (setq name (idlwave-sintern-routine-or-method name class)
	  class (idlwave-sintern-class class)
	  type (cond ((equal type "f") 'fun)
		     ((equal type "p") 'pro)
		     (t t)))
    (idlwave-do-find-module name type class)))

(defun idlwave-do-find-module (name type class &optional force-source)
  (let ((name1 (idlwave-make-full-name class name))
	source buf1 entry
	(buf (current-buffer))
	(pos (point))
	name2)
    (setq entry (idlwave-best-rinfo-assq name type class (idlwave-routines))
	  source (or force-source (nth 3 entry))
	  name2 (if (nth 2 entry)
		    (idlwave-make-full-name (nth 2 entry) name)
		  name1))		  
    (cond
     ((or (null name) (equal name ""))
      (error "Abort"))
     ((null entry)
      (error "Nothing known about a module %s" name2))
     ((eq (car source) 'system)
      (error "Source code for system routine %s is not available" 
	     name2))
     ((equal (cdr source) "")
      (error "Source code for routine %s is not available"
	     name2))
     ((memq (car source) '(buffer lib compiled))
      (setq buf1 
	    (if (eq (car source) 'lib)
		(idlwave-find-file-noselect
		 (idlwave-expand-lib-file-name
		  (or (cdr source)
		      (format "%s.pro" (downcase name)))) 'find)
	      (idlwave-find-file-noselect (cdr source) 'find)))
      (pop-to-buffer buf1 t)
      (goto-char (point-max))
      (let ((case-fold-search t))
	(if (re-search-backward
	     (concat "^[ \t]*\\<"
		     (cond ((equal type "f") "function")
			   ((equal type "p") "pro")
			   (t "\\(pro\\|function\\)"))
		     "\\>[ \t]+" 
		     (regexp-quote (downcase name2))
		     "[^a-zA-Z0-9_$]")
	     nil t)
	    (goto-char (match-beginning 0))
	  (pop-to-buffer buf)
	  (goto-char pos)
	  (error "Could not find routine %s" name2)))))))

(defun idlwave-what-module ()
  "Return a default module for stuff near point.
Used by `idlwave-routine-info' and `idlwave-find-module'."
  (idlwave-routines)
  (if (let ((case-fold-search t))
	(save-excursion
	  (idlwave-beginning-of-statement)
	  (looking-at "[ \t]*\\(pro\\|function\\)[ \t]+\\(\\([a-zA-Z0-9_$]+\\)::\\)?\\([a-zA-Z0-9$_]+\\)\\([, \t\n]\\|$\\)")))
      ;; This is a function or procedure definition statement
      ;; We return the defined routine as module.
      (list
       (idlwave-sintern-routine-or-method (match-string 4)
					  (match-string 2))
       (if (equal (downcase (match-string 1)) "pro") 'pro 'fun)
       (idlwave-sintern-class (match-string 3)))

    ;; Not a definition statement - analyze precise positon.
    (let* ((where (idlwave-where))
	   (cw (nth 2 where))
	   (pro (car (nth 0 where)))
	   (func (car (nth 1 where)))
	   (this-word (idlwave-this-word "a-zA-Z0-9$_"))
	   (next-char (save-excursion (skip-chars-forward "a-zA-Z0-9$_")
				      (following-char)))
	   )
      (cond
       ((and (eq cw 'procedure)
	     (not (equal this-word "")))
	(setq this-word (idlwave-sintern-routine-or-method 
			 this-word (nth 2 (nth 3 where))))
	(list this-word 'pro
	      (idlwave-determine-class 
	       (cons this-word (cdr (nth 3 where)))
	       'pro)))
       ((and (eq cw 'function) 
	     (not (equal this-word ""))
	     (or (eq next-char ?\()	; exclude arrays, vars.
		 (looking-at "[a-zA-Z0-9_]*[ \t]*(")))
	(setq this-word (idlwave-sintern-routine-or-method 
			 this-word (nth 2 (nth 3 where))))
	(list this-word 'fun
	      (idlwave-determine-class
	       (cons this-word (cdr (nth 3 where)))
	       'fun)))
       ((and (memq cw '(function-keyword procedure-keyword))
	     (not (equal this-word ""))
	     (eq next-char ?\())	; A function!
	(setq this-word (idlwave-sintern-routine this-word))
	(list this-word 'fun nil))
       (func
	(list func 'fun (idlwave-determine-class (nth 1 where) 'fun)))
       (pro
	(list pro 'pro (idlwave-determine-class (nth 0 where) 'pro)))
       (t nil)))))

(defun idlwave-what-module-find-class ()
  "Call idlwave-what-module and find the inherited class if necessary."
  (let* ((module (idlwave-what-module))
	 (class (nth 2 module))
	 classes)
    (if (and (= (length module) 3)
	     (stringp class))
	(list (car module)
	      (nth 1 module)
	      (apply 'idlwave-find-inherited-class module))
      module)))

(defun idlwave-find-inherited-class (name type class)
  "Find the class which defines TYPE NAME and is CLASS or inherited by CLASS."
  (let ((entry (idlwave-best-rinfo-assoc name type class (idlwave-routines))))
    (if entry
	(nth 2 entry)
      class)))

(defun idlwave-fix-module-if-obj_new (module)
  "Check if MODULE points to obj_new.  If yes, and if the cursor is in the
keyword region, change to the appropriate Init method."
  (let* ((name (car module))
	 (pos (point))
	 (case-fold-search t)
	 string)
    (if (and (stringp name)
	     (equal (downcase name) "obj_new")
	     (save-excursion
	       (idlwave-beginning-of-statement)
	       (setq string (buffer-substring (point) pos))
	       (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
			     string)))
	(let ((name "Init")
	      (class (match-string 1 string)))
	  (setq module (list (idlwave-sintern-method "Init")
			     'fun
			     (idlwave-sintern-class class)))))
    module))


(defun idlwave-fix-keywords (name type class keywords)
  ;; This fixes the list of keywords.
  (let ((case-fold-search t))

    ;; If this is the OBJ_NEW function, try to figure out the class and use
    ;; the keywords from the corresponding INIT method.
    (if (and (equal (upcase name) "OBJ_NEW")
	     (or (eq major-mode 'idlwave-mode)
		 (eq major-mode 'idlwave-shell-mode)))
	(let* ((bos (save-excursion (idlwave-beginning-of-statement) (point)))
	       (string (buffer-substring bos (point)))
	       (case-fold-search t)
	       class)
	  (and (string-match "obj_new([^'\"]*['\"]\\([a-zA-Z0-9_]+\\)"
			     string)
	       (setq class (idlwave-sintern-class (match-string 1 string)))
	       (setq idlwave-current-obj_new-class class)
	       (setq keywords 
		     (append keywords 
			     (nth 5 (idlwave-rinfo-assq
				     (idlwave-sintern-method "INIT")
				     'fun
				     class
				     (idlwave-routines))))))))

    ;; If the class is `t', combine all keywords of all methods NAME
    (when (eq class t)
      (loop for x in (idlwave-routines) do
	    (and (nth 2 x)                ; non-nil class
		 (eq (nth 1 x) type)      ; correct type
		 (eq (car x) name)        ; correct name
		 (mapcar (lambda (k) (add-to-list 'keywords k))
			 (nth 5 x))))
      (setq keywords (idlwave-uniquify keywords)))
    
    ;; If we have inheritance, add all keywords from superclasses, if
    ;; the user indicated that method in
    ;; `idlwave-keyword-class-inheritance'
    (when (and 
	   idlwave-keyword-class-inheritance
	   (stringp class)
	   (or (assq (idlwave-sintern-keyword "_extra") keywords)
	       (assq (idlwave-sintern-keyword "_ref_extra") keywords))
	   (boundp 'super-classes)
	   ;; Check if one of the keyword-class regexps matches the name
	   (let ((regexps idlwave-keyword-class-inheritance) re)
	     (catch 'exit
	       (while (setq re (pop regexps))
		 (if (string-match re name) (throw 'exit t))))))
      (loop for x in (idlwave-routines) do
	    (and (nth 2 x)                           ; non-nil class
		 (or (eq (nth 2 x) class)            ; the right class
		     (memq (nth 2 x) super-classes)) ; an inherited class
		 (eq (nth 1 x) type)                 ; correct type
		 (eq (car x) name)                   ; correct name
		 (mapcar (lambda (k) (add-to-list 'keywords k))
			 (nth 5 x))))
      (setq keywords (idlwave-uniquify keywords)))
    
    ;; Return the final list
    keywords))

(defun idlwave-expand-keyword (keyword module)
  "Expand KEYWORD to one of the legal keyword parameters of MODULE.
KEYWORD may be an exact match or an abbreviation of a keyword.
If the match is exact, KEYWORD itself is returned, even if there may be other
keywords of which KEYWORD is an abbreviation.  This is necessary because some
system routines have keywords which are prefixes of other keywords.
If KEYWORD is an abbreviation of several keywords, a list of all possible
completions is returned.
If the abbreviation was unique, the correct keyword is returned.
If it cannot be a keyword, the function return nil.
If we do not know about MODULE, just return KEYWORD literally."
  (let* ((name (car module))
	 (type (nth 1 module))
	 (class (nth 2 module))
	 (kwd (idlwave-sintern-keyword keyword))
	 (entry (idlwave-best-rinfo-assoc name type class (idlwave-routines)))
	 (kwd-alist (nth 5 entry))
	 (extra (or (assq (idlwave-sintern-keyword "_EXTRA") kwd-alist)
		    (assq (idlwave-sintern-keyword "_REF_EXTRA") kwd-alist)))
	 (completion-ignore-case t)
	 candidates)
    (cond ((assq kwd kwd-alist) 
	   kwd)
	  ((setq candidates (all-completions kwd kwd-alist))
	   (if (= (length candidates) 1)
	       (car candidates)
	     candidates))
	  ((and entry extra)
	   ;; Inheritance may cause this keyword to be correct 
	   keyword)
	  (entry
	   ;; We do know the function, which does not have the keyword.
	   nil)
	  (t
	   ;; We do not know the function, so this just might be a correct
	   ;; keyword - return it as it is.
	   keyword))))

(defvar idlwave-rinfo-mouse-map (make-sparse-keymap))
(defvar idlwave-rinfo-map (make-sparse-keymap))
(define-key idlwave-rinfo-mouse-map 
  (if (featurep 'xemacs) [button2] [mouse-2])
  'idlwave-mouse-active-rinfo)
(define-key idlwave-rinfo-mouse-map 
  (if (featurep 'xemacs) [(shift button2)] [(shift mouse-2)])
  'idlwave-mouse-active-rinfo-shift)
(define-key idlwave-rinfo-mouse-map 
  (if (featurep 'xemacs) [button3] [mouse-3])
  'idlwave-mouse-active-rinfo-right)
(define-key idlwave-rinfo-mouse-map " " 'idlwave-active-rinfo-space)
(define-key idlwave-rinfo-map "q" 'idlwave-quit-help)
(define-key idlwave-rinfo-mouse-map "q" 'idlwave-quit-help)
(defvar idlwave-popup-source nil)
(defvar idlwave-rinfo-marker (make-marker))

(defun idlwave-quit-help ()
  (interactive)
  (let ((ri-window (get-buffer-window "*Help*"))
	(olh-window (get-buffer-window "*IDLWAVE Help*")))
    (when (and olh-window
	       (fboundp 'idlwave-help-quit))
      (select-window olh-window)
      (idlwave-help-quit))
    (when (window-live-p ri-window)
      (delete-window ri-window))))

(defun idlwave-display-calling-sequence (name type class
					      &optional initial-class)
  ;; Display the calling sequence of module NAME, type TYPE in class CLASS.
  (let* ((initial-class (or initial-class class))
	 (entry (or (idlwave-best-rinfo-assq name type class
					     (idlwave-routines))
		    (idlwave-rinfo-assq name type class 
					idlwave-unresolved-routines)))
	 (name (or (car entry) name))
	 (class (or (nth 2 entry) class))
	 (superclasses (idlwave-all-class-inherits initial-class))
	 (twins (idlwave-routine-twins entry))
	 (dtwins (idlwave-study-twins twins))
	 (all dtwins)
	 (system (idlwave-rinfo-assq
		  name type class idlwave-system-routines))
	 (have-sysdoc (and system (idlwave-help-directory)))
	 ;; (source (nth 3 entry))
	 (have-olh (and (or system idlwave-extra-help-function)
			(idlwave-help-directory)))
	 (calling-seq (nth 4 entry))
	 (keywords (nth 5 entry))
	 (olh (nth 6 entry))
	 (help-echo-kwd
	  (if have-olh
	      "Button2: Insert KEYWORD (SHIFT=`/KEYWORD')    Button3: Online Help "
	    "Button2: Insert KEYWORD (SHIFT=`/KEYWORD')."))
	 (help-echo-use
	  (if have-olh
	      "Button2/3: Online Help"
	    nil))
	 (help-echo-src
	  (if (idlwave-help-directory)
	      "Button2: Pop to source and back.             Button3: Source in Help window."
	    "Button2: Pop to source and back."))
	 (help-echo-class
	  "Button2: Display info about same method in superclass")
	 (col 0)
	 (data (list name type class (current-buffer) olh initial-class))
	 (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
	 (face 'idlwave-help-link-face)
	 beg props win cnt total)
    (setq keywords (idlwave-fix-keywords name type class keywords))
    (cond
     ((null entry)
      (error "No %s %s known %s" type name
	     (if initial-class (concat "in class " initial-class) "")))
     ((or (null name) (equal name ""))
      (error "No function or procedure call at point"))
     ((null calling-seq)
      (error "Calling sequence of %s %s is not available" type name))
     (t
      (save-excursion
	(move-marker idlwave-rinfo-marker (point))
	(set-buffer (get-buffer-create "*Help*"))
	(use-local-map idlwave-rinfo-map)
	(setq buffer-read-only nil)
	(erase-buffer)
	(set (make-local-variable 'idlwave-popup-source) nil)
	(set (make-local-variable 'idlwave-current-obj_new-class)
				  idlwave-current-obj_new-class)
	(when superclasses
	  (setq props (list 'mouse-face 'highlight
			    km-prop idlwave-rinfo-mouse-map
			    'help-echo help-echo-class
			    'data (cons 'class data)))
	  (let ((classes (cons initial-class superclasses)) c)
	    (insert "Classes: ")
	    (while (setq c (pop classes))
	      (insert " ")
	      (setq beg (point))
	      (insert c)
	      (if (equal (downcase c) (downcase class))
		  (add-text-properties beg (point) (list 'face 'bold))
		(if (idlwave-rinfo-assq name type c (idlwave-routines))
		    (add-text-properties beg (point) props))))
	    (insert "\n")))
	(setq props (if have-olh
			(list 'mouse-face 'highlight
			      km-prop idlwave-rinfo-mouse-map
			      'help-echo help-echo-use
			      'data (cons 'usage data))))
	(if have-sysdoc (setq props (append (list 'face face) props)))
	(insert "Usage:    ")
	(setq beg (point))
	(insert (if class
		    (format calling-seq class name)
		  (format calling-seq name))
		"\n")
	(add-text-properties beg (point) props)
	
	(insert "Keywords:")
	(if (null keywords)
	    (insert " No keywords accepted.")
	  (setq col 9)
	  (mapcar
	   (lambda (x)
	     (if (>= (+ col 1 (length (car x))) 
		     (window-width))
		 (progn
		   (insert "\n         ")
		   (setq col 9)))
	     (insert " ")
	     (setq beg (point)
		   props (list 'mouse-face 'highlight
			       km-prop idlwave-rinfo-mouse-map
			       'data (cons 'keyword data)
			       'help-echo help-echo-kwd
			       'keyword (car x)))
	     (if have-sysdoc (setq props (append (list 'face face) props)))
	     (insert (car x))
	     (add-text-properties beg (point) props)
	     (setq col (+ col 1 (length (car x)))))
	   keywords))
	
	(setq cnt 1 total (length all))
	(while (setq entry (pop all))
	  (setq props (list 'mouse-face 'highlight
			    km-prop idlwave-rinfo-mouse-map
			    'help-echo help-echo-src
			    'source (cons (car (nth 2 entry)) (nth 1 entry))
			    'data (cons 'source data)))
	  (idlwave-insert-source-location
	   (format "\n%-8s  %s" 
		   (if (equal cnt 1)
		       (if (> total 1) "Sources:" "Source:")
		     "")
		   (if (> total 1) "- " ""))
	   entry props)
	  (incf cnt)
	  (when (and all (> cnt idlwave-rinfo-max-source-lines))
	    ;; No more source lines, please
	    (insert (format 
		     "\n          Source information truncated to %d entries."
		     idlwave-rinfo-max-source-lines))
	    (setq all nil)))

	(setq buffer-read-only t))
      (display-buffer "*Help*")
      (if (and (setq win (get-buffer-window "*Help*"))
	       idlwave-resize-routine-help-window)
	  (progn
	    (let ((ww (selected-window)))
	      (unwind-protect
		  (progn
		    (select-window win)
		    (enlarge-window (- (/ (frame-height) 2) 
				       (window-height)))
		    (shrink-window-if-larger-than-buffer))
		(select-window ww)))))))))

(defun idlwave-insert-source-location (prefix entry &optional file-props)
  "Insert a source location into the routine info buffer.
Start line with PREFIX.
If a file name is inserted, add FILE-PROPS to it."

  (let* ((key (car entry))
	 (file (nth 1 entry))
	 (types (nth 2 entry))
	 (shell-flag (member 'compiled types))
	 (buffer-flag (member 'buffer types))
	 (lib-flag (member 'lib types))
	 (ndupl (or (and buffer-flag (idlwave-count-eq 'buffer types))
		    (and lib-flag (idlwave-count-eq 'lib types))
		    1))
	 (doflags t)
	 beg special)

    (insert prefix)

    (cond
     ((eq key 'system)
      (setq doflags nil)
                                (insert "System    "))
     ((eq key 'builtin)
      (setq doflags nil)
                                (insert "Builtin   "))
     ((and (not file) shell-flag)
                                (insert "Unresolved"))
     ((null file)               (insert "ERROR"))
     ((setq special (idlwave-special-lib-test file))
      (insert (format "%-10s" special)))
     ((idlwave-syslib-p file)
      (if (string-match "obsolete" (file-name-directory file))
	                        (insert "Obsolete  ")
                                (insert "SystemLib ")))
     ((idlwave-lib-p file)      (insert "Library   "))
     (t                         (insert "Other     ")))

    (when doflags
      (insert (concat
	       "  ["
	       (if lib-flag "C" "-")
	       (if shell-flag "S" "-")
	       (if buffer-flag "B" "-")
	       "] ")))
    (when (> ndupl 1) 
      (setq beg (point))
      (insert (format "(%dx) " ndupl))
      (add-text-properties beg (point) (list 'face 'bold)))
    (when (and file (not (equal file "")))
      (setq beg (point))
      (insert (apply 'abbreviate-file-name
		     (if (featurep 'xemacs) (list file t) (list file))))
      (if file-props
	  (add-text-properties beg (point) file-props)))))

(defun idlwave-special-lib-test (file)
  "Check the path of FILE against the regexps which define special libs.
Return the name of the special lib if there is a match."
  (let ((alist idlwave-special-lib-alist)
	entry rtn)
    (cond
     ((stringp file)
      (while (setq entry (pop alist))
	(if (string-match (car entry) file)
	    (setq rtn (cdr entry)
		  alist nil)))
      rtn)
     (t nil))))
  
(defun idlwave-mouse-active-rinfo-right (ev)
  (interactive "e")
  (idlwave-mouse-active-rinfo ev 'right))

(defun idlwave-mouse-active-rinfo-shift (ev)
  (interactive "e")
  (idlwave-mouse-active-rinfo ev nil 'shift))

(defun idlwave-active-rinfo-space ()
  (interactive)
  (idlwave-mouse-active-rinfo nil 'right))

(defun idlwave-mouse-active-rinfo (ev &optional right shift)
  "Does the mouse actions in the routine info buffer.
Optional args RIGHT and SHIFT indicate, if mouse-3 was used, and if SHIFT
was pressed."
  (interactive "e")
  (if ev (mouse-set-point ev))
  (let (data id name type class buf keyword bufwin source word initial-class)
    (setq data (get-text-property (point) 'data)
	  source (get-text-property (point) 'source)
	  keyword (get-text-property (point) 'keyword)
	  id (car data)
	  name (nth 1 data) type (nth 2 data) class (nth 3 data)
	  buf (nth 4 data)
	  initial-class (nth 6 data)
	  word (idlwave-this-word)
	  bufwin (get-buffer-window buf t))
    (cond ((eq id 'class)
	   (if (window-live-p bufwin) (select-window bufwin))
	   (idlwave-display-calling-sequence 
	    (idlwave-sintern-method name)
	    type (idlwave-sintern-class word) 
	    initial-class))
	  ((eq id 'usage)
	   (idlwave-require-online-help)
	   (idlwave-online-help nil name type class))
	  ((eq id 'source)
	   (if (and right (idlwave-help-directory))
	       (let ((idlwave-extra-help-function 'idlwave-help-with-source)
		     (idlwave-help-source-try-header nil)
		     ;; Fake idlwave-routines, to make help find the right entry
		     (idlwave-routines
		      (list (list (nth 1 data) (nth 2 data) (nth 3 data) source ""))))
		 (idlwave-require-online-help)
		 (idlwave-help-get-special-help name type class nil))
	     (setq idlwave-popup-source (not idlwave-popup-source))
	     (if idlwave-popup-source
		 (condition-case err
		     (idlwave-do-find-module name type class source)
		   (error
		    (setq idlwave-popup-source nil)
		    (if (window-live-p bufwin) (select-window bufwin))
		    (error (nth 1 err))))
	       (if bufwin
		   (select-window bufwin)
		 (pop-to-buffer buf))
	       (goto-char (marker-position idlwave-rinfo-marker)))))
	  ((eq id 'keyword)
	   (if right
	       (progn
		 (idlwave-require-online-help)
		 (idlwave-online-help nil name type class keyword))
	     (idlwave-rinfo-insert-keyword keyword buf shift))))))

(defun idlwave-rinfo-insert-keyword (keyword buffer &optional shift)
  "Insert KEYWORD in BUFFER.  Make sure buffer is displayed in a window."
  (let ((bwin (get-buffer-window buffer)))
    (if idlwave-complete-empty-string-as-lower-case
	(setq keyword (downcase keyword)))
    (if bwin
	(select-window bwin)
      (pop-to-buffer buffer)
      (setq bwin (get-buffer-window buffer)))
    (if (eq (preceding-char) ?/)
	(insert keyword)
      (unless (save-excursion 
		(re-search-backward
		 "[(,][ \t]*\\(\\$[ \t]*\\(;.*\\)?\n\\)?[ \t]*\\=" 
		 (min (- (point) 100) (point-min)) t))
	(insert ", "))
      (if shift (insert "/"))
      (insert keyword)
      (if (and (not shift)
	       idlwave-keyword-completion-adds-equal)
	  (insert "=")))))

(defun idlwave-list-buffer-load-path-shadows (&optional arg)
  "List the load path shadows of all routines defined in current buffer."
  (interactive "P")
  (idlwave-routines)
  (if (eq major-mode 'idlwave-mode)
      (idlwave-list-load-path-shadows
       nil (idlwave-update-current-buffer-info 'save-buffer)
       "in current buffer")
    (error "Current buffer is not in idlwave-mode")))

(defun idlwave-list-shell-load-path-shadows (&optional arg)
  "List the load path shadows of all routines compiled under the shell.
This is very useful for checking an IDL application.  Just compile the
application, do RESOLVE_ALL, and `C-c C-i' to compile all referenced
routines and update IDLWAVE internal info.  Then check for shadowing
with this command."
  (interactive "P")
  (cond
   ((or (not (fboundp 'idlwave-shell-is-running))
	(not (idlwave-shell-is-running)))
    (error "Shell is not running"))
   ((null idlwave-compiled-routines)
    (error "No compiled routines.  Maybe you need to update with `C-c C-i'"))
   (t
    (idlwave-list-load-path-shadows nil idlwave-compiled-routines
				    "in the shell"))))

(defun idlwave-list-all-load-path-shadows (&optional arg)
  "List the load path shadows of all routines known to IDLWAVE."
  (interactive "P")
  (idlwave-list-load-path-shadows nil nil "globally"))

(defun idlwave-list-load-path-shadows (arg &optional special-routines loc)
  "List the routines which are defined multiple times.
Search the information IDLWAVE has about IDL routines for multiple
definitions.
When SPECIAL-ROUTINES in non-nil, only look for shadows of these routines.

When IDL hits a routine call which is not defined, it will search on
the load path in order to find a definition.  The output of this
command can be used to detect possible name clashes during this process."
  (idlwave-routines)  ; Make sure everything is loaded.
  (unless idlwave-library-routines
    (or (y-or-n-p 
	 "You don't have a library catalog.  Continue anyway? ")
	(error "Abort")))
  (let* ((routines (append idlwave-system-routines
			   idlwave-compiled-routines
			   idlwave-library-routines
			   idlwave-buffer-routines
			   nil))
	 (km-prop (if (featurep 'xemacs) 'keymap 'local-map))
	 (keymap (make-sparse-keymap))
	 (props (list 'mouse-face 'highlight
		      km-prop keymap
		      'help-echo "Mouse2: Find source"))      
	 (nroutines (length (or special-routines routines)))
	 (step (/ nroutines 99))
	 (n 0)
	 (next-perc 1)
	 (cnt 0)
	 (idlwave-sort-prefer-buffer-info nil)
	 routine twins dtwins twin done props1 lroutines)

    (if special-routines
	;; Just looking for shadows of a few special routines
	(setq lroutines routines
	      routines special-routines))

    (message "Sorting routines...")
    (setq routines (sort routines
			 (lambda (a b)
			   (string< (downcase (idlwave-make-full-name
					       (nth 2 a) (car a)))
				    (downcase (idlwave-make-full-name
					       (nth 2 b) (car b)))))))
    (message "Sorting routines...done")

    (define-key keymap (if (featurep 'xemacs) [(button2)] [(mouse-2)])
      (lambda (ev) 
	(interactive "e")
	(mouse-set-point ev)
	(apply 'idlwave-do-find-module
	       (get-text-property (point) 'find-args))))
    (define-key keymap [(return)]
      (lambda () 
	(interactive)
	(apply 'idlwave-do-find-module
	       (get-text-property (point) 'find-args))))
    (message "Compiling list...( 0%%)")
    (save-excursion
      (set-buffer (get-buffer-create "*Shadows*"))
      (setq buffer-read-only nil)
      (erase-buffer)
      (while (setq routine (pop routines))
	(setq n (1+ n))
	(if (= (* next-perc step) n)
	    (progn
	      (message "Compiling list...(%2d%%)" next-perc)
	      (setq next-perc (1+ next-perc))))
	;; Get a list of all twins
	(setq twins (idlwave-routine-twins routine (or lroutines routines)))
	(if (memq routine done)
	    (setq dtwins nil)
	  (setq dtwins (idlwave-study-twins twins)))
	;; Mark all twins as dealt with
	(setq done (append twins done))
	(when (or (> (length dtwins) 1)
		  (> (idlwave-count-eq 'lib (nth 2 (car dtwins))) 1)
		  (> (idlwave-count-eq 'buffer (nth 2 (car dtwins))) 1))
	  (incf cnt)
	  (insert (format "\n%s%s"
			  (idlwave-make-full-name (nth 2 routine) (car routine))
			  (if (eq (nth 1 routine) 'fun) "()" "")))
	  (while (setq twin (pop dtwins))
	    (setq props1 (append (list 'find-args
				       (list (nth 0 routine) 
					     (nth 1 routine) 
					     (nth 2 routine)
					     (cons 'lib (nth 1 twin))))
				 props))
	    (idlwave-insert-source-location "\n   - " twin props1))))
      (goto-char (point-min))
      (setq buffer-read-only t))
    (setq loc (or loc ""))
    (if (> cnt 0)
	(progn
	  (display-buffer (get-buffer "*Shadows*"))
	  (message "%d case%s of shadowing found %s"
		   cnt (if (= cnt 1) "" "s") loc))
      (message "No shadowing conflicts found %s" loc))))

(defun idlwave-print-source (routine)
  (let* ((source (nth 3 routine))
	 (stype (car source))
	 (sfile (cdr source)))
    (if (and (eq stype 'lib) sfile)
	(progn
	  (setq sfile (idlwave-expand-lib-file-name sfile))
	  (if (idlwave-syslib-p sfile) (setq stype 'syslib))))
    (if (and (eq stype 'compiled)
	     (or (not (stringp sfile))
		 (not (string-match "\\S-" sfile))))
	(setq stype 'unresolved))
    (princ (format "      %-10s %s\n" 
		   stype
		   (if sfile sfile "No source code available")))))

(defun idlwave-routine-twins (entry &optional list)
  "Return all twin entries of ENTRY in LIST.
LIST defaults to `idlwave-routines'.
Twin entries are those which have the same name, type, and class.
ENTRY will also be returned, as the first item of this list."
  (let* ((name (car entry))
	 (type (nth 1 entry))
	 (class (nth 2 entry))
	 (candidates (idlwave-all-assq name (or list (idlwave-routines))))
	 twins candidate)
    (while (setq candidate (pop candidates))
      (if (and (not (eq candidate entry))
	       (eq type (nth 1 candidate))
	       (eq class (nth 2 candidate)))
	  (push candidate twins)))
    (if (setq candidate (idlwave-rinfo-assq name type class 
					    idlwave-unresolved-routines))
	(push candidate twins))
    (cons entry (nreverse twins))))

(defun idlwave-study-twins (entries)
  "Return dangerous twins of first entry in TWINS.
Dangerous twins are routines with same name, but in different files
on the load path.
If a file is in the system library and has an entry in the
`idlwave-system-routines' list, we omit the latter because many IDL 
routines are implemented as library routines."
  (let* ((entry (car entries))
	 (name (car entry))      ; 
	 (type (nth 1 entry))    ; Must be bound for
	 (class (nth 2 entry))   ;  idlwave-routine-twin-compare
	 (cnt 0)
	 source type file thefile alist syslibp key)
    (while (setq entry (pop entries))
      (incf cnt)
      (setq source (nth 3 entry)
	    type (car source)
	    file (cdr source))
      (if (eq type 'lib)
	  (setq file (idlwave-expand-lib-file-name file)))
      ;; Make KEY to index entry properly
      (setq key (cond ((eq type 'system) type)
		      (file (file-truename file))
		      (t 'unresolved)))
      (if (and file 
	       (not syslibp)
	       (idlwave-syslib-p file))
	  ;; We do have an entry in the system library
	  (setq syslibp t))
      
      (setq thefile (or thefile file))
      (if (setq entry (assoc key alist))
	  (push type (nth 2 entry))
	(push (list key file (list type)) alist)))
    
    (setq alist (nreverse alist))
    
    (when syslibp
      ;; File is system *library* - remove any system entry
      (setq alist (delq (assoc 'system alist) alist)))
    
    (when (and (idlwave-syslib-scanned-p)
	       (setq entry (assoc 'system alist)))
      (setcar entry 'builtin))
    (sort alist 'idlwave-routine-twin-compare)))

(defvar name)
(defvar type)
(defvar class)
(defvar idlwave-sort-prefer-buffer-info t
  "Internal variable used to influence `idlwave-routine-twin-compare'.")

(defmacro idlwave-xor (a b)
  `(and (or ,a ,b)
	(not (and ,a ,b))))

(defun idlwave-routine-entry-compare (a b)
  "Compare two routine info entries for sortiung.  This is the general case.
It first compates class, names, and type.  If it turns out that A and B
are twins (same name, class, and type), calls another routine which
compares twins on the basis of their file names and path locations."
  (let ((name (car a)) (type (nth 1 a)) (class (nth 2 a)))
    (cond
     ((not (equal (idlwave-downcase-safe class)
		  (idlwave-downcase-safe (nth 2 b))))
      ;; Class decides
      (cond ((null (nth 2 b)) nil)
	    ((null class) t)
	    (t (string< (downcase class) (downcase (nth 2 b))))))
     ((not (equal (downcase name) (downcase (car b))))
      ;; Name decides
      (string< (downcase name) (downcase (car b))))
     ((not (eq type (nth 1 b)))
      ;; Type decides
      (< (if (eq type 'fun) 1 0) (if (eq (nth 1 b) 'fun) 1 0)))
     (t	
      ;; A and B are twins - so the decision is more complicated.
      ;; Call twin-compare with the proper arguments.
      (idlwave-routine-entry-compare-twins a b)))))

(defun idlwave-routine-entry-compare-twins (a b)
  "Compare two routine entries, under the assumption that they are twins.
This basically calles `idlwave-routine-twin-compare' with the correct args."
  (let ((name (car a)) (type (nth 1 a)) (class (nth 2 a)) ; needed outside
	(atype (car (nth 3 a)))
	(btype (car (nth 3 b)))
	(afile (cdr (nth 3 a)))
	(bfile (cdr (nth 3 b))))
    (if (eq atype 'lib)
	(setq afile (idlwave-expand-lib-file-name afile)))
    (if (eq btype 'lib)
	(setq bfile (idlwave-expand-lib-file-name bfile)))
    (idlwave-routine-twin-compare
     (if (stringp afile)
	 (list (file-truename afile) afile (list atype))
       (list atype afile (list atype)))
     (if (stringp bfile)
	 (list (file-truename bfile) bfile (list btype))
       (list btype bfile (list btype))))
    ))

(defun idlwave-routine-twin-compare (a b)
  "Compare two routine twin entries for sorting.
In here, A and B are not normal routine info entries, but special
lists (KEY FILENAME (TYPES...)).
This expects NAME TYPE CLASS to be bound to the right values."
  (let* (;; Dis-assemble entries
	 (akey (car a))	     (bkey (car b))
	 (afile (nth 1 a))   (bfile (nth 1 b))
	 (atypes (nth 2 a))  (btypes (nth 2 b))
	 ;; System routines?
	 (asysp (memq akey '(builtin system)))
	 (bsysp (memq bkey '(builtin system)))
	 ;; Compiled routines?
	 (acompp (memq 'compiled atypes))
	 (bcompp (memq 'compiled btypes))
	 ;; Unresolved?
	 (aunresp (or (eq akey 'unresolved)
		      (and acompp (not afile))))
	 (bunresp (or (eq bkey 'unresolved)
		      (and bcompp (not bfile))))
	 ;; Buffer info available?
	 (abufp (memq 'buffer atypes))
	 (bbufp (memq 'buffer btypes))
	 ;; On search path?
	 (tpath-alist (idlwave-true-path-alist))
	 (apathp (assoc akey tpath-alist))
	 (bpathp (assoc bkey tpath-alist))
	 ;; How early on search path?  High number means early since we
	 ;; measure the tail of the path list
	 (anpath (length (memq apathp tpath-alist)))
	 (bnpath (length (memq bpathp tpath-alist)))
	 ;; Look at file names
	 (aname (if (stringp afile) (downcase (file-name-nondirectory afile)) ""))
	 (bname (if (stringp bfile) (downcase (file-name-nondirectory bfile)) ""))
	 (fname-re (if class (format "\\`%s__\\(%s\\|define\\)\\.pro\\'"
				     (regexp-quote (downcase class))
				     (regexp-quote (downcase name)))
		     (format "\\`%s\\.pro" (regexp-quote (downcase name)))))
	 ;; Is file name derived from the routine name?
	 ;; Method file or class definition file?
	 (anamep (string-match fname-re aname))
	 (adefp (and class anamep (string= "define" (match-string 1 aname))))
	 (bnamep (string-match fname-re bname))
	 (bdefp (and class bnamep (string= "define" (match-string 1 bname)))))

    ;; Now: follow JD's ideas about sorting.  Looks really simple now,
    ;; doesn't it?  The difficult stuff is hidden above...
    (cond
     ((idlwave-xor asysp  bsysp)       asysp)	; System entries first
     ((idlwave-xor aunresp bunresp)    bunresp) ; Unresolved last
     ((and idlwave-sort-prefer-buffer-info
	   (idlwave-xor abufp bbufp))  abufp)	; Buffers before non-buffers
     ((idlwave-xor acompp bcompp)      acompp)	; Compiled entries
     ((idlwave-xor apathp bpathp)      apathp)	; Library before non-library
     ((idlwave-xor anamep bnamep)      anamep)	; Correct file names first
     ((and class anamep bnamep                  ; both file names match ->
	   (idlwave-xor adefp bdefp))  bdefp)	; __define after __method
     ((> anpath bnpath)                t)	; Who is first on path?
     (t                                nil))))	; Default

(defun idlwave-downcase-safe (string)
  "Donwcase if string, else return unchanged."
  (if (stringp string)
      (downcase string)
    string))

(defun idlwave-count-eq (elt list)
  "How often is ELT in LIST?"
  (length (delq nil (mapcar (lambda (x) (eq x elt)) list))))

(defun idlwave-syslib-p (file)
  "Non-nil of FILE is in the system library."
  (let* ((true-syslib (file-name-as-directory
		       (file-truename
			(expand-file-name "lib" (idlwave-sys-dir)))))
	 (true-file (file-truename file)))
    (string-match (concat "^" (regexp-quote true-syslib)) true-file)))

(defun idlwave-lib-p (file)
  "Non-nil if file is in the library"
  (let ((true-dir (file-name-directory (file-truename file))))
    (assoc true-dir (idlwave-true-path-alist))))

(defun idlwave-true-path-alist ()
  "Return `idlwave-path-alist' alist with true-names.
Info is cached, but relies on the functons setting `idlwave-path-alist'
to reset the variable `idlwave-true-path-alist' to nil."
  (or idlwave-true-path-alist
      (setq idlwave-true-path-alist
	    (mapcar (lambda(x) (cons
				(file-name-as-directory
				 (file-truename
				  (directory-file-name
				   (car x))))
				(cdr x)))
		    idlwave-path-alist))))

(defun idlwave-syslib-scanned-p ()
  "Non-nil if the system lib file !DIR/lib has been scanned."
  (let* ((true-syslib (file-name-as-directory
		       (file-truename
			(expand-file-name "lib" (idlwave-sys-dir))))))
    (cdr (assoc true-syslib (idlwave-true-path-alist)))))

;; ----------------------------------------------------------------------------
;;
;; Online Help display


;; ----------------------------------------------------------------------------
;;
;; Additions for use with imenu.el and func-menu.el
;; (pop-up a list of IDL units in the current file).
;;

(defun idlwave-prev-index-position ()
  "Search for the previous procedure or function.
Return nil if not found.  For use with imenu.el."
  (save-match-data
    (cond
     ((idlwave-find-key "\\<\\(pro\\|function\\)\\>" -1 'nomark))
     ;;   ((idlwave-find-key idlwave-begin-unit-reg 1 'nomark)
     (t nil))))

(defun idlwave-unit-name ()
  "Return the unit name.
Assumes that point is at the beginning of the unit as found by
`idlwave-prev-index-position'."
  (forward-sexp 2)
  (forward-sexp -1)
  (let ((begin (point)))
    (re-search-forward "[a-zA-Z][a-zA-Z0-9$_]+\\(::[a-zA-Z][a-zA-Z0-9$_]+\\)?")
    (if (fboundp 'buffer-substring-no-properties)
        (buffer-substring-no-properties begin (point))
      (buffer-substring begin (point)))))

(defun idlwave-function-menu ()
  "Use `imenu' or `function-menu' to jump to a procedure or function."
  (interactive)
  (if (string-match "XEmacs" emacs-version)
      (progn
	(require 'func-menu)
	(function-menu))
    (require 'imenu)
    (imenu (imenu-choose-buffer-index))))

;; Here we kack func-menu.el in order to support this new mode.
;; The latest versions of func-menu.el already have this stuff in, so
;; we hack only if it is not already there.
(when (fboundp 'eval-after-load)
  (eval-after-load "func-menu"
    '(progn
       (or (assq 'idlwave-mode fume-function-name-regexp-alist)
	   (not (boundp 'fume-function-name-regexp-idl))      ; avoid problems
	   (setq fume-function-name-regexp-alist
		 (cons '(idlwave-mode . fume-function-name-regexp-idl)
		       fume-function-name-regexp-alist)))
       (or (assq 'idlwave-mode fume-find-function-name-method-alist)
	   (not (fboundp 'fume-find-next-idl-function-name))  ; avoid problems
	   (setq fume-find-function-name-method-alist
		 (cons '(idlwave-mode . fume-find-next-idl-function-name)
		       fume-find-function-name-method-alist))))))

(defun idlwave-edit-in-idlde ()
  "Edit the current file in IDL Development environment."
  (interactive)
  (start-process "idldeclient" nil
		 idlwave-shell-explicit-file-name "-c" "-e"
                 (buffer-file-name) "&"))
                
(defun idlwave-launch-idlhelp ()
  "Start the IDLhelp application."
  (interactive)
  (start-process "idlhelp" nil idlwave-help-application))
 
;; Menus - using easymenu.el
(defvar idlwave-mode-menu-def
  `("IDLWAVE"
    ["PRO/FUNC menu" idlwave-function-menu t]
    ("Motion"
     ["Subprogram Start" idlwave-beginning-of-subprogram t]
     ["Subprogram End" idlwave-end-of-subprogram t]
     ["Block Start" idlwave-beginning-of-block t]
     ["Block End" idlwave-end-of-block t]
     ["Up Block" idlwave-backward-up-block t]
     ["Down Block" idlwave-down-block t]
     ["Skip Block Backward" idlwave-backward-block t]
     ["Skip Block Forward" idlwave-forward-block t])
    ("Mark"
     ["Subprogram" idlwave-mark-subprogram t]
     ["Block" idlwave-mark-block t]
     ["Header" idlwave-mark-doclib t])
    ("Format"
     ["Indent Subprogram" idlwave-indent-subprogram t]
     ["(Un)Comment Region" idlwave-toggle-comment-region "C-c ;"]
     ["Continue/Split line" idlwave-split-line t]
     "--"
     ["Toggle Auto Fill" idlwave-auto-fill-mode :style toggle
      :selected (symbol-value idlwave-fill-function)])
    ("Templates"
     ["Procedure" idlwave-procedure t]
     ["Function" idlwave-function t]
     ["Doc Header" idlwave-doc-header t]
     ["Log" idlwave-doc-modification t]
     "--"
     ["Case" idlwave-case t]
     ["For" idlwave-for t]
     ["Repeat" idlwave-repeat t]
     ["While" idlwave-while t]
     "--"
     ["Close Block" idlwave-close-block t])
    ("Completion"
     ["Complete" idlwave-complete t]
     ("Complete Special"
      ["1 Procedure Name" (idlwave-complete 'procedure) t]
      ["2 Procedure Keyword" (idlwave-complete 'procedure-keyword) t]
      "--"
      ["3 Function Name" (idlwave-complete 'function) t]
      ["4 Function Keyword" (idlwave-complete 'function-keyword) t]
      "--"
      ["5 Procedure Method Name" (idlwave-complete 'procedure-method) t]
      ["6 Procedure Method Keyword" (idlwave-complete 'procedure-method-keyword) t]
      "--"
      ["7 Function Method Name" (idlwave-complete 'function-method) t]
      ["8 Function Method Keyword" (idlwave-complete 'function-method-keyword) t]
      "--"
      ["9 Class Name"  idlwave-complete-class t]))
    ("Routine Info"
     ["Show Routine Info" idlwave-routine-info t]
     ["Online Context Help" idlwave-context-help (idlwave-help-directory)]
     "--"
     ["Find Routine Source" idlwave-find-module t]
     ["Resolve Routine" idlwave-resolve (featurep 'idlw-shell)]
     "--"
     ["Update Routine Info" idlwave-update-routine-info t]
     "--"
     "IDL Library Catalog"
     ["Select Catalog Directories" (idlwave-create-libinfo-file nil) t]
     ["Scan Directories" (idlwave-update-routine-info '(16))
      (and idlwave-path-alist (not idlwave-catalog-process))]
     ["Scan Directories &" (idlwave-update-routine-info '(64))
      (and idlwave-path-alist (not idlwave-catalog-process))]
     "--"
     "Routine Shadows"
     ["Check Current Buffer" idlwave-list-buffer-load-path-shadows t]
     ["Check Compiled Routines" idlwave-list-shell-load-path-shadows t]
     ["Check Everything" idlwave-list-all-load-path-shadows t])
    ("Misc"
     ["Kill auto-created buffers" idlwave-kill-autoloaded-buffers t]
     "--"
     ["Insert TAB character" idlwave-hard-tab t])
     "--"
    ("External"
     ["Generate IDL tags" idlwave-make-tags t]
     ["Start IDL shell" idlwave-shell t]
     ["Edit file in IDLDE" idlwave-edit-in-idlde t]
     ["Launch IDL Help" idlwave-launch-idlhelp t])
    "--"
    ("Customize"
     ["Browse IDLWAVE Group" idlwave-customize t]
     "--"
     ["Build Full Customize Menu" idlwave-create-customize-menu 
      (fboundp 'customize-menu-create)])
    ("Documentation"
     ["Describe Mode" describe-mode t]
     ["Abbreviation List" idlwave-list-abbrevs t]
     "--"
     ["Commentary in idlwave.el" idlwave-show-commentary t]
     ["Commentary in idlw-shell.el" idlwave-shell-show-commentary t]
     "--"
     ["Info" idlwave-info t]
     "--"
     ["Launch IDL Help" idlwave-launch-idlhelp t])))

(defvar idlwave-mode-debug-menu-def
  '("Debug"
    ["Start IDL shell" idlwave-shell t]
    ["Save and .RUN buffer" idlwave-shell-save-and-run
     (and (boundp 'idlwave-shell-automatic-start) 
	  idlwave-shell-automatic-start)]))

(if (or (featurep 'easymenu) (load "easymenu" t))
    (progn
      (easy-menu-define idlwave-mode-menu idlwave-mode-map 
			"IDL and WAVE CL editing menu" 
			idlwave-mode-menu-def)
      (easy-menu-define idlwave-mode-debug-menu idlwave-mode-map 
			"IDL and WAVE CL editing menu" 
			idlwave-mode-debug-menu-def)))

(defun idlwave-customize ()
  "Call the customize function with idlwave as argument."
  (interactive)
  ;; Try to load the code for the shell, so that we can customize it 
  ;; as well.
  (or (featurep 'idlw-shell)
      (load "idlw-shell" t))
  (customize-browse 'idlwave))

(defun idlwave-create-customize-menu ()
  "Create a full customization menu for IDLWAVE, insert it into the menu."
  (interactive)
  (if (fboundp 'customize-menu-create)
      (progn
	;; Try to load the code for the shell, so that we can customize it 
	;; as well.
	(or (featurep 'idlw-shell)
	    (load "idlw-shell" t))
	(easy-menu-change 
	 '("IDLWAVE") "Customize"
	 `(["Browse IDLWAVE group" idlwave-customize t]
	   "--"
	   ,(customize-menu-create 'idlwave)
	   ["Set" Custom-set t]
	   ["Save" Custom-save t]
	   ["Reset to Current" Custom-reset-current t]
	   ["Reset to Saved" Custom-reset-saved t]
	   ["Reset to Standard Settings" Custom-reset-standard t]))
	(message "\"IDLWAVE\"-menu now contains full customization menu"))
    (error "Cannot expand menu (outdated version of cus-edit.el)")))

(defun idlwave-show-commentary ()
  "Use the finder to view the file documentation from `idlwave.el'."
  (interactive)
  (require 'finder)
  (finder-commentary "idlwave.el"))

(defun idlwave-shell-show-commentary ()
  "Use the finder to view the file documentation from `idlw-shell.el'."
  (interactive)
  (require 'finder)
  (finder-commentary "idlw-shell.el"))

(defun idlwave-info ()
  "Read documentation for IDLWAVE in the info system."
  (interactive)
  (require 'info)
  (Info-goto-node "(idlwave)"))

(defun idlwave-list-abbrevs (arg)
  "Show the code abbreviations define in IDLWAVE mode.
This lists all abbrevs where the replacement text differs from the input text.
These are the ones the users want to learn to speed up their writing.

The function does *not* list abbrevs which replace a word with itself
to call a hook.  These hooks are used to change the case of words or
to blink the matching `begin', and the user does not need to know them.

With arg, list all abbrevs with the corresponding hook.

This function was written since `list-abbrevs' looks terrible for IDLWAVE mode."

  (interactive "P")
  (let ((table (symbol-value 'idlwave-mode-abbrev-table))
	abbrevs
	str rpl func fmt (len-str 0) (len-rpl 0))
    (mapatoms 
     (lambda (sym)
       (if (symbol-value sym)
	   (progn
	     (setq str (symbol-name sym)
		   rpl (symbol-value sym)
		   func (symbol-function sym))
	     (if arg
		 (setq func (prin1-to-string func))
	       (if (and (listp func) (stringp (nth 2 func)))
		   (setq rpl (concat "EVAL: " (nth 2 func))
			 func "")
		 (setq func "")))
	     (if (or arg (not (string= rpl str)))
		 (progn
		   (setq len-str (max len-str (length str)))
		   (setq len-rpl (max len-rpl (length rpl)))
		   (setq abbrevs (cons (list str rpl func) abbrevs)))))))
     table)
    ;; sort the list
    (setq abbrevs (sort abbrevs (lambda (a b) (string< (car a) (car b)))))
    ;; Make the format
    (setq fmt (format "%%-%ds   %%-%ds   %%s\n" len-str len-rpl))
    (with-output-to-temp-buffer "*Help*"
      (if arg
	  (progn
	    (princ "Abbreviations and Actions in IDLWAVE-Mode\n") 
	    (princ "=========================================\n\n")
	    (princ (format fmt "KEY" "REPLACE" "HOOK"))
	    (princ (format fmt "---" "-------" "----")))
	(princ "Code Abbreviations and Templates in IDLWAVE-Mode\n")
	(princ "================================================\n\n")
	(princ (format fmt "KEY" "ACTION" ""))
	(princ (format fmt "---" "------" "")))
      (mapcar
       (lambda (list)
	 (setq str (car list)
	       rpl (nth 1 list)
	       func (nth 2 list))
	 (princ (format fmt str rpl func)))
       abbrevs)))
  ;; Make sure each abbreviation uses only one display line
  (save-excursion
    (set-buffer "*Help*")
    (setq truncate-lines t)))

;; Add .pro files to speedbar for support, if it's loaded
(eval-after-load "speedbar" '(speedbar-add-supported-extension ".pro"))

;; Try to load online help, but catch any errors.
(condition-case nil
    (idlwave-require-online-help)
  (error nil))

;; Set an idle timer to load the routine info.
;; Will only work on systems which support this.
(or idlwave-routines (idlwave-start-load-rinfo-timer))

;; Run the hook
(run-hooks 'idlwave-load-hook)

;; XEmacs addition
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.[Pp][Rr][Oo]\\'" . idlwave-mode))

(provide 'idlwave)

;;; idlwave.el ends here
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.