summaryrefslogtreecommitdiff
path: root/emacs/cperl-mode.el
blob: c78a148e452d95ec6e2732778c7b5a6c1f72cfcf (plain)
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
;;; This code started from the following message of long time ago (IZ):

;;; From: olson@mcs.anl.gov (Bob Olson)
;;; Newsgroups: comp.lang.perl
;;; Subject: cperl-mode: Another perl mode for Gnuemacs
;;; Date: 14 Aug 91 15:20:01 GMT

;; Perl code editing commands for Emacs
;; Copyright (C) 1985-1996 Bob Olson, Ilya Zakharevich

;; This file is not (yet) part of GNU Emacs. It may be distributed
;; either under the same terms as GNU Emacs, or under the same terms
;; as Perl. You should have recieved a copy of Perl Artistic license
;; along with the Perl distribution.

;; 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, 675 Mass Ave, Cambridge, MA 02139, USA.

;;; Corrections made by Ilya Zakharevich ilya@math.mps.ohio-state.edu
;;; XEmacs changes by Peter Arius arius@informatik.uni-erlangen.de

;; $Id: cperl-mode.el,v 1.25 1996/09/06 09:51:41 ilya Exp ilya $

;;; To use this mode put the following into your .emacs file:

;; (autoload 'perl-mode "cperl-mode" "alternate mode for editing Perl programs" t)

;;; You can either fine-tune the bells and whistles of this mode or
;;; bulk enable them by putting

;; (setq cperl-hairy t)

;;; in your .emacs file. (Emacs rulers do not consider it politically
;;; correct to make whistles enabled by default.)

;;; Additional useful commands to put into your .emacs file:

;; (setq auto-mode-alist
;;       (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
;; (setq interpreter-mode-alist (append interpreter-mode-alist
;; 				        '(("miniperl" . perl-mode))))

;;; The mode information (on C-h m) provides customization help.
;;; If you use font-lock feature of this mode, it is advisable to use
;;; eather lazy-lock-mode or fast-lock-mode (available on ELisp
;;; archive in files lazy-lock.el and fast-lock.el). I prefer lazy-lock.

;;; Faces used now: three faces for first-class and second-class keywords
;;; and control flow words, one for each: comments, string, labels,
;;; functions definitions and packages, arrays, hashes, and variable
;;; definitions. If you do not see all these faces, your font-lock does
;;; not define them, so you need to define them manually. Maybe you have 
;;; an obsolete font-lock from 19.28 or earlier. Upgrade.

;;; If you have grayscale monitor, and do not have the variable
;;; font-lock-display-type bound to 'grayscale, insert 

;;; (setq font-lock-display-type 'grayscale)

;;; to your .emacs file.

;;;; This mode supports font-lock, imenu and mode-compile. In the
;;;; hairy version font-lock is on, but you should activate imenu
;;;; yourself (note that mode-compile is not standard yet). Well, you
;;;; can use imenu from keyboard anyway (M-x imenu), but it is better
;;;; to bind it like that:

;; (define-key global-map [M-S-down-mouse-3] 'imenu)

;;; In fact the version of font-lock that this version supports can be
;;; much newer than the version you actually have. This means that a
;;; lot of faces can be set up, but are not visible on your screen
;;; since the coloring rules for this faces are not defined.

;;; Updates: ========================================

;;; Made less hairy by default: parentheses not electric, 
;;; linefeed not magic. Bug with abbrev-mode corrected.

;;;; After 1.4:
;;;  Better indentation:
;;;  subs inside braces should work now, 
;;;  Toplevel braces obey customization.
;;;  indent-for-comment knows about bad cases, cperl-indent-for-comment
;;;  moves cursor to a correct place.
;;;  cperl-indent-exp written from the scratch! Slow... (quadratic!) :-( 
;;;        (50 secs on DB::DB (sub of 430 lines), 486/66)
;;;  Minor documentation fixes.
;;;  Imenu understands packages as prefixes (including nested).
;;;  Hairy options can be switched off one-by-one by setting to null.
;;;  Names of functions and variables changed to conform to `cperl-' style.

;;;; After 1.5:
;;;  Some bugs with indentation of labels (and embedded subs) corrected.
;;;  `cperl-indent-region' done (slow :-()).
;;;  `cperl-fill-paragraph' done.
;;;  Better package support for `imenu'.
;;;  Progress indicator for indentation (with `imenu' loaded).
;;;  `Cperl-set' was busted, now setting the individual hairy option 
;;;     should be better.

;;;; After 1.6:
;;; `cperl-set-style' done.
;;; `cperl-check-syntax' done.
;;; Menu done.
;;; New config variables `cperl-close-paren-offset' and `cperl-comment-column'.
;;; Bugs with `cperl-auto-newline' corrected.
;;; `cperl-electric-lbrace' can work with `cperl-auto-newline' in situation 
;;; like $hash{.

;;;; 1.7 XEmacs (arius@informatik.uni-erlangen.de):
;;; - use `next-command-event', if `next-command-events' does not exist
;;; - use `find-face' as def. of `is-face'
;;; - corrected def. of `x-color-defined-p'
;;; - added const defs for font-lock-comment-face,
;;;   font-lock-keyword-face and font-lock-function-name-face
;;; - added def. of font-lock-variable-name-face
;;; - added (require 'easymenu) inside an `eval-when-compile'
;;; - replaced 4-argument `substitute-key-definition' with ordinary
;;;   `define-key's
;;; - replaced `mark-active' in menu definition by `cperl-use-region-p'.
;;; Todo (at least):
;;; - use emacs-vers.el (http://www.cs.utah.edu/~eeide/emacs/emacs-vers.el.gz)
;;;   for portable code?
;;; - should `cperl-mode' do a 
;;;	(if (featurep 'easymenu) (easy-menu-add cperl-menu))
;;;   or should this be left to the user's `cperl-mode-hook'?

;;; Some bugs introduced by the above fix corrected (IZ ;-).
;;; Some bugs under XEmacs introduced by the correction corrected.

;;; Some more can remain since there are two many different variants. 
;;; Please feedback!

;;; We do not support fontification of arrays and hashes under 
;;; obsolete font-lock any more. Upgrade.

;;;; after 1.8 Minor bug with parentheses.
;;;; after 1.9 Improvements from Joe Marzot.
;;;; after 1.10
;;;  Does not need easymenu to compile under XEmacs.
;;;  `vc-insert-headers' should work better.
;;;  Should work with 19.29 and 19.12.
;;;  Small improvements to fontification.
;;;  Expansion of keywords does not depend on C-? being backspace.

;;; after 1.10+
;;; 19.29 and 19.12 supported.
;;; `cperl-font-lock-enhanced' deprecated. Use font-lock-extra.el.
;;; Support for font-lock-extra.el.

;;;; After 1.11:
;;; Tools submenu.
;;; Support for perl5-info.
;;; `imenu-go-find-at-position' in Tools requires imenu-go.el (see hints above)
;;; Imenu entries do not work with stock imenu.el. Patch sent to maintainers.
;;; Fontifies `require a if b;', __DATA__.
;;; Arglist for auto-fill-mode was incorrect.

;;;; After 1.12:
;;; `cperl-lineup-step' and `cperl-lineup' added: lineup constructions 
;;; vertically.
;;; `cperl-do-auto-fill' updated for 19.29 style.
;;; `cperl-info-on-command' now has a default.
;;; Workaround for broken C-h on XEmacs.
;;; VC strings escaped.
;;; C-h f now may prompt for function name instead of going on,
;;; controlled by `cperl-info-on-command-no-prompt'.

;;;; After 1.13:
;;; Msb buffer list includes perl files
;;; Indent-for-comment uses indent-to
;;; Can write tag files using etags.

;;;; After 1.14:
;;; Recognizes (tries to ;-) {...} which are not blocks during indentation.
;;; `cperl-close-paren-offset' affects ?\] too (and ?\} if not block)
;;; Bug with auto-filling comments started with "##" corrected.

;;;; Very slow now: on DB::DB 0.91, 486/66:

;;;Function Name                             Call Count  Elapsed Time  Average Time
;;;========================================  ==========  ============  ============
;;;cperl-block-p                             469         3.7799999999  0.0080597014
;;;cperl-get-state                           505         163.39000000  0.3235445544
;;;cperl-comment-indent                      12          0.0299999999  0.0024999999
;;;cperl-backward-to-noncomment              939         4.4599999999  0.0047497337
;;;cperl-calculate-indent                    505         172.22000000  0.3410297029
;;;cperl-indent-line                         505         172.88000000  0.3423366336
;;;cperl-use-region-p                        40          0.0299999999  0.0007499999
;;;cperl-indent-exp                          1           177.97000000  177.97000000
;;;cperl-to-comment-or-eol                   1453        3.9800000000  0.0027391603
;;;cperl-backward-to-start-of-continued-exp  9           0.0300000000  0.0033333333
;;;cperl-indent-region                       1           177.94000000  177.94000000

;;;; After 1.15:
;;; Takes into account white space after opening parentheses during indent.
;;; May highlight pods and here-documents: see `cperl-pod-here-scan',
;;; `cperl-pod-here-fontify', `cperl-pod-face'. Does not use this info
;;; for indentation so far.
;;; Fontification updated to 19.30 style. 
;;; The change 19.29->30 did not add all the required functionality,
;;;     but broke "font-lock-extra.el". Get "choose-color.el" from
;;;       ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs

;;;; After 1.16:
;;;       else # comment
;;;    recognized as a start of a block.
;;;  Two different font-lock-levels provided.
;;;  `cperl-pod-head-face' introduced. Used for highlighting.
;;;  `imenu' marks pods, +Packages moved to the head. 

;;;; After 1.17:
;;;  Scan for pods highlights here-docs too.
;;;  Note that the tag of here-doc may be rehighlighted later by lazy-lock.
;;;  Only one here-doc-tag per line is supported, and one in comment
;;;  or a string may break fontification.
;;;  POD headers were supposed to fill one line only.

;;;; After 1.18:
;;;  `font-lock-keywords' were set in 19.30 style _always_. Current scheme 
;;;    may  break under XEmacs.
;;;  `cperl-calculate-indent' dis suppose that `parse-start' was defined.
;;;  `fontified' tag is added to fontified text as well as `lazy-lock' (for
;;;    compatibility with older lazy-lock.el) (older one overfontifies
;;;    something nevertheless :-().
;;;  Will not indent something inside pod and here-documents.
;;;  Fontifies the package name after import/no/bootstrap.
;;;  Added new entry to menu with meta-info about the mode.

;;;; After 1.19:
;;;  Prefontification works much better with 19.29. Should be checked
;;;   with 19.30 as well.
;;;  Some misprints in docs corrected.
;;;  Now $a{-text} and -text => "blah" are fontified as strings too.
;;;  Now the pod search is much stricter, so it can help you to find
;;;    pod sections which are broken because of whitespace before =blah
;;;    - just observe the fontification.

;;;; After 1.20
;;;  Anonymous subs are indented with respect to the level of
;;;    indentation of `sub' now.
;;;  {} is recognized as hash after `bless' and `return'.
;;;  Anonymous subs are split by `cperl-linefeed' as well.
;;;  Electric parens embrace a region if present.
;;;  To make `cperl-auto-newline' useful,
;;;    `cperl-auto-newline-after-colon' is introduced.
;;;  `cperl-electric-parens' is now t or nul. The old meaning is moved to
;;;  `cperl-electric-parens-string'.
;;;  `cperl-toggle-auto-newline' introduced, put on C-c C-a.
;;;  `cperl-toggle-abbrev' introduced, put on C-c C-k.
;;;  `cperl-toggle-electric' introduced, put on C-c C-e.
;;;  Beginning-of-defun-regexp was not anchored.

;;;; After 1.21
;;;  Auto-newline grants `cperl-extra-newline-before-brace' if "{" is typed
;;;    after ")".
;;;  {} is recognized as expression after `tr' and friends.

;;;; After 1.22
;;;  Entry Hierarchy added to imenu. Very primitive so far.
;;;  One needs newer `imenu-go'.el. A patch to `imenu' is needed as well.
;;;  Writes its own TAGS files.
;;;  Class viewer based on TAGS files. Does not trace @ISA so far.
;;;  19.31: Problems with scan for PODs corrected.
;;;  First POD header correctly fontified.
;;;  I needed (setq imenu-use-keymap-menu t) to get good imenu in 19.31.
;;;  Apparently it makes a lot of hierarchy code obsolete...

;;;; After 1.23
;;;  Tags filler now scans *.xs as well.
;;;  The info from *.xs scan is used by the hierarchy viewer.
;;;  Hierarchy viewer documented.
;;;  Bug in 19.31 imenu documented.

;;;; After 1.24
;;;  New location for info-files mentioned,
;;;  Electric-; should work better.
;;;  Minor bugs with POD marking.

;;;; After 1.25
;;;  `cperl-info-page' introduced.  
;;;  To make `uncomment-region' working, `comment-region' would
;;;  not insert extra space.
;;;  Here documents delimiters better recognized 
;;;  (empty one, and non-alphanums in quotes handled). May be wrong with 1<<14?
;;;  `cperl-db' added, used in menu.
;;;  imenu scan removes text-properties, for better debugging
;;;    - but the bug is in 19.31 imenu.
;;;  formats highlighted by font-lock and prescan, embedded comments
;;;  are not treated.
;;;  POD/friends scan merged in one pass.
;;;  Syntax class is not used for analyzing the code, only char-syntax
;;;  may be cecked against _ or'ed with w.
;;;  Syntax class of `:' changed to be _.
;;;  `cperl-find-bad-style' added.

(defvar cperl-extra-newline-before-brace nil
  "*Non-nil means that if, elsif, while, until, else, for, foreach
and do constructs look like:

	if ()
	{
	}

instead of:

	if () {
	}
")

(defvar cperl-indent-level 2
  "*Indentation of CPerl statements with respect to containing block.")
(defvar cperl-lineup-step nil
  "*`cperl-lineup' will always lineup at multiple of this number.
If `nil', the value of `cperl-indent-level' will be used.")
(defvar cperl-brace-imaginary-offset 0
  "*Imagined indentation of a Perl open brace that actually follows a statement.
An open brace following other text is treated as if it were this far
to the right of the start of its line.")
(defvar cperl-brace-offset 0
  "*Extra indentation for braces, compared with other text in same context.")
(defvar cperl-label-offset -2
  "*Offset of CPerl label lines relative to usual indentation.")
(defvar cperl-min-label-indent 1
  "*Minimal offset of CPerl label lines.")
(defvar cperl-continued-statement-offset 2
  "*Extra indent for lines not starting new statements.")
(defvar cperl-continued-brace-offset 0
  "*Extra indent for substatements that start with open-braces.
This is in addition to cperl-continued-statement-offset.")
(defvar cperl-close-paren-offset -1
  "*Extra indent for substatements that start with close-parenthesis.")

(defvar cperl-auto-newline nil
  "*Non-nil means automatically newline before and after braces,
and after colons and semicolons, inserted in CPerl code. The following
\\[cperl-electric-backspace] will remove the inserted whitespace.
Insertion after colons requires both this variable and 
`cperl-auto-newline-after-colon' set.")

(defvar cperl-auto-newline-after-colon nil
  "*Non-nil means automatically newline even after colons.
Subject to `cperl-auto-newline' setting.")

(defvar cperl-tab-always-indent t
  "*Non-nil means TAB in CPerl mode should always reindent the current line,
regardless of where in the line point is when the TAB command is used.")

(defvar cperl-font-lock nil
  "*Non-nil (and non-null) means CPerl buffers will use font-lock-mode.
Can be overwritten by `cperl-hairy' if nil.")

(defvar cperl-electric-lbrace-space nil
  "*Non-nil (and non-null) means { after $ in CPerl buffers should be preceeded by ` '.
Can be overwritten by `cperl-hairy' if nil.")

(defvar cperl-electric-parens-string "({[<"
  "*String of parentheses that should be electric in CPerl.")

(defvar cperl-electric-parens nil
  "*Non-nil (and non-null) means parentheses should be electric in CPerl.
Can be overwritten by `cperl-hairy' if nil.")
(defvar cperl-electric-parens-mark  
  (and window-system
       (or (and (boundp 'transient-mark-mode) ; For Emacs
		transient-mark-mode)
	   (and (boundp 'zmacs-regions) ; For XEmacs
		zmacs-regions)))
  "*Not-nil means that electric parens look for active mark.
Default is yes if there is visual feedback on mark.")

(defvar cperl-electric-parens-mark (and window-system transient-mark-mode)
  "*Not-nil means that electric parens look for active mark.
Default is yes if there is visual feedback on mark.")

(defvar cperl-electric-linefeed nil
  "*If true, LFD should be hairy in CPerl, otherwise C-c LFD is hairy.
In any case these two mean plain and hairy linefeeds together.
Can be overwritten by `cperl-hairy' if nil.")

(defvar cperl-electric-keywords nil
  "*Not-nil (and non-null) means keywords are electric in CPerl.
Can be overwritten by `cperl-hairy' if nil.")

(defvar cperl-hairy nil
  "*Not-nil means all the bells and whistles are enabled in CPerl.")

(defvar cperl-comment-column 32
  "*Column to put comments in CPerl (use \\[cperl-indent]' to lineup with code).")

(defvar cperl-vc-header-alist '((SCCS "$sccs = '%W\%' ;")
				(RCS "$rcs = ' $Id\$ ' ;"))
  "*What to use as `vc-header-alist' in CPerl.")

(defvar cperl-info-on-command-no-prompt nil
  "*Not-nil (and non-null) means not to prompt on C-h f.
The opposite behaviour is always available if prefixed with C-c.
Can be overwritten by `cperl-hairy' if nil.")

(defvar cperl-pod-face 'font-lock-comment-face
  "*The result of evaluation of this expression is used for pod highlighting.")

(defvar cperl-pod-head-face 'font-lock-variable-name-face
  "*The result of evaluation of this expression is used for pod highlighting.
Font for POD headers.")

(defvar cperl-here-face 'font-lock-string-face
  "*The result of evaluation of this expression is used for here-docs highlighting.")

(defvar cperl-pod-here-fontify '(featurep 'font-lock)
  "*Not-nil after evaluation means to highlight pod and here-docs sections.")

(defvar cperl-pod-here-scan t
  "*Not-nil means look for pod and here-docs sections during startup.
You can always make lookup from menu or using \\[cperl-find-pods-heres].")

(defvar cperl-imenu-addback nil
  "*Not-nil means add backreferences to generated `imenu's.
May require patched `imenu' and `imenu-go'.")

(defvar cperl-info-page "perl"
  "Name of the info page containging perl docs.
Older version of this page was called `perl5', newer `perl'.")



;;; Short extra-docs.

(defvar cperl-tips 'please-ignore-this-line
  "Get newest version of this package from
  ftp://ftp.math.ohio-state.edu/pub/users/ilya/emacs
and/or
  ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl

Get support packages choose-color.el (or font-lock-extra.el before
19.30), imenu-go.el from the same place.  \(Look for other files there
too... ;-) Get a patch for imenu.el in 19.29.  Note that for 19.30 and
later you should use choose-color.el *instead* of font-lock-extra.el 
\(and you will not get smart highlighting in C :-().

Note that to enable Compile choices in the menu you need to install
mode-compile.el.

Get perl5-info from 
  $CPAN/doc/manual/info/perl-info.tar.gz
older version was on
  http://www.metronet.com:70/9/perlinfo/perl5/manual/perl5-info.tar.gz

If you use imenu-go, run imenu on perl5-info buffer (you can do it
from CPerl menu). If many files are related, generate TAGS files from
Tools/Tags submenu in CPerl menu.

If some class structure is too complicated, use Tools/Hierarchy-view
from CPerl menu, or hierarchic view of imenu. The second one uses the
current buffer only, the first one requires generation of TAGS from
CPerl/Tools/Tags menu beforehand.

Run CPerl/Tools/Insert-spaces-if-needed to fix your lazy typing.

Before reporting (non-)problems look in the problem section on what I
know about them.")

(defvar cperl-problems 'please-ignore-this-line
"Emacs has a _very_ restricted syntax parsing engine. 

It may be corrected on the level of C code, please look in the
`non-problems' section if you want to volunteer.

CPerl mode tries to corrects some Emacs misunderstandings, however,
for effeciency reasons the degree of correction is different for
different operations. The partially corrected problems are: POD
sections, here-documents, regexps. The operations are: highlighting,
indentation, electric keywords, electric braces. 

This may be confusing, since the regexp s#//#/#\; may be highlighted
as a comment, but it will recognized as a regexp by the indentation
code. Or the opposite case, when a pod section is highlighted, but
breaks the indentation of the following code.

The main trick (to make $ a \"backslash\") makes constructions like
${aaa} look like unbalanced braces. The only trick I can think out is
to insert it as $ {aaa} (legal in perl5, not in perl4). 

Similar problems arise in regexps, when /(\\s|$)/ should be rewritten
as /($|\\s)/. Note that such a transpositinon is not always possible
:-(.  " )

(defvar cperl-non-problems 'please-ignore-this-line
"As you know from `problems' section, Perl syntax too hard for CPerl.

Most the time, if you write your own code, you may find an equivalent
\(and almost as readable) expression.

Try to help it: add comments with embedded quotes to fix CPerl
misunderstandings about the end of quotation:

$a='500$';      # ';

You won't need it too often. The reason: $ \"quotes\" the following
character (this saves a life a lot of times in CPerl), thus due to
Emacs parsing rules it does not consider tick after the dollar as a
closing one, but as a usual character.

Now the indentation code is pretty wise. The only drawback is that it
relies on Emacs parsing to find matching parentheses. And Emacs
*cannot* match parentheses in Perl 100% correctly. So
	1 if s#//#/#;
will not break indentation, but
	1 if ( s#//#/# );
will.

If you still get wrong indentation in situation that you think the
code should be able to parse, try:

a) Check what Emacs thinks about balance of your parentheses.
b) Supply the code to me (IZ).

Pods are treated _very_ rudimentally. Here-documents are not treated
at all (except highlighting and inhibiting indentation). (This may
change some time. RMS approved making syntax lookup recognize text
attributes, but volonteers are needed to change Emacs C code.)

To speed up coloring the following compromises exist:
   a) sub in $mypackage::sub may be highlighted.
   b) -z in [a-z] may be highlighted.
   c) if your regexp contains a keyword (like \"s\"), it may be highlighted.


Imenu in 19.31 is broken. Set `imenu-use-keymap-menu' to t, and remove
`car' before `imenu-choose-buffer-index' in `imenu'.
")



;;; Portability stuff:

(defsubst cperl-xemacs-p ()
  (string-match "XEmacs\\|Lucid" emacs-version))

(defvar del-back-ch (car (append (where-is-internal 'delete-backward-char)
				 (where-is-internal 'backward-delete-char-untabify)))
  "Character generated by key bound to delete-backward-char.")

(and (vectorp del-back-ch) (= (length del-back-ch) 1) 
     (setq del-back-ch (aref del-back-ch 0)))

(if (cperl-xemacs-p)
    (progn
      ;; "Active regions" are on: use region only if active
      ;; "Active regions" are off: use region unconditionally
      (defun cperl-use-region-p ()
	(if zmacs-regions (mark) t))
      (defun cperl-mark-active () (mark)))
  (defun cperl-use-region-p ()
    (if transient-mark-mode mark-active t))
  (defun cperl-mark-active () mark-active))

(defsubst cperl-enable-font-lock ()
  (or (cperl-xemacs-p) window-system))

(if (boundp 'unread-command-events)
    (if (cperl-xemacs-p)
	(defun cperl-putback-char (c)	; XEmacs >= 19.12
	  (setq unread-command-events (list (character-to-event c))))
      (defun cperl-putback-char (c)	; Emacs 19
	(setq unread-command-events (list c))))
  (defun cperl-putback-char (c)		; XEmacs <= 19.11
    (setq unread-command-event (character-to-event c))))

(or (fboundp 'uncomment-region)
    (defun uncomment-region (beg end)
      (interactive "r")
      (comment-region beg end -1)))

(defvar cperl-do-not-fontify
  (if (string< emacs-version "19.30")
      'fontified
    'lazy-lock)
  "Text property which inhibits refontification.")

(defsubst cperl-put-do-not-fontify (from to)
  (put-text-property (max (point-min) (1- from))
		     to cperl-do-not-fontify t))


;;; Probably it is too late to set these guys already, but it can help later:

(setq auto-mode-alist
      (append '(("\\.[pP][Llm]$" . perl-mode))  auto-mode-alist ))
(and (boundp 'interpreter-mode-alist)
     (setq interpreter-mode-alist (append interpreter-mode-alist
					  '(("miniperl" . perl-mode)))))
(if (fboundp 'eval-when-compile)
    (eval-when-compile
      (condition-case nil
	  (require 'imenu)
	(error nil))
      (condition-case nil
	  (require 'easymenu)
	(error nil))
      ;; Calling `cperl-enable-font-lock' below doesn't compile on XEmacs,
      ;; macros instead of defsubsts don't work on Emacs, so we do the
      ;; expansion manually. Any other suggestions?
      (if (or (string-match "XEmacs\\|Lucid" emacs-version)
	      window-system)
	  (require 'font-lock))
      (require 'cl)
      ))

(defvar cperl-mode-abbrev-table nil
  "Abbrev table in use in Cperl-mode buffers.")

(add-hook 'edit-var-mode-alist '(perl-mode (regexp . "^cperl-")))

(defvar cperl-mode-map () "Keymap used in CPerl mode.")

(if cperl-mode-map nil
  (setq cperl-mode-map (make-sparse-keymap))
  (define-key cperl-mode-map "{" 'cperl-electric-lbrace)
  (define-key cperl-mode-map "[" 'cperl-electric-paren)
  (define-key cperl-mode-map "(" 'cperl-electric-paren)
  (define-key cperl-mode-map "<" 'cperl-electric-paren)
  (define-key cperl-mode-map "}" 'cperl-electric-brace)
  (define-key cperl-mode-map ";" 'cperl-electric-semi)
  (define-key cperl-mode-map ":" 'cperl-electric-terminator)
  (define-key cperl-mode-map "\C-j" 'newline-and-indent)
  (define-key cperl-mode-map "\C-c\C-j" 'cperl-linefeed)
  (define-key cperl-mode-map "\C-c\C-a" 'cperl-toggle-auto-newline)
  (define-key cperl-mode-map "\C-c\C-k" 'cperl-toggle-abbrev)
  (define-key cperl-mode-map "\C-c\C-e" 'cperl-toggle-electric)
  (define-key cperl-mode-map "\e\C-q" 'cperl-indent-exp) ; Usually not bound
  ;;(define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
  ;;(define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
  (define-key cperl-mode-map "\177" 'cperl-electric-backspace)
  (define-key cperl-mode-map "\t" 'cperl-indent-command)
  (if (cperl-xemacs-p)
      ;; don't clobber the backspace binding:
      (define-key cperl-mode-map [(control h) f] 'cperl-info-on-command)
    (define-key cperl-mode-map "\C-hf" 'cperl-info-on-command))
  (if (cperl-xemacs-p)
      ;; don't clobber the backspace binding:
      (define-key cperl-mode-map [(control c) (control h) f]
	'cperl-info-on-current-command)
    (define-key cperl-mode-map "\C-c\C-hf" 'cperl-info-on-current-command))
  (if (and (cperl-xemacs-p) 
	   (<= emacs-minor-version 11) (<= emacs-major-version 19))
      (progn
	;; substitute-key-definition is usefulness-deenhanced...
	(define-key cperl-mode-map "\M-q" 'cperl-fill-paragraph)
	(define-key cperl-mode-map "\e;" 'cperl-indent-for-comment)
	(define-key cperl-mode-map "\e\C-\\" 'cperl-indent-region))
    (substitute-key-definition
     'indent-sexp 'cperl-indent-exp
     cperl-mode-map global-map)
    (substitute-key-definition
     'fill-paragraph 'cperl-fill-paragraph
     cperl-mode-map global-map)
    (substitute-key-definition
     'indent-region 'cperl-indent-region
     cperl-mode-map global-map)
    (substitute-key-definition
     'indent-for-comment 'cperl-indent-for-comment
     cperl-mode-map global-map)))

(condition-case nil
    (progn
      (require 'easymenu)
      (easy-menu-define cperl-menu cperl-mode-map "Menu for CPerl mode"
         '("Perl"
	   ["Beginning of function" beginning-of-defun t]
	   ["End of function" end-of-defun t]
	   ["Mark function" mark-defun t]
	   ["Indent expression" cperl-indent-exp t]
	   ["Fill paragraph/comment" cperl-fill-paragraph t]
	   ["Line up a construction" cperl-lineup (cperl-use-region-p)]
	   "----"
	   ["Indent region" cperl-indent-region (cperl-use-region-p)]
	   ["Comment region" cperl-comment-region (cperl-use-region-p)]
	   ["Uncomment region" cperl-uncomment-region (cperl-use-region-p)]
	   "----"
	   ["Run" mode-compile (fboundp 'mode-compile)]
	   ["Kill" mode-compile-kill (and (fboundp 'mode-compile-kill)
					  (get-buffer "*compilation*"))]
	   ["Next error" next-error (get-buffer "*compilation*")]
	   ["Check syntax" cperl-check-syntax (fboundp 'mode-compile)]
	   "----"
	   ["Debugger" cperl-db t]
	   "----"
	   ("Tools"
	    ["Imenu" imenu (fboundp 'imenu)]
	    ["Insert spaces if needed" cperl-find-bad-style t]
	    ["Class Hierarchy from TAGS" cperl-tags-hier-init t]
	    ;;["Update classes" (cperl-tags-hier-init t) tags-table-list]
	    ["Imenu on info" cperl-imenu-on-info (featurep 'imenu)]
	    ("Tags"
;;;	     ["Create tags for current file" cperl-etags t]
;;;	     ["Add tags for current file" (cperl-etags t) t]
;;;	     ["Create tags for Perl files in directory" (cperl-etags nil t) t]
;;;	     ["Add tags for Perl files in directory" (cperl-etags t t) t]
;;;	     ["Create tags for Perl files in (sub)directories" 
;;;	      (cperl-etags nil 'recursive) t]
;;;	     ["Add tags for Perl files in (sub)directories"
;;;	      (cperl-etags t 'recursive) t]) 
;;;; cperl-write-tags (&optional file erase recurse dir inbuffer)
	     ["Create tags for current file" (cperl-write-tags nil t) t]
	     ["Add tags for current file" (cperl-write-tags) t]
	     ["Create tags for Perl files in directory" 
	      (cperl-write-tags nil t nil t) t]
	     ["Add tags for Perl files in directory" 
	      (cperl-write-tags nil nil nil t) t]
	     ["Create tags for Perl files in (sub)directories" 
	      (cperl-write-tags nil t t t) t]
	     ["Add tags for Perl files in (sub)directories"
	      (cperl-write-tags nil nil t t) t])
	    ["Recalculate PODs and HEREs" cperl-find-pods-heres t]
	    ["Define word at point" imenu-go-find-at-position 
	     (fboundp 'imenu-go-find-at-position)]
	    ["Help on function" cperl-info-on-command t]
	    ["Help on function at point" cperl-info-on-current-command t])
	   ("Toggle..."
	    ["Auto newline" cperl-toggle-auto-newline t]
	    ["Electric parens" cperl-toggle-electric t]
	    ["Electric keywords" cperl-toggle-abbrev t]
	    )
	   ("Indent styles..."
	    ["GNU" (cperl-set-style "GNU") t]
	    ["C++" (cperl-set-style "C++") t]
	    ["FSF" (cperl-set-style "FSF") t]
	    ["BSD" (cperl-set-style "BSD") t]
	    ["Whitesmith" (cperl-set-style "Whitesmith") t])
	   ("Micro-docs"
	    ["Tips" (describe-variable 'cperl-tips) t]
	    ["Problems" (describe-variable 'cperl-problems) t]
	    ["Non-problems" (describe-variable 'cperl-non-problems) t]))))
  (error nil))

(autoload 'c-macro-expand "cmacexp"
  "Display the result of expanding all C macros occurring in the region.
The expansion is entirely correct because it uses the C preprocessor."
  t)

(defvar cperl-mode-syntax-table nil
  "Syntax table in use in Cperl-mode buffers.")

(if cperl-mode-syntax-table
    ()
  (setq cperl-mode-syntax-table (make-syntax-table))
  (modify-syntax-entry ?\\ "\\" cperl-mode-syntax-table)
  (modify-syntax-entry ?/ "." cperl-mode-syntax-table)
  (modify-syntax-entry ?* "." cperl-mode-syntax-table)
  (modify-syntax-entry ?+ "." cperl-mode-syntax-table)
  (modify-syntax-entry ?- "." cperl-mode-syntax-table)
  (modify-syntax-entry ?= "." cperl-mode-syntax-table)
  (modify-syntax-entry ?% "." cperl-mode-syntax-table)
  (modify-syntax-entry ?< "." cperl-mode-syntax-table)
  (modify-syntax-entry ?> "." cperl-mode-syntax-table)
  (modify-syntax-entry ?& "." cperl-mode-syntax-table)
  (modify-syntax-entry ?$ "\\" cperl-mode-syntax-table)
  (modify-syntax-entry ?\n ">" cperl-mode-syntax-table)
  (modify-syntax-entry ?# "<" cperl-mode-syntax-table)
  (modify-syntax-entry ?' "\"" cperl-mode-syntax-table)
  (modify-syntax-entry ?` "\"" cperl-mode-syntax-table)
  (modify-syntax-entry ?_ "w" cperl-mode-syntax-table)
  (modify-syntax-entry ?: "_" cperl-mode-syntax-table)
  (modify-syntax-entry ?| "." cperl-mode-syntax-table))



;; Make customization possible "in reverse"
;;(defun cperl-set (symbol to)
;;  (or (eq (symbol-value symbol) 'null) (set symbol to)))
(defsubst cperl-val (symbol &optional default hairy)
  (cond
   ((eq (symbol-value symbol) 'null) default)
   (cperl-hairy (or hairy t))
   (t (symbol-value symbol))))

;; provide an alias for working with emacs 19.  the perl-mode that comes
;; with it is really bad, and this lets us seamlessly replace it.
(fset 'perl-mode 'cperl-mode)
(defun cperl-mode ()
  "Major mode for editing Perl code.
Expression and list commands understand all C brackets.
Tab indents for Perl code.
Paragraphs are separated by blank lines only.
Delete converts tabs to spaces as it moves back.

Various characters in Perl almost always come in pairs: {}, (), [],
sometimes <>. When the user types the first, she gets the second as
well, with optional special formatting done on {}.  (Disabled by
default.)  You can always quote (with \\[quoted-insert]) the left
\"paren\" to avoid the expansion. The processing of < is special,
since most the time you mean \"less\". Cperl mode tries to guess
whether you want to type pair <>, and inserts is if it
appropriate. You can set `cperl-electric-parens-string' to the string that
contains the parenths from the above list you want to be electrical.
Electricity of parenths is controlled by `cperl-electric-parens'.
You may also set `cperl-electric-parens-mark' to have electric parens
look for active mark and \"embrace\" a region if possible.'

CPerl mode provides expansion of the Perl control constructs:
   if, else, elsif, unless, while, until, for, and foreach.
=========(Disabled by default, see `cperl-electric-keywords'.)
The user types the keyword immediately followed by a space, which causes
the construct to be expanded, and the user is positioned where she is most
likely to want to be.
eg. when the user types a space following \"if\" the following appears in
the buffer:
            if () {     or   if ()
            }                 {
                              }
and the cursor is between the parentheses.  The user can then type some
boolean expression within the parens.  Having done that, typing
\\[cperl-linefeed] places you, appropriately indented on a new line
between the braces. If CPerl decides that you want to insert
\"English\" style construct like
            bite if angry;
it will not do any expansion. See also help on variable 
`cperl-extra-newline-before-brace'.

\\[cperl-linefeed] is a convinience replacement for typing carriage
return. It places you in the next line with proper indentation, or if
you type it inside the inline block of control construct, like
            foreach (@lines) {print; print}
and you are on a boundary of a statement inside braces, it will
transform the construct into a multiline and will place you into an
apporpriately indented blank line. If you need a usual 
`newline-and-indent' behaviour, it is on \\[newline-and-indent], 
see documentation on `cperl-electric-linefeed'.

\\{cperl-mode-map}

Setting the variable `cperl-font-lock' to t switches on
font-lock-mode, `cperl-electric-lbrace-space' to t switches on
electric space between $ and {, `cperl-electric-parens-string' is the
string that contains parentheses that should be electric in CPerl (see
also `cperl-electric-parens-mark' and `cperl-electric-parens'),
setting `cperl-electric-keywords' enables electric expansion of
control structures in CPerl. `cperl-electric-linefeed' governs which
one of two linefeed behavior is preferable. You can enable all these
options simultaneously (recommended mode of use) by setting
`cperl-hairy' to t. In this case you can switch separate options off
by setting them to `null'. Note that one may undo the extra whitespace
inserted by semis and braces in `auto-newline'-mode by consequent
\\[cperl-electric-backspace].

If your site has perl5 documentation in info format, you can use commands
\\[cperl-info-on-current-command] and \\[cperl-info-on-command] to access it.
These keys run commands `cperl-info-on-current-command' and
`cperl-info-on-command', which one is which is controlled by variable
`cperl-info-on-command-no-prompt' (in turn affected by `cperl-hairy').

Variables `cperl-pod-here-scan', `cperl-pod-here-fontify',
`cperl-pod-face', `cperl-pod-head-face' control processing of pod and
here-docs sections. In a future version results of scan may be used
for indentation too, currently they are used for highlighting only.

Variables controlling indentation style:
 `cperl-tab-always-indent'
    Non-nil means TAB in CPerl mode should always reindent the current line,
    regardless of where in the line point is when the TAB command is used.
 `cperl-auto-newline'
    Non-nil means automatically newline before and after braces,
    and after colons and semicolons, inserted in Perl code. The following
    \\[cperl-electric-backspace] will remove the inserted whitespace.
    Insertion after colons requires both this variable and 
    `cperl-auto-newline-after-colon' set. 
 `cperl-auto-newline-after-colon'
    Non-nil means automatically newline even after colons.
    Subject to `cperl-auto-newline' setting.
 `cperl-indent-level'
    Indentation of Perl statements within surrounding block.
    The surrounding block's indentation is the indentation
    of the line on which the open-brace appears.
 `cperl-continued-statement-offset'
    Extra indentation given to a substatement, such as the
    then-clause of an if, or body of a while, or just a statement continuation.
 `cperl-continued-brace-offset'
    Extra indentation given to a brace that starts a substatement.
    This is in addition to `cperl-continued-statement-offset'.
 `cperl-brace-offset'
    Extra indentation for line if it starts with an open brace.
 `cperl-brace-imaginary-offset'
    An open brace following other text is treated as if it the line started
    this far to the right of the actual line indentation.
 `cperl-label-offset'
    Extra indentation for line that is a label.
 `cperl-min-label-indent'
    Minimal indentation for line that is a label.

Settings for K&R and BSD indentation styles are
  `cperl-indent-level'                5    8
  `cperl-continued-statement-offset'  5    8
  `cperl-brace-offset'               -5   -8
  `cperl-label-offset'               -5   -8

If `cperl-indent-level' is 0, the statement after opening brace in column 0 is indented on `cperl-brace-offset'+`cperl-continued-statement-offset'.

Turning on CPerl mode calls the hooks in the variable `cperl-mode-hook'
with no args."
  (interactive)
  (kill-all-local-variables)
  ;;(if cperl-hairy
  ;;    (progn
  ;;	(cperl-set 'cperl-font-lock cperl-hairy)
  ;;	(cperl-set 'cperl-electric-lbrace-space cperl-hairy)
  ;;	(cperl-set 'cperl-electric-parens "{[(<")
  ;;	(cperl-set 'cperl-electric-keywords cperl-hairy)
  ;;	(cperl-set 'cperl-electric-linefeed cperl-hairy)))
  (use-local-map cperl-mode-map)
  (if (cperl-val 'cperl-electric-linefeed)
      (progn
	(local-set-key "\C-J" 'cperl-linefeed)
	(local-set-key "\C-C\C-J" 'newline-and-indent)))
  (if (cperl-val 'cperl-info-on-command-no-prompt)
      (progn
	(if (cperl-xemacs-p)
	    ;; don't clobber the backspace binding:
	    (local-set-key [(control h) f] 'cperl-info-on-current-command)
	  (local-set-key "\C-hf" 'cperl-info-on-current-command))
	(if (cperl-xemacs-p)
	    ;; don't clobber the backspace binding:
	    (local-set-key [(control c) (control h) f]
			   'cperl-info-on-command)
	  (local-set-key "\C-c\C-hf" 'cperl-info-on-command))))
  (setq major-mode 'perl-mode)
  (setq mode-name "CPerl")
  (if (not cperl-mode-abbrev-table)
      (let ((prev-a-c abbrevs-changed))
	(define-abbrev-table 'cperl-mode-abbrev-table '(
		("if" "if" cperl-electric-keyword 0)
		("elsif" "elsif" cperl-electric-keyword 0)
		("while" "while" cperl-electric-keyword 0)
		("until" "until" cperl-electric-keyword 0)
		("unless" "unless" cperl-electric-keyword 0)
		("else" "else" cperl-electric-else 0)
		("for" "for" cperl-electric-keyword 0)
		("foreach" "foreach" cperl-electric-keyword 0)
		("do" "do" cperl-electric-keyword 0)))
	(setq abbrevs-changed prev-a-c)))
  (setq local-abbrev-table cperl-mode-abbrev-table)
  (abbrev-mode (if (cperl-val 'cperl-electric-keywords) 1 0))
  (set-syntax-table cperl-mode-syntax-table)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat "^$\\|" page-delimiter))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (make-local-variable 'paragraph-ignore-fill-prefix)
  (setq paragraph-ignore-fill-prefix t)
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'cperl-indent-line)
  (make-local-variable 'require-final-newline)
  (setq require-final-newline t)
  (make-local-variable 'comment-start)
  (setq comment-start "# ")
  (make-local-variable 'comment-end)
  (setq comment-end "")
  (make-local-variable 'comment-column)
  (setq comment-column cperl-comment-column)
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "#+ *")
  (make-local-variable 'defun-prompt-regexp)
  (setq defun-prompt-regexp "^[ \t]*sub[ \t]+\\([^ \t\n{;]+\\)[ \t]*")
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'cperl-comment-indent)
  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
  (make-local-variable 'indent-region-function)
  (setq indent-region-function 'cperl-indent-region)
  ;;(setq auto-fill-function 'cperl-do-auto-fill) ; Need to switch on and off!
  (make-local-variable 'imenu-create-index-function)
  (setq imenu-create-index-function
	(function imenu-example--create-perl-index))
  (make-local-variable 'imenu-sort-function)
  (setq imenu-sort-function nil)
  (make-local-variable 'vc-header-alist)
  (setq vc-header-alist cperl-vc-header-alist)
  (make-local-variable 'font-lock-defaults)
  (setq	font-lock-defaults
	(if (string< emacs-version "19.30")
	    '(perl-font-lock-keywords-2)
	  '((perl-font-lock-keywords
	     perl-font-lock-keywords-1
	     perl-font-lock-keywords-2))))
  (or (fboundp 'cperl-old-auto-fill-mode)
      (progn
	(fset 'cperl-old-auto-fill-mode (symbol-function 'auto-fill-mode))
	(defun auto-fill-mode (&optional arg)
	  (interactive "P")
	  (cperl-old-auto-fill-mode arg)
	  (and auto-fill-function (eq major-mode 'perl-mode)
	       (setq auto-fill-function 'cperl-do-auto-fill)))))
  (if (cperl-enable-font-lock)
      (if (cperl-val 'cperl-font-lock) 
	  (progn (or cperl-faces-init (cperl-init-faces))
		 (font-lock-mode 1))))
  (and (boundp 'msb-menu-cond)
       (not cperl-msb-fixed)
       (cperl-msb-fix))
  (run-hooks 'cperl-mode-hook)
  ;; After hooks since fontification will break this
  (if cperl-pod-here-scan (cperl-find-pods-heres)))

;; Fix for perldb - make default reasonable
(defun cperl-db ()
  (interactive)
  (require 'gud)
  (perldb (read-from-minibuffer "Run perldb (like this): "
				(if (consp gud-perldb-history)
				    (car gud-perldb-history)
				  (concat "perl " ;;(file-name-nondirectory
						   ;; I have problems
						   ;; in OS/2
						   ;; otherwise
						   (buffer-file-name)))
				nil nil
				'(gud-perldb-history . 1))))

;; Fix for msb.el
(defvar cperl-msb-fixed nil)

(defun cperl-msb-fix ()
  ;; Adds perl files to msb menu, supposes that msb is already loaded
  (setq cperl-msb-fixed t)
  (let* ((l (length msb-menu-cond))
	 (last (nth (1- l) msb-menu-cond))
	 (precdr (nthcdr (- l 2) msb-menu-cond)) ; cdr of this is last
	 (handle (1- (nth 1 last))))
    (setcdr precdr (list
		    (list
		     '(eq major-mode 'perl-mode)
		     handle
		     "Perl Files (%d)")
		    last))))

;; This is used by indent-for-comment
;; to decide how much to indent a comment in CPerl code
;; based on its context. Do fallback if comment is found wrong.

(defvar cperl-wrong-comment)

(defun cperl-comment-indent ()
  (let ((p (point)) (c (current-column)) was)
    (if (looking-at "^#") 0		; Existing comment at bol stays there.
      ;; Wrong comment found
      (save-excursion
	(setq was (cperl-to-comment-or-eol))
	(if (= (point) p)
	    (progn
	      (skip-chars-backward " \t")
	      (max (1+ (current-column)) ; Else indent at comment column
		   comment-column))
	  (if was nil
	    (insert comment-start)
	    (backward-char (length comment-start)))
	  (setq cperl-wrong-comment t)
	  (indent-to comment-column 1)	; Indent minimum 1
	  c)))))			; except leave at least one space.

;;;(defun cperl-comment-indent-fallback ()
;;;  "Is called if the standard comment-search procedure fails.
;;;Point is at start of real comment."
;;;  (let ((c (current-column)) target cnt prevc)
;;;    (if (= c comment-column) nil
;;;      (setq cnt (skip-chars-backward "[ \t]"))
;;;      (setq target (max (1+ (setq prevc 
;;;			     (current-column))) ; Else indent at comment column
;;;		   comment-column))
;;;      (if (= c comment-column) nil
;;;	(delete-backward-char cnt)
;;;	(while (< prevc target)
;;;	  (insert "\t")
;;;	  (setq prevc (current-column)))
;;;	(if (> prevc target) (progn (delete-char -1) (setq prevc (current-column))))
;;;	(while (< prevc target)
;;;	  (insert " ")
;;;	  (setq prevc (current-column)))))))

(defun cperl-indent-for-comment ()
  "Substite for `indent-for-comment' in CPerl."
  (interactive)
  (let (cperl-wrong-comment)
    (indent-for-comment)
    (if cperl-wrong-comment
	(progn (cperl-to-comment-or-eol)
	       (forward-char (length comment-start))))))

(defun cperl-comment-region (b e arg)
  "Comment or uncomment each line in the region in CPerl mode.
See `comment-region'."
  (interactive "r\np")
  (let ((comment-start "#"))
    (comment-region b e arg)))

(defun cperl-uncomment-region (b e arg)
  "Uncomment or comment each line in the region in CPerl mode.
See `comment-region'."
  (interactive "r\np")
  (let ((comment-start "#"))
    (comment-region b e (- arg))))

(defun cperl-electric-brace (arg &optional only-before)
  "Insert character and correct line's indentation.
If ONLY-BEFORE and `cperl-auto-newline', will insert newline before the
place (even in empty line), but not after. If after \")\" and the inserted
char is \"{\", insert extra newline before only if 
`cperl-extra-newline-before-brace'."
  (interactive "P")
  (let (insertpos)
    (if (and (not arg)			; No args, end (of empty line or auto)
	     (eolp)
	     (or (and (null only-before)
		      (save-excursion
			(skip-chars-backward " \t")
			(bolp)))
		 (and (eq last-command-char ?\{) ; Do not insert newline
		      ;; if after ")" and `cperl-extra-newline-before-brace'
		      ;; is nil, do not insert extra newline.
		      (not cperl-extra-newline-before-brace)
		      (save-excursion
			(skip-chars-backward " \t")
			(eq (preceding-char) ?\))))
		 (if cperl-auto-newline 
		     (progn (cperl-indent-line) (newline) t) nil)))
	(progn
	  (if cperl-auto-newline
	      (setq insertpos (point)))
	  (insert last-command-char)
	  (cperl-indent-line)
	  (if (and cperl-auto-newline (null only-before))
	      (progn
		(newline)
		(cperl-indent-line)))
	  (save-excursion
	    (if insertpos (progn (goto-char insertpos)
				 (search-forward (make-string 
						  1 last-command-char))
				 (setq insertpos (1- (point)))))
	    (delete-char -1))))
    (if insertpos
	(save-excursion
	  (goto-char insertpos)
	  (self-insert-command (prefix-numeric-value arg)))
      (self-insert-command (prefix-numeric-value arg)))))

(defun cperl-electric-lbrace (arg)
  "Insert character, correct line's indentation, correct quoting by space."
  (interactive "P")
  (let (pos after 
	    (cperl-auto-newline cperl-auto-newline)
	    (other-end (if (and cperl-electric-parens-mark
				(cperl-mark-active)
				(> (mark) (point)))
			   (save-excursion
			     (goto-char (mark))
			     (point-marker)) 
			 nil)))
    (and (cperl-val 'cperl-electric-lbrace-space)
	 (eq (preceding-char) ?$)
	 (save-excursion
	   (skip-chars-backward "$")
	   (looking-at "\\(\\$\\$\\)*\\$\\([^\\$]\\|$\\)"))
	 (insert ? ))
    (if (cperl-after-expr-p nil "{};)") nil (setq cperl-auto-newline nil))
    (cperl-electric-brace arg)
    (and (cperl-val 'cperl-electric-parens)
	 (eq last-command-char ?{)
	 (memq last-command-char 
	       (append cperl-electric-parens-string nil))
	 (or (if other-end (goto-char (marker-position other-end)))
	     t)
	 (setq last-command-char ?} pos (point))
	 (progn (cperl-electric-brace arg t)
		(goto-char pos)))))

(defun cperl-electric-paren (arg)
  "Insert a matching pair of parentheses."
  (interactive "P")
  (let ((beg (save-excursion (beginning-of-line) (point)))
	(other-end (if (and cperl-electric-parens-mark
			    (cperl-mark-active) 
			    (> (mark) (point)))
			   (save-excursion
			     (goto-char (mark))
			     (point-marker)) 
		     nil)))
    (if (and (cperl-val 'cperl-electric-parens)
	     (memq last-command-char
		   (append cperl-electric-parens-string nil))
	     (>= (save-excursion (cperl-to-comment-or-eol) (point)) (point))
	     ;;(not (save-excursion (search-backward "#" beg t)))
	     (if (eq last-command-char ?<)
		 (cperl-after-expr-p nil "{};(,:=")
	       1))
	(progn
	  (insert last-command-char)
	  (if other-end (goto-char (marker-position other-end)))
	  (insert (cdr (assoc last-command-char '((?{ .?})
						  (?[ . ?])
						  (?( . ?))
						  (?< . ?>)))))
	  (forward-char -1))
      (insert last-command-char)
      )))

(defun cperl-electric-keyword ()
  "Insert a construction appropriate after a keyword."
  (let ((beg (save-excursion (beginning-of-line) (point))) 
	(dollar (eq (preceding-char) ?$)))
    (and (save-excursion
	   (backward-sexp 1)
	   (cperl-after-expr-p nil "{};:"))
	 (save-excursion 
	   (not 
	    (re-search-backward
	     "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
	     beg t)))
	 (save-excursion (or (not (re-search-backward "^=" nil t))
			     (looking-at "=cut")))
	 (progn
	   (and dollar (insert " $"))
	   (cperl-indent-line)
	   ;;(insert " () {\n}")
 	   (cond
 	    (cperl-extra-newline-before-brace
 	     (insert " ()\n")
 	     (insert "{")
 	     (cperl-indent-line)
 	     (insert "\n")
 	     (cperl-indent-line)
 	     (insert "\n}"))
 	    (t
 	     (insert " () {\n}"))
 	    )
	   (or (looking-at "[ \t]\\|$") (insert " "))
	   (cperl-indent-line)
	   (if dollar (progn (search-backward "$")
			     (forward-char 1))
	     (search-backward ")"))
	   (cperl-putback-char del-back-ch)))))

(defun cperl-electric-else ()
  "Insert a construction appropriate after a keyword."
  (let ((beg (save-excursion (beginning-of-line) (point))))
    (and (save-excursion
	   (backward-sexp 1)
	   (cperl-after-expr-p nil "{};:"))
	 (save-excursion 
	   (not 
	    (re-search-backward
	     "[#\"'`]\\|\\<q\\(\\|[wqx]\\)\\>"
	     beg t)))
	 (save-excursion (or (not (re-search-backward "^=" nil t))
			     (looking-at "=cut")))
	 (progn
	   (cperl-indent-line)
	   ;;(insert " {\n\n}")
 	   (cond
 	    (cperl-extra-newline-before-brace
 	     (insert "\n")
 	     (insert "{")
 	     (cperl-indent-line)
 	     (insert "\n\n}"))
 	    (t
 	     (insert " {\n\n}"))
 	    )
	   (or (looking-at "[ \t]\\|$") (insert " "))
	   (cperl-indent-line)
	   (forward-line -1)
	   (cperl-indent-line)
	   (cperl-putback-char del-back-ch)))))

(defun cperl-linefeed ()
  "Go to end of line, open a new line and indent appropriately."
  (interactive)
  (let ((beg (save-excursion (beginning-of-line) (point)))
	(end (save-excursion (end-of-line) (point)))
	(pos (point)) start)
    (if (and				; Check if we need to split:
					; i.e., on a boundary and inside "{...}" 
	 (save-excursion (cperl-to-comment-or-eol)
	   (>= (point) pos))		; Not in a comment
	 (or (save-excursion
	       (skip-chars-backward " \t" beg)
	       (forward-char -1)
	       (looking-at "[;{]"))     ; After { or ; + spaces
	     (looking-at "[ \t]*}")	; Before }
	     (re-search-forward "\\=[ \t]*;" end t)) ; Before spaces + ;
	 (save-excursion
	   (and
	    (eq (car (parse-partial-sexp pos end -1)) -1) 
					; Leave the level of parens
	    (looking-at "[,; \t]*\\($\\|#\\)") ; Comma to allow anon subr
					; Are at end
	    (progn
	      (backward-sexp 1)
	      (setq start (point-marker))
	      (<= start pos)))))	; Redundant? Are after the
					; start of parens group.
	(progn
	  (skip-chars-backward " \t")
	  (or (memq (preceding-char) (append ";{" nil))
	      (insert ";"))
	  (insert "\n")
	  (forward-line -1)
	  (cperl-indent-line)
	  (goto-char start)
	  (or (looking-at "{[ \t]*$")	; If there is a statement
					; before, move it to separate line
	      (progn
		(forward-char 1)
		(insert "\n")
		(cperl-indent-line)))
	  (forward-line 1)		; We are on the target line
	  (cperl-indent-line)
	  (beginning-of-line)
	  (or (looking-at "[ \t]*}[,; \t]*$") ; If there is a statement
					    ; after, move it to separate line
	      (progn
		(end-of-line)
		(search-backward "}" beg)
		(skip-chars-backward " \t")
		(or (memq (preceding-char) (append ";{" nil))
		    (insert ";"))
		(insert "\n")
		(cperl-indent-line)
		(forward-line -1)))
	  (forward-line -1)		; We are on the line before target 
	  (end-of-line)
	  (newline-and-indent))
      (end-of-line)			; else
      (cond
       ((and (looking-at "\n[ \t]*{$")
	     (save-excursion
	       (skip-chars-backward " \t")
	       (eq (preceding-char) ?\)))) ; Probably if () {} group
					   ; with an extra newline.
	(forward-line 2)
	(cperl-indent-line))
       ((looking-at "\n[ \t]*$")	; Next line is empty - use it.
        (forward-line 1)
	(cperl-indent-line))
       (t
	(newline-and-indent))))))

(defun cperl-electric-semi (arg)
  "Insert character and correct line's indentation."
  (interactive "P")
  (if cperl-auto-newline
      (cperl-electric-terminator arg)
    (self-insert-command (prefix-numeric-value arg))))

(defun cperl-electric-terminator (arg)
  "Insert character and correct line's indentation."
  (interactive "P")
  (let (insertpos (end (point)) 
		  (auto (and cperl-auto-newline
			     (or (not (eq last-command-char ?:))
				 cperl-auto-newline-after-colon))))
    (if (and ;;(not arg) 
	     (eolp)
	     (not (save-excursion
		    (beginning-of-line)
		    (skip-chars-forward " \t")
		    (or
		     ;; Ignore in comment lines
		     (= (following-char) ?#)
		     ;; Colon is special only after a label
		     ;; So quickly rule out most other uses of colon
		     ;; and do no indentation for them.
		     (and (eq last-command-char ?:)
			  (save-excursion
			    (forward-word 1)
			    (skip-chars-forward " \t")
			    (and (< (point) end)
				 (progn (goto-char (- end 1))
					(not (looking-at ":"))))))
		     (progn
		       (beginning-of-defun)
		       (let ((pps (parse-partial-sexp (point) end)))
			 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
	(progn
	  (insert last-command-char)
	  ;;(forward-char -1)
	  (if auto (setq insertpos (point-marker)))
	  ;;(forward-char 1)
	  (cperl-indent-line)
	  (if auto
	      (progn
		(newline)
		(cperl-indent-line)))
;;	  (save-excursion
;;	    (if insertpos (progn (goto-char (marker-position insertpos))
;;				 (search-forward (make-string 
;;						  1 last-command-char))
;;				 (setq insertpos (1- (point)))))
;;	    (delete-char -1))))
	  (save-excursion
	    (if insertpos (goto-char (1- (marker-position insertpos)))
	      (forward-char -1))
	    (delete-char 1))))
    (if insertpos
	(save-excursion
	  (goto-char insertpos)
	  (self-insert-command (prefix-numeric-value arg)))
      (self-insert-command (prefix-numeric-value arg)))))

(defun cperl-electric-backspace (arg)
  "Backspace-untabify, or remove the whitespace inserted by an electric key."
  (interactive "p")
  (if (and cperl-auto-newline 
	   (memq last-command '(cperl-electric-semi 
				cperl-electric-terminator
				cperl-electric-lbrace))
	   (memq (preceding-char) '(?  ?\t ?\n)))
      (let (p)
	(if (eq last-command 'cperl-electric-lbrace) 
	    (skip-chars-forward " \t\n"))
	(setq p (point))
	(skip-chars-backward " \t\n")
	(delete-region (point) p))
    (backward-delete-char-untabify arg)))

(defun cperl-inside-parens-p ()
  (condition-case ()
      (save-excursion
	(save-restriction
	  (narrow-to-region (point)
			    (progn (beginning-of-defun) (point)))
	  (goto-char (point-max))
	  (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
    (error nil)))

(defun cperl-indent-command (&optional whole-exp)
  "Indent current line as Perl code, or in some cases insert a tab character.
If `cperl-tab-always-indent' is non-nil (the default), always indent current line.
Otherwise, indent the current line only if point is at the left margin
or in the line's indentation; otherwise insert a tab.

A numeric argument, regardless of its value,
means indent rigidly all the lines of the expression starting after point
so that this line becomes properly indented.
The relative indentation among the lines of the expression are preserved."
  (interactive "P")
  (if whole-exp
      ;; If arg, always indent this line as Perl
      ;; and shift remaining lines of expression the same amount.
      (let ((shift-amt (cperl-indent-line))
	    beg end)
	(save-excursion
	  (if cperl-tab-always-indent
	      (beginning-of-line))
	  (setq beg (point))
	  (forward-sexp 1)
	  (setq end (point))
	  (goto-char beg)
	  (forward-line 1)
	  (setq beg (point)))
	(if (> end beg)
	    (indent-code-rigidly beg end shift-amt "#")))
    (if (and (not cperl-tab-always-indent)
	     (save-excursion
	       (skip-chars-backward " \t")
	       (not (bolp))))
	(insert-tab)
      (cperl-indent-line))))

(defun cperl-indent-line (&optional symbol)
  "Indent current line as Perl code.
Return the amount the indentation changed by."
  (let (indent
	beg shift-amt
	(case-fold-search nil)
	(pos (- (point-max) (point))))
    (setq indent (cperl-calculate-indent nil symbol))
    (beginning-of-line)
    (setq beg (point))
    (cond ((eq indent nil)
	   (setq indent (current-indentation)))
	  ;;((eq indent t)    ; Never?
	  ;; (setq indent (cperl-calculate-indent-within-comment)))
	  ;;((looking-at "[ \t]*#")
	  ;; (setq indent 0))
	  (t
	   (skip-chars-forward " \t")
	   (if (listp indent) (setq indent (car indent)))
	   (cond ((looking-at "[A-Za-z]+:[^:]")
		  (and (> indent 0)
		       (setq indent (max cperl-min-label-indent
					 (+ indent cperl-label-offset)))))
		 ((= (following-char) ?})
		  (setq indent (- indent cperl-indent-level)))
		 ((memq (following-char) '(?\) ?\])) ; To line up with opening paren.
		  (setq indent (+ indent cperl-close-paren-offset)))
		 ((= (following-char) ?{)
		  (setq indent (+ indent cperl-brace-offset))))))
    (skip-chars-forward " \t")
    (setq shift-amt (- indent (current-column)))
    (if (zerop shift-amt)
	(if (> (- (point-max) pos) (point))
	    (goto-char (- (point-max) pos)))
      (delete-region beg (point))
      (indent-to indent)
      ;; If initial point was within line's indentation,
      ;; position after the indentation.  Else stay at same point in text.
      (if (> (- (point-max) pos) (point))
	  (goto-char (- (point-max) pos))))
    shift-amt))

(defun cperl-after-label ()
  ;; Returns true if the point is after label. Does not do save-excursion.
  (and (eq (preceding-char) ?:)
       (memq (char-syntax (char-after (- (point) 2)))
	     '(?w ?_))
       (progn
	 (backward-sexp)
	 (looking-at "[a-zA-Z_][a-zA-Z0-9_]*:[^:]"))))

(defun cperl-get-state (&optional parse-start start-state)
  ;; returns list (START STATE DEPTH PRESTART), START is a good place
  ;; to start parsing, STATE is what is returned by
  ;; `parse-partial-sexp'. DEPTH is true is we are immediately after
  ;; end of block which contains START. PRESTART is the position
  ;; basing on which START was found.
  (save-excursion
    (let ((start-point (point)) depth state start prestart)
      (if parse-start
	  (goto-char parse-start)
	(beginning-of-defun))
      (setq prestart (point))
      (if start-state nil
	;; Try to go out, if sub is not on the outermost level
	(while (< (point) start-point)
	  (setq start (point) parse-start start depth nil
		state (parse-partial-sexp start start-point -1))
	  (if (> (car state) -1) nil
	    ;; The current line could start like }}}, so the indentation
	    ;; corresponds to a different level than what we reached
	    (setq depth t)
	    (beginning-of-line 2)))	; Go to the next line.
	(if start (goto-char start)))	; Not at the start of file
      (setq start (point))
      (if (< start start-point) (setq parse-start start))
      (or state (setq state (parse-partial-sexp start start-point -1 nil start-state)))
      (list start state depth prestart))))

(defun cperl-block-p ()			; Do not C-M-q ! One string contains ";" !
  ;; Positions is before ?\{. Checks whether it starts a block.
  ;; No save-excursion!
  (cperl-backward-to-noncomment (point-min))
  ;;(skip-chars-backward " \t\n\f")
  (or (memq (preceding-char) (append ";){}$@&%\C-@" nil)) ; Or label! \C-@ at bobp
					; Label may be mixed up with `$blah :'
      (save-excursion (cperl-after-label))
      (and (memq (char-syntax (preceding-char)) '(?w ?_))
	   (progn
	     (backward-sexp)
	     ;; Need take into account `bless', `return', `tr',...
	     (or (and (looking-at "[a-zA-Z0-9_:]+[ \t\n\f]*[{#]") ; Method call syntax
		      (not (looking-at "\\(bless\\|return\\|qw\\|tr\\|[smy]\\)\\>")))
		 (progn
		   (skip-chars-backward " \t\n\f")
		   (and (memq (char-syntax (preceding-char)) '(?w ?_))
			(progn
			  (backward-sexp)
			  (looking-at 
			   "sub[ \t]+[a-zA-Z0-9_:]+[ \t\n\f]*[#{]")))))))))

(defun cperl-calculate-indent (&optional parse-start symbol)
  "Return appropriate indentation for current line as Perl code.
In usual case returns an integer: the column to indent to.
Returns nil if line starts inside a string, t if in a comment."
  (save-excursion
    (if (memq (get-text-property (point) 'syntax-type) '(pod here-doc)) nil
      (beginning-of-line)
      (let* ((indent-point (point))
	     (case-fold-search nil)
	     (s-s (cperl-get-state))
	     (start (nth 0 s-s))
	     (state (nth 1 s-s))
	     (containing-sexp (car (cdr state)))
	     (char-after (save-excursion
			   (skip-chars-forward " \t")
			   (following-char)))
	     (start-indent (save-excursion
			     (goto-char start)
			     (- (current-indentation)
				(if (nth 2 s-s) cperl-indent-level 0))))
	     old-indent)
	;;      (or parse-start (null symbol)
	;;	  (setq parse-start (symbol-value symbol) 
	;;		start-indent (nth 2 parse-start) 
	;;		parse-start (car parse-start)))
	;;      (if parse-start
	;;	  (goto-char parse-start)
	;;	(beginning-of-defun))
	;;      ;; Try to go out
	;;      (while (< (point) indent-point)
	;;	(setq start (point) parse-start start moved nil
	;;	      state (parse-partial-sexp start indent-point -1))
	;;	(if (> (car state) -1) nil
	;;	  ;; The current line could start like }}}, so the indentation
	;;	  ;; corresponds to a different level than what we reached
	;;	  (setq moved t)
	;;	  (beginning-of-line 2)))	; Go to the next line.
	;;      (if start				; Not at the start of file
	;;	  (progn
	;;	    (goto-char start)
	;;	    (setq start-indent (current-indentation))
	;;	    (if moved			; Should correct...
	;;		(setq start-indent (- start-indent cperl-indent-level))))
	;;	(setq start-indent 0))
	;;      (if (< (point) indent-point) (setq parse-start (point)))
	;;      (or state (setq state (parse-partial-sexp 
	;;			     (point) indent-point -1 nil start-state)))
	;;      (setq containing-sexp 
	;;	    (or (car (cdr state)) 
	;;		(and (>= (nth 6 state) 0) old-containing-sexp))
	;;	    old-containing-sexp nil start-state nil)
;;;;      (while (< (point) indent-point)
;;;;	(setq parse-start (point))
;;;;	(setq state (parse-partial-sexp (point) indent-point -1 nil start-state))
;;;;	(setq containing-sexp 
;;;;	      (or (car (cdr state)) 
;;;;		  (and (>= (nth 6 state) 0) old-containing-sexp))
;;;;	      old-containing-sexp nil start-state nil))
	;;      (if symbol (set symbol (list indent-point state start-indent)))
	;;      (goto-char indent-point)
	(cond ((or (nth 3 state) (nth 4 state))
	       ;; return nil or t if should not change this line
	       (nth 4 state))
	      ((null containing-sexp)
	       ;; Line is at top level.  May be data or function definition,
	       ;; or may be function argument declaration.
	       ;; Indent like the previous top level line
	       ;; unless that ends in a closeparen without semicolon,
	       ;; in which case this line is the first argument decl.
	       (skip-chars-forward " \t")
	       (+ start-indent
		  (if (= (following-char) ?{) cperl-continued-brace-offset 0)
		  (progn
		    (cperl-backward-to-noncomment (or parse-start (point-min)))
		    ;;(skip-chars-backward " \t\f\n")
		    ;; Look at previous line that's at column 0
		    ;; to determine whether we are in top-level decls
		    ;; or function's arg decls.  Set basic-indent accordingly.
		    ;; Now add a little if this is a continuation line.
		    (if (or (bobp)
			    (memq (preceding-char) (append " ;}" nil)) ; Was ?\)
			    (memq char-after (append ")]}" nil))) 
			0
		      cperl-continued-statement-offset))))
	      ((/= (char-after containing-sexp) ?{)
	       ;; line is expression, not statement:
	       ;; indent to just after the surrounding open,
	       ;; skip blanks if we do not close the expression.
	       (goto-char (1+ containing-sexp))
	       (or (memq char-after (append ")]}" nil))
		   (looking-at "[ \t]*\\(#\\|$\\)")
		   (skip-chars-forward " \t"))
	       (current-column))
	      ((progn
		 ;; Containing-expr starts with \{. Check whether it is a hash.
		 (goto-char containing-sexp)
		 (not (cperl-block-p)))
	       (goto-char (1+ containing-sexp))
	       (or (eq char-after ?\})
		   (looking-at "[ \t]*\\(#\\|$\\)")
		   (skip-chars-forward " \t"))
	       (+ (current-column)	; Correct indentation of trailing ?\}
		  (if (eq char-after ?\}) (+ cperl-indent-level
					     cperl-close-paren-offset) 
		    0)))
	      (t
	       ;; Statement level.  Is it a continuation or a new statement?
	       ;; Find previous non-comment character.
	       (goto-char indent-point)
	       (cperl-backward-to-noncomment containing-sexp)
	       ;; Back up over label lines, since they don't
	       ;; affect whether our line is a continuation.
	       (while (or (eq (preceding-char) ?\,)
			  (and (eq (preceding-char) ?:)
			       (or;;(eq (char-after (- (point) 2)) ?\') ; ????
				(memq (char-syntax (char-after (- (point) 2)))
				      '(?w ?_)))))
		 (if (eq (preceding-char) ?\,)
		     ;; Will go to beginning of line, essentially.
		     ;; Will ignore embedded sexpr XXXX.
		     (cperl-backward-to-start-of-continued-exp containing-sexp))
		 (beginning-of-line)
		 (cperl-backward-to-noncomment containing-sexp))
	       ;; Now we get the answer.
	       (if (not (memq (preceding-char) (append ", ;}{" '(nil)))) ; Was ?\,
		   ;; This line is continuation of preceding line's statement;
		   ;; indent  `cperl-continued-statement-offset'  more than the
		   ;; previous line of the statement.
		   (progn
		     (cperl-backward-to-start-of-continued-exp containing-sexp)
		     (+ (if (memq char-after (append "}])" nil))
			    0		; Closing parenth
			  cperl-continued-statement-offset)
			(current-column)
			(if (eq char-after ?\{)
			    cperl-continued-brace-offset 0)))
		 ;; This line starts a new statement.
		 ;; Position following last unclosed open.
		 (goto-char containing-sexp)
		 ;; Is line first statement after an open-brace?
		 (or
		  ;; If no, find that first statement and indent like
		  ;; it.  If the first statement begins with label, do
		  ;; not belive when the indentation of the label is too
		  ;; small.
		  (save-excursion
		    (forward-char 1)
		    (setq old-indent (current-indentation))
		    (let ((colon-line-end 0))
		      (while (progn (skip-chars-forward " \t\n")
				    (looking-at "#\\|[a-zA-Z0-9_$]*:[^:]"))
			;; Skip over comments and labels following openbrace.
			(cond ((= (following-char) ?\#)
			       (forward-line 1))
			      ;; label:
			      (t
			       (save-excursion (end-of-line)
					       (setq colon-line-end (point)))
			       (search-forward ":"))))
		      ;; The first following code counts
		      ;; if it is before the line we want to indent.
		      (and (< (point) indent-point)
			   (if (> colon-line-end (point)) ; After label
			       (if (> (current-indentation) 
				      cperl-min-label-indent)
				   (- (current-indentation) cperl-label-offset)
				 ;; Do not belive: `max' is involved
				 (+ old-indent cperl-indent-level))
			     (current-column)))))
		  ;; If no previous statement,
		  ;; indent it relative to line brace is on.
		  ;; For open brace in column zero, don't let statement
		  ;; start there too.  If cperl-indent-level is zero,
		  ;; use cperl-brace-offset + cperl-continued-statement-offset instead.
		  ;; For open-braces not the first thing in a line,
		  ;; add in cperl-brace-imaginary-offset.

		  ;; If first thing on a line:  ?????
		  (+ (if (and (bolp) (zerop cperl-indent-level))
			 (+ cperl-brace-offset cperl-continued-statement-offset)
		       cperl-indent-level)
		     ;; Move back over whitespace before the openbrace.
		     ;; If openbrace is not first nonwhite thing on the line,
		     ;; add the cperl-brace-imaginary-offset.
		     (progn (skip-chars-backward " \t")
			    (if (bolp) 0 cperl-brace-imaginary-offset))
		     ;; If the openbrace is preceded by a parenthesized exp,
		     ;; move to the beginning of that;
		     ;; possibly a different line
		     (progn
		       (if (eq (preceding-char) ?\))
			   (forward-sexp -1))
		       ;; In the case it starts a subroutine, indent with
		       ;; respect to `sub', not with respect to the the
		       ;; first thing on the line, say in the case of
		       ;; anonymous sub in a hash.
		       ;;
		       (skip-chars-backward " \t")
		       (if (and (eq (preceding-char) ?b)
				(progn
				  (forward-word -1)
				  (looking-at "sub\\>"))
				(setq old-indent 
				      (nth 1 
					   (parse-partial-sexp 
					    (save-excursion (beginning-of-line) (point)) 
					    (point)))))
			   (progn (goto-char (1+ old-indent))
				  (skip-chars-forward " \t")
				  (current-column))
			 ;; Get initial indentation of the line we are on.
			 ;; If line starts with label, calculate label indentation
			 (if (save-excursion
			       (beginning-of-line)
			       (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
			     (if (> (current-indentation) cperl-min-label-indent)
				 (- (current-indentation) cperl-label-offset)
			       (cperl-calculate-indent 
				(if (and parse-start (<= parse-start (point)))
				    parse-start)))
			   (current-indentation)))))))))))))

(defvar cperl-indent-alist
  '((string nil)
    (comment nil)
    (toplevel 0)
    (toplevel-after-parenth 2)
    (toplevel-continued 2)
    (expression 1))
  "Alist of indentation rules for CPerl mode.
The values mean:
  nil: do not indent;
  number: add this amount of indentation.")

(defun cperl-where-am-i (&optional parse-start start-state)
  ;; Unfinished
  "Return a list of lists ((TYPE POS)...) of good points before the point.
POS may be nil if it is hard to find, say, when TYPE is `string' or `comment'."
  (save-excursion
    (let* ((start-point (point))
	   (s-s (cperl-get-state))
	   (start (nth 0 s-s))
	   (state (nth 1 s-s))
	   (prestart (nth 3 s-s))
	   (containing-sexp (car (cdr state)))
	   (case-fold-search nil)
	   (res (list (list 'parse-start start) (list 'parse-prestart prestart))))
      (cond ((nth 3 state)		; In string
	     (setq res (cons (list 'string nil (nth 3 state)) res))) ; What started string
	    ((nth 4 state)		; In comment
	     (setq res (cons '(comment) res)))
	    ((null containing-sexp)
	     ;; Line is at top level.  
	     ;; Indent like the previous top level line
	     ;; unless that ends in a closeparen without semicolon,
	     ;; in which case this line is the first argument decl.
	     (cperl-backward-to-noncomment (or parse-start (point-min)))
	     ;;(skip-chars-backward " \t\f\n")
	     (cond
	      ((or (bobp)
		   (memq (preceding-char) (append ";}" nil)))
	       (setq res (cons (list 'toplevel start) res)))
	      ((eq (preceding-char) ?\) )
	       (setq res (cons (list 'toplevel-after-parenth start) res)))
	      (t 
	       (setq res (cons (list 'toplevel-continued start) res)))))
	    ((/= (char-after containing-sexp) ?{)
	     ;; line is expression, not statement:
	     ;; indent to just after the surrounding open.
	     ;; skip blanks if we do not close the expression.
	     (setq res (cons (list 'expression-blanks
				   (progn
				     (goto-char (1+ containing-sexp))
				     (or (looking-at "[ \t]*\\(#\\|$\\)")
					 (skip-chars-forward " \t"))
				     (point)))
			     (cons (list 'expression containing-sexp) res))))
	    ((progn
	      ;; Containing-expr starts with \{. Check whether it is a hash.
	      (goto-char containing-sexp)
	      (not (cperl-block-p)))
	     (setq res (cons (list 'expression-blanks
				   (progn
				     (goto-char (1+ containing-sexp))
				     (or (looking-at "[ \t]*\\(#\\|$\\)")
					 (skip-chars-forward " \t"))
				     (point)))
			     (cons (list 'expression containing-sexp) res))))
	    (t
	     ;; Statement level.
	     (setq res (cons (list 'in-block containing-sexp) res))
	     ;; Is it a continuation or a new statement?
	     ;; Find previous non-comment character.
	     (cperl-backward-to-noncomment containing-sexp)
	     ;; Back up over label lines, since they don't
	     ;; affect whether our line is a continuation.
	     ;; Back up comma-delimited lines too ?????
	     (while (or (eq (preceding-char) ?\,)
			(save-excursion (cperl-after-label)))
	       (if (eq (preceding-char) ?\,)
		   ;; Will go to beginning of line, essentially
		     ;; Will ignore embedded sexpr XXXX.
		   (cperl-backward-to-start-of-continued-exp containing-sexp))
	       (beginning-of-line)
	       (cperl-backward-to-noncomment containing-sexp))
	     ;; Now we get the answer.
	     (if (not (memq (preceding-char) (append ";}{" '(nil)))) ; Was ?\,
		 ;; This line is continuation of preceding line's statement.
		 (list (list 'statement-continued containing-sexp))
	       ;; This line starts a new statement.
	       ;; Position following last unclosed open.
	       (goto-char containing-sexp)
	       ;; Is line first statement after an open-brace?
	       (or
		;; If no, find that first statement and indent like
		;; it.  If the first statement begins with label, do
		;; not belive when the indentation of the label is too
		;; small.
		(save-excursion
		  (forward-char 1)
		  (let ((colon-line-end 0))
		    (while (progn (skip-chars-forward " \t\n" start-point)
				  (and (< (point) start-point)
				       (looking-at
					"#\\|[a-zA-Z_][a-zA-Z0-9_]*:[^:]")))
		      ;; Skip over comments and labels following openbrace.
		      (cond ((= (following-char) ?\#)
			     ;;(forward-line 1)
			     (end-of-line))
			    ;; label:
			    (t
			     (save-excursion (end-of-line)
					     (setq colon-line-end (point)))
			     (search-forward ":"))))
		    ;; Now at the point, after label, or at start 
		    ;; of first statement in the block.
		    (and (< (point) start-point)
			 (if (> colon-line-end (point)) 
			     ;; Before statement after label
			     (if (> (current-indentation) 
				    cperl-min-label-indent)
				 (list (list 'label-in-block (point)))
			       ;; Do not belive: `max' is involved
			       (list
				(list 'label-in-block-min-indent (point))))
			   ;; Before statement
			   (list 'statement-in-block (point))))))
		;; If no previous statement,
		;; indent it relative to line brace is on.
		;; For open brace in column zero, don't let statement
		;; start there too.  If cperl-indent-level is zero,
		;; use cperl-brace-offset + cperl-continued-statement-offset instead.
		;; For open-braces not the first thing in a line,
		;; add in cperl-brace-imaginary-offset.

		;; If first thing on a line:  ?????
		(+ (if (and (bolp) (zerop cperl-indent-level))
		       (+ cperl-brace-offset cperl-continued-statement-offset)
		     cperl-indent-level)
		   ;; Move back over whitespace before the openbrace.
		   ;; If openbrace is not first nonwhite thing on the line,
		   ;; add the cperl-brace-imaginary-offset.
		   (progn (skip-chars-backward " \t")
			  (if (bolp) 0 cperl-brace-imaginary-offset))
		   ;; If the openbrace is preceded by a parenthesized exp,
		   ;; move to the beginning of that;
		   ;; possibly a different line
		   (progn
		     (if (eq (preceding-char) ?\))
			 (forward-sexp -1))
		     ;; Get initial indentation of the line we are on.
		     ;; If line starts with label, calculate label indentation
		     (if (save-excursion
			   (beginning-of-line)
			   (looking-at "[ \t]*[a-zA-Z_][a-zA-Z_]*:[^:]"))
			 (if (> (current-indentation) cperl-min-label-indent)
			     (- (current-indentation) cperl-label-offset)
			   (cperl-calculate-indent 
			    (if (and parse-start (<= parse-start (point)))
				parse-start)))
		       (current-indentation))))))))
      res)))

(defun cperl-calculate-indent-within-comment ()
  "Return the indentation amount for line, assuming that
the current line is to be regarded as part of a block comment."
  (let (end star-start)
    (save-excursion
      (beginning-of-line)
      (skip-chars-forward " \t")
      (setq end (point))
      (and (= (following-char) ?#)
	   (forward-line -1)
	   (cperl-to-comment-or-eol)
	   (setq end (point)))
      (goto-char end)
      (current-column))))


(defun cperl-to-comment-or-eol ()
  "Goes to position before comment on the current line, or to end of line.
Returns true if comment is found."
  (let (state stop-in cpoint (lim (progn (end-of-line) (point))))
      (beginning-of-line)
      (if (re-search-forward "\\=[ \t]*\\(#\\|$\\)" lim t) 
	  (if (eq (preceding-char) ?\#) (progn (backward-char 1) t))
	;; Else
	(while (not stop-in)
	  (setq state (parse-partial-sexp (point) lim nil nil nil t))
					; stop at comment
	  ;; If fails (beginning-of-line inside sexp), then contains not-comment
	  ;; Do simplified processing
	  ;;(if (re-search-forward "[^$]#" lim 1)
	  ;;      (progn
	  ;;	(forward-char -1)
	  ;;	(skip-chars-backward " \t\n\f" lim))
	  ;;    (goto-char lim))		; No `#' at all
	  ;;)
	  (if (nth 4 state)		; After `#';
					; (nth 2 state) can be
					; beginning of m,s,qq and so
					; on
	      (if (nth 2 state)
		  (progn
		    (setq cpoint (point))
		    (goto-char (nth 2 state))
		    (cond
		     ((looking-at "\\(s\\|tr\\)\\>")
		      (or (re-search-forward
			   "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*"
			   lim 'move)
			  (setq stop-in t)))
		     ((looking-at "\\(m\\|q\\([qxw]\\)?\\)\\>")
		      (or (re-search-forward
			   "\\=\\w+[ \t]*#\\([^\n\\\\#]\\|\\\\[\\\\#]\\)*#"
			   lim 'move)
			  (setq stop-in t)))
		     (t			; It was fair comment
		      (setq stop-in t)	; Finish
		      (goto-char (1- cpoint)))))
		(setq stop-in t)	; Finish
		(forward-char -1))
	    (setq stop-in t))		; Finish
	  )
	(nth 4 state))))

(defun cperl-find-pods-heres (&optional min max)
  "Scans the buffer for POD sections and here-documents.
If `cperl-pod-here-fontify' is not-nil after evaluation, will fontify 
the sections using `cperl-pod-head-face', `cperl-pod-face', 
`cperl-here-face'."
  (interactive)
  (or min (setq min (point-min)))
  (or max (setq max (point-max)))
  (let (face head-face here-face b e bb tag qtag err b1 e1 argument
	     (cperl-pod-here-fontify (eval cperl-pod-here-fontify))
	     (case-fold-search nil) (inhibit-read-only t) (buffer-undo-list t)
	     (modified (buffer-modified-p))
	     (after-change-functions nil)
	     (search
	      (concat
	       "\\(\\`\n?\\|\n\n\\)=" 
	       "\\|"
	       ;; One extra () before this:
	       "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\3\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
	       "\\|"
	       ;; 1+5 extra () before this:
	       "^[ \t]*format[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$")))
    (unwind-protect
	(progn
	  (save-excursion
	    (message "Scanning for pods, formats and here-docs...")
	    (if cperl-pod-here-fontify
		;; We had evals here, do not know why...
		(setq face cperl-pod-face
		      head-face cperl-pod-head-face
		      here-face cperl-here-face))
	    (remove-text-properties min max '(syntax-type t))
	    ;; Need to remove face as well...
	    (goto-char min)
	    (while (re-search-forward search max t)
	      (cond 
	       ((match-beginning 1)	; POD section
		;;  "\\(\\`\n?\\|\n\n\\)=" 
		(if (looking-at "\n*cut\\>")
		    (progn
		      (message "=cut is not preceeded by a pod section")
		      (setq err (point)))
		  (beginning-of-line)
		
		  (setq b (point) bb b)
		  (or (re-search-forward "\n\n=cut\\>" max 'toend)
		      (message "Cannot find the end of a pod section"))
		  (beginning-of-line 3)
		  (setq e (point))
		  (put-text-property b e 'in-pod t)
		  (goto-char b)
		  (while (re-search-forward "\n\n[ \t]" e t)
		    (beginning-of-line)
		    (put-text-property b (point) 'syntax-type 'pod)
		    (cperl-put-do-not-fontify b (point))
		    ;;(put-text-property (max (point-min) (1- b))
		    ;;		     (point) cperl-do-not-fontify t)
		    (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
		    (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
		    (beginning-of-line)
		    (setq b (point)))
		  (put-text-property (point) e 'syntax-type 'pod)
		  (cperl-put-do-not-fontify (point) e)
		  ;;(put-text-property (max (point-min) (1- (point)))
		  ;;		   e cperl-do-not-fontify t)
		  (if cperl-pod-here-fontify 
		      (progn (put-text-property (point) e 'face face)
			     (goto-char bb)
			     (if (looking-at 
				  "=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
				 (put-text-property 
				  (match-beginning 1) (match-end 1)
				  'face head-face))
			     (while (re-search-forward
				     ;; One paragraph
				     "\n\n=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
				     e 'toend)
			       (put-text-property 
				(match-beginning 1) (match-end 1)
				'face head-face))))
		  (goto-char e)))
	      ;; 1 () ahead
	      ;; "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\3\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
	      ((match-beginning 2)	; 1 + 1
	       (if (match-beginning 5)	;4 + 1
		  (setq b1 (match-beginning 5) ; 4 + 1
			e1 (match-end 5)) ; 4 + 1
		(setq b1 (match-beginning 4) ; 3 + 1
		      e1 (match-end 4))) ; 3 + 1
	      (setq tag (buffer-substring b1 e1)
		    qtag (regexp-quote tag))
	      (cond (cperl-pod-here-fontify 
		     (put-text-property b1 e1 'face font-lock-reference-face)
		     (cperl-put-do-not-fontify b1 e1)))
	      (forward-line)
	      (setq b (point))
	      (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
		     (if cperl-pod-here-fontify 
			 (progn
			   (put-text-property (match-beginning 0) (match-end 0) 
					      'face font-lock-reference-face)
			   (cperl-put-do-not-fontify b (match-end 0))
			   ;;(put-text-property (max (point-min) (1- b))
			   ;;		      (min (point-max)
			   ;;			   (1+ (match-end 0)))
			   ;;		      cperl-do-not-fontify t)
			   (put-text-property b (match-beginning 0) 
					      'face here-face)))
		     (put-text-property b (match-beginning 0) 
					'syntax-type 'here-doc)
		     (cperl-put-do-not-fontify b (match-beginning 0)))
		    (t (message "End of here-document `%s' not found." tag))))
	      (t
	       ;; 1+5=6 extra () before this:
	       ;; "^[ \t]*format[ \t]*\\([a-zA-Z0-9_]+\\)?[ \t]*=[ \t]*$")))
	       (setq b (point)
		     name (if (match-beginning 7) ; 6 + 1
			      (buffer-substring (match-beginning 7) ; 6 + 1
						(match-end 7)) ; 6 + 1
			    ""))
	       (setq argument nil)
	       (if cperl-pod-here-fontify 
		   (while (and (eq (forward-line) 0)
			       (not (looking-at "^[.;]$")))
		     (cond
		      ((looking-at "^#")) ; Skip comments
		      ((and argument	; Skip argument multi-lines
			    (looking-at "^[ \t]*{")) 
		       (forward-sexp 1)
		       (setq argument nil))
		      (argument		; Skip argument lines
		       (setq argument nil))
		      (t		; Format line
		       (setq b1 (point))
		       (setq argument (looking-at "^[^\n]*[@^]"))
		       (end-of-line)
		       (put-text-property b1 (point) 
					  'face font-lock-string-face)
		       (cperl-put-do-not-fontify b1 (point)))))
		 (re-search-forward (concat "^[.;]$") max 'toend))
	       (beginning-of-line)
	       (if (looking-at "^[.;]$")
		   (progn
		     (put-text-property (point) (+ (point) 2)
					'face font-lock-string-face)
		     (cperl-put-do-not-fontify (point) (+ (point) 2)))
		 (message "End of format `%s' not found." name))
	       (forward-line)
	       (put-text-property b (point) 'syntax-type 'format)
;;;	       (cond ((re-search-forward (concat "^[.;]$") max 'toend)
;;;		      (if cperl-pod-here-fontify 
;;;			  (progn
;;;			    (put-text-property b (match-end 0)
;;;					       'face font-lock-string-face)
;;;			    (cperl-put-do-not-fontify b (match-end 0))))
;;;		      (put-text-property b (match-end 0) 
;;;					 'syntax-type 'format)
;;;		      (cperl-put-do-not-fontify b (match-beginning 0)))
;;;		     (t (message "End of format `%s' not found." name)))
	       )))
;;;	    (while (re-search-forward "\\(\\`\n?\\|\n\n\\)=" max t)
;;;	      (if (looking-at "\n*cut\\>")
;;;		  (progn
;;;		    (message "=cut is not preceeded by a pod section")
;;;		    (setq err (point)))
;;;		(beginning-of-line)
		
;;;		(setq b (point) bb b)
;;;		(or (re-search-forward "\n\n=cut\\>" max 'toend)
;;;		    (message "Cannot find the end of a pod section"))
;;;		(beginning-of-line 3)
;;;		(setq e (point))
;;;		(put-text-property b e 'in-pod t)
;;;		(goto-char b)
;;;		(while (re-search-forward "\n\n[ \t]" e t)
;;;		  (beginning-of-line)
;;;		  (put-text-property b (point) 'syntax-type 'pod)
;;;		  (cperl-put-do-not-fontify b (point))
;;;		  ;;(put-text-property (max (point-min) (1- b))
;;;		  ;;		     (point) cperl-do-not-fontify t)
;;;		  (if cperl-pod-here-fontify (put-text-property b (point) 'face face))
;;;		  (re-search-forward "\n\n[^ \t\f\n]" e 'toend)
;;;		  (beginning-of-line)
;;;		  (setq b (point)))
;;;		(put-text-property (point) e 'syntax-type 'pod)
;;;		(cperl-put-do-not-fontify (point) e)
;;;		;;(put-text-property (max (point-min) (1- (point)))
;;;		;;		   e cperl-do-not-fontify t)
;;;		(if cperl-pod-here-fontify 
;;;		    (progn (put-text-property (point) e 'face face)
;;;			   (goto-char bb)
;;;			   (if (looking-at 
;;;			    "=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$")
;;;			       (put-text-property 
;;;				(match-beginning 1) (match-end 1)
;;;				'face head-face))
;;;			   (while (re-search-forward
;;;				   ;; One paragraph
;;;				   "\n\n=[a-zA-Z0-9]+\\>[ \t]*\\(\\(\n?[^\n]\\)+\\)$"
;;;				   e 'toend)
;;;			     (put-text-property 
;;;			      (match-beginning 1) (match-end 1)
;;;			      'face head-face))))
;;;		(goto-char e)))
;;;	    (goto-char min)
;;;	    (while (re-search-forward 
;;;		    ;; We exclude \n to avoid misrecognition inside quotes.
;;;		    "<<\\(\\([\"'`]\\)\\([^\"'`\n]*\\)\\2\\|\\(\\([a-zA-Z_][a-zA-Z_0-9]*\\)?\\)\\)"
;;;		    max t)
;;;	      (if (match-beginning 4)
;;;		  (setq b1 (match-beginning 4)
;;;			e1 (match-end 4))
;;;		(setq b1 (match-beginning 3)
;;;		      e1 (match-end 3)))
;;;	      (setq tag (buffer-substring b1 e1)
;;;		    qtag (regexp-quote tag))
;;;	      (cond (cperl-pod-here-fontify 
;;;		     (put-text-property b1 e1 'face font-lock-reference-face)
;;;		     (cperl-put-do-not-fontify b1 e1)))
;;;	      (forward-line)
;;;	      (setq b (point))
;;;	      (cond ((re-search-forward (concat "^" qtag "$") max 'toend)
;;;		     (if cperl-pod-here-fontify 
;;;			 (progn
;;;			   (put-text-property (match-beginning 0) (match-end 0) 
;;;					      'face font-lock-reference-face)
;;;			   (cperl-put-do-not-fontify b (match-end 0))
;;;			   ;;(put-text-property (max (point-min) (1- b))
;;;			   ;;		      (min (point-max)
;;;			   ;;			   (1+ (match-end 0)))
;;;			   ;;		      cperl-do-not-fontify t)
;;;			   (put-text-property b (match-beginning 0) 
;;;					      'face here-face)))
;;;		     (put-text-property b (match-beginning 0) 
;;;					'syntax-type 'here-doc)
;;;		     (cperl-put-do-not-fontify b (match-beginning 0)))
;;;		    (t (message "End of here-document `%s' not found." tag))))
;;;	    (goto-char min)
;;;	    (while (re-search-forward 
;;;		    "^[ \t]*format[ \t]*\\(\\([a-zA-Z0-9_]+[ \t]*\\)?\\)=[ \t]*$"
;;;		    max t)
;;;	      (setq b (point)
;;;		    name (buffer-substring (match-beginning 1)
;;;					   (match-end 1)))
;;;	      (cond ((re-search-forward (concat "^[.;]$") max 'toend)
;;;		     (if cperl-pod-here-fontify 
;;;			 (progn
;;;			   (put-text-property b (match-end 0)
;;;					      'face font-lock-string-face)
;;;			   (cperl-put-do-not-fontify b (match-end 0))))
;;;		     (put-text-property b (match-end 0) 
;;;					'syntax-type 'format)
;;;		     (cperl-put-do-not-fontify b (match-beginning 0)))
;;;		    (t (message "End of format `%s' not found." name))))
)
	  (if err (goto-char err)
	    (message "Scan for pods, formats and here-docs completed.")))
      (and (buffer-modified-p)
	   (not modified)
	   (set-buffer-modified-p nil)))))

(defun cperl-backward-to-noncomment (lim)
  ;; Stops at lim or after non-whitespace that is not in comment
  (let (stop p)
    (while (and (not stop) (> (point) (or lim 1)))
      (skip-chars-backward " \t\n\f" lim)
      (setq p (point))
      (beginning-of-line)
      (if (looking-at "^[ \t]*\\(#\\|$\\)") nil	; Only comment, skip
	;; Else
	(cperl-to-comment-or-eol) 
	(skip-chars-backward " \t")
	(if (< p (point)) (goto-char p))
	(setq stop t)))))

(defun cperl-after-expr-p (&optional lim chars test)
  "Returns true if the position is good for start of expression.
TEST is the expression to evaluate at the found position. If absent,
CHARS is a string that contains good characters to have before us."
  (let (stop p)
    (save-excursion
      (while (and (not stop) (> (point) (or lim 1)))
	(skip-chars-backward " \t\n\f" lim)
	(setq p (point))
	(beginning-of-line)
	(if (looking-at "^[ \t]*\\(#\\|$\\)") nil ; Only comment, skip
	  ;; Else: last iteration (What to do with labels?)
	  (cperl-to-comment-or-eol) 
	  (skip-chars-backward " \t")
	  (if (< p (point)) (goto-char p))
	  (setq stop t)))
      (or (bobp)
	  (progn
	    (backward-char 1)
	    (if test (eval test)
	      (memq (following-char) (append (or chars "{};") nil))))))))

(defun cperl-backward-to-start-of-continued-exp (lim)
  (if (memq (preceding-char) (append ")]}\"'`" nil))
      (forward-sexp -1))
  (beginning-of-line)
  (if (<= (point) lim)
      (goto-char (1+ lim)))
  (skip-chars-forward " \t"))


(defvar innerloop-done nil)
(defvar last-depth nil)

(defun cperl-indent-exp ()
  "Simple variant of indentation of continued-sexp.
Should be slow. Will not indent comment if it starts at `comment-indent'
or looks like continuation of the comment on the previous line."
  (interactive)
  (save-excursion
    (let ((tmp-end (progn (end-of-line) (point))) top done)
      (save-excursion
	(while (null done)
	  (beginning-of-line)
	  (setq top (point))
	  (while (= (nth 0 (parse-partial-sexp (point) tmp-end
					       -1)) -1)
	    (setq top (point)))		; Get the outermost parenths in line
	  (goto-char top)
	  (while (< (point) tmp-end)
	    (parse-partial-sexp (point) tmp-end nil t) ; To start-sexp or eol
	    (or (eolp) (forward-sexp 1)))
	  (if (> (point) tmp-end) (progn (end-of-line) (setq tmp-end (point)))
	    (setq done t)))
	(goto-char tmp-end)
	(setq tmp-end (point-marker)))
      (cperl-indent-region (point) tmp-end))))

(defun cperl-indent-region (start end)
  "Simple variant of indentation of region in CPerl mode.
Should be slow. Will not indent comment if it starts at `comment-indent' 
or looks like continuation of the comment on the previous line.
Indents all the lines whose first character is between START and END 
inclusive."
  (interactive "r")
  (save-excursion
    (let (st comm indent-info old-comm-indent new-comm-indent 
	     (pm 0) (imenu-scanning-message "Indenting... (%3d%%)"))
      (goto-char start)
      (setq old-comm-indent (and (cperl-to-comment-or-eol)
				 (current-column))
	    new-comm-indent old-comm-indent)
      (goto-char start)
      (or (bolp) (beginning-of-line 2))
      (or (fboundp 'imenu-progress-message)
	  (message "Indenting... For feedback load `imenu'..."))
      (while (and (<= (point) end) (not (eobp))) ; bol to check start
	(and (fboundp 'imenu-progress-message)
	     (imenu-progress-message 
	      pm (/ (* 100 (- (point) start)) (- end start -1))))
	(setq st (point) 
	      indent-info nil
	      ) ; Believe indentation of the current
	(if (and (setq comm (looking-at "[ \t]*#"))
		 (or (eq (current-indentation) (or old-comm-indent 
						   comment-column))
		     (setq old-comm-indent nil)))
	    (if (and old-comm-indent
		     (= (current-indentation) old-comm-indent))
		(let ((comment-column new-comm-indent))
		  (indent-for-comment)))
	  (progn 
	    (cperl-indent-line 'indent-info)
	    (or comm
		(progn
		  (if (setq old-comm-indent (and (cperl-to-comment-or-eol)
						 (current-column)))
		      (progn (indent-for-comment)
			     (skip-chars-backward " \t")
			     (skip-chars-backward "#")
			     (setq new-comm-indent (current-column))))))))
	(beginning-of-line 2))
      	(if (fboundp 'imenu-progress-message)
	     (imenu-progress-message pm 100)
	  (message nil)))))

(defun cperl-slash-is-regexp (&optional pos)
  (save-excursion
    (goto-char (if pos pos (1- (point))))
    (and
     (not (memq (get-text-property (point) 'face)
		'(font-lock-string-face font-lock-comment-face)))
     (cperl-after-expr-p nil nil '
		       (or (looking-at "[^]a-zA-Z0-9_)}]")
			   (eq (get-text-property (point) 'face)
			       'font-lock-keyword-face))))))

;; Stolen from lisp-mode with a lot of improvements

(defun cperl-fill-paragraph (&optional justify iteration)
  "Like \\[fill-paragraph], but handle CPerl comments.
If any of the current line is a comment, fill the comment or the
block of it that point is in, preserving the comment's initial
indentation and initial hashes. Behaves usually outside of comment."
  (interactive "P")
  (let (
	;; Non-nil if the current line contains a comment.
	has-comment

	;; If has-comment, the appropriate fill-prefix for the comment.
	comment-fill-prefix
	;; Line that contains code and comment (or nil)
	start
	c spaces len dc (comment-column comment-column))
    ;; Figure out what kind of comment we are looking at.
    (save-excursion
      (beginning-of-line)
      (cond

       ;; A line with nothing but a comment on it?
       ((looking-at "[ \t]*#[# \t]*")
	(setq has-comment t
	      comment-fill-prefix (buffer-substring (match-beginning 0)
						    (match-end 0))))

       ;; A line with some code, followed by a comment?  Remember that the
       ;; semi which starts the comment shouldn't be part of a string or
       ;; character.
       ((cperl-to-comment-or-eol)
	(setq has-comment t)
	(looking-at "#+[ \t]*")
	(setq start (point) c (current-column) 
	      comment-fill-prefix
	      (concat (make-string (current-column) ?\ )
		      (buffer-substring (match-beginning 0) (match-end 0)))
	      spaces (progn (skip-chars-backward " \t") 
			    (buffer-substring (point) start))
	      dc (- c (current-column)) len (- start (point)) 
	      start (point-marker))
	(delete-char len)
	(insert (make-string dc ?-)))))
    (if (not has-comment)
	(fill-paragraph justify)	; Do the usual thing outside of comment
      ;; Narrow to include only the comment, and then fill the region.
      (save-restriction
	(narrow-to-region
	 ;; Find the first line we should include in the region to fill.
	 (if start (progn (beginning-of-line) (point))
	   (save-excursion
	     (while (and (zerop (forward-line -1))
			 (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
	     ;; We may have gone to far.  Go forward again.
	     (or (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")
		 (forward-line 1))
	     (point)))
	 ;; Find the beginning of the first line past the region to fill.
	 (save-excursion
	   (while (progn (forward-line 1)
			 (looking-at "^[ \t]*#+[ \t]*[^ \t\n#]")))
	   (point)))
	;; Remove existing hashes
	(goto-char (point-min))
	(while (progn (forward-line 1) (< (point) (point-max)))
	  (skip-chars-forward " \t")
	  (and (looking-at "#+") 
	       (delete-char (- (match-end 0) (match-beginning 0)))))

	;; Lines with only hashes on them can be paragraph boundaries.
	(let ((paragraph-start (concat paragraph-start "\\|^[ \t#]*$"))
	      (paragraph-separate (concat paragraph-start "\\|^[ \t#]*$"))
	      (fill-prefix comment-fill-prefix))
	  (fill-paragraph justify)))
      (if (and start)
	  (progn 
	    (goto-char start)
	    (if (> dc 0)
	      (progn (delete-char dc) (insert spaces)))
	    (if (or (= (current-column) c) iteration) nil
	      (setq comment-column c)
	      (indent-for-comment)
	      ;; Repeat once more, flagging as iteration
	      (cperl-fill-paragraph justify t)))))))

(defun cperl-do-auto-fill ()
  ;; Break out if the line is short enough
  (if (> (save-excursion
	   (end-of-line)
	   (current-column))
	 fill-column)
  (let ((c (save-excursion (beginning-of-line)
			   (cperl-to-comment-or-eol) (point)))
	(s (memq (following-char) '(?\ ?\t))) marker)
    (if (>= c (point)) nil
      (setq marker (point-marker))
      (cperl-fill-paragraph)
      (goto-char marker)
      ;; Is not enough, sometimes marker is a start of line
      (if (bolp) (progn (re-search-forward "#+[ \t]*") 
			(goto-char (match-end 0))))
      ;; Following space could have gone:
      (if (or (not s) (memq (following-char) '(?\ ?\t))) nil
	(insert " ")
	(backward-char 1))
      ;; Previous space could have gone:
      (or (memq (preceding-char) '(?\ ?\t)) (insert " "))))))

(defvar imenu-example--function-name-regexp-perl
      "^\\([ \t]*\\(sub\\|package\\)[ \t\n]+\\([a-zA-Z_0-9:']+\\)[ \t]*\\|=head\\([12]\\)[ \t]+\\([^\n]+\\)$\\)")

(defun cperl-imenu-addback (lst &optional isback name)
  ;; We suppose that the lst is a DAG, unless the first element only
  ;; loops back, and ISBACK is set. Thus this function cannot be
  ;; applied twice without ISBACK set.
  (cond ((not cperl-imenu-addback) lst)
	(t
	 (or name 
	     (setq name "+++BACK+++"))
	 (mapcar (function (lambda (elt)
			     (if (and (listp elt) (listp (cdr elt)))
				 (progn
				   ;; In the other order it goes up
				   ;; one level only ;-(
				   (setcdr elt (cons (cons name lst)
						     (cdr elt)))
				   (cperl-imenu-addback (cdr elt) t name)
				   ))))
		 (if isback (cdr lst) lst))
	 lst)))

(defun imenu-example--create-perl-index (&optional regexp)
  (require 'cl)
  (let ((index-alist '()) (index-pack-alist '()) (index-pod-alist '()) 
	(index-unsorted-alist '()) (i-s-f (default-value 'imenu-sort-function))
	(index-meth-alist '()) meth
	packages ends-ranges p
	(prev-pos 0) char fchar index index1 name (end-range 0) package)
    (goto-char (point-min))
    (imenu-progress-message prev-pos 0)
    ;; Search for the function
    (progn ;;save-match-data
      (while (re-search-forward
	      (or regexp imenu-example--function-name-regexp-perl)
	      nil t)
	(imenu-progress-message prev-pos)
	;;(backward-up-list 1)
	(cond
	 ((match-beginning 2)		; package or sub
	  (save-excursion
	    (goto-char (match-beginning 2))
	    (setq fchar (following-char))
	    )
	  (setq char (following-char) meth nil)
	  (setq p (point))
	  (while (and ends-ranges (>= p (car ends-ranges)))
	    ;; delete obsolete entries
	    (setq ends-ranges (cdr ends-ranges) packages (cdr packages)))
	  (setq package (or (car packages) "")
		end-range (or (car ends-ranges) 0))
	  (if (eq fchar ?p)
	      (setq name (buffer-substring (match-beginning 3) (match-end 3))
		    name (progn
			   (set-text-properties 0 (length name) nil name)
			   name)
		    package (concat name "::") 
		    name (concat "package " name)
		    end-range 
		    (save-excursion
		      (parse-partial-sexp (point) (point-max) -1) (point))
		    ends-ranges (cons end-range ends-ranges)
		    packages (cons package packages)))
	  ;;   )
	  ;; Skip this function name if it is a prototype declaration.
	  (if (and (eq fchar ?s) (eq char ?\;)) nil
	    (setq index (imenu-example--name-and-position))
	    (if (eq fchar ?p) nil
	      (setq name (buffer-substring (match-beginning 3) (match-end 3)))
	      (set-text-properties 0 (length name) nil name)
	      (cond ((string-match "[:']" name)
		     (setq meth t))
		    ((> p end-range) nil)
		    (t 
		     (setq name (concat package name) meth t))))
	    (setcar index name)
	    (if (eq fchar ?p) 
		(push index index-pack-alist)
	      (push index index-alist))
	    (if meth (push index index-meth-alist))
	    (push index index-unsorted-alist)))
	 (t				; Pod section
	  ;; (beginning-of-line)
	  (setq index (imenu-example--name-and-position)
		name (buffer-substring (match-beginning 5) (match-end 5)))
	  (set-text-properties 0 (length name) nil name)
	  (if (eq (char-after (match-beginning 4)) ?2)
	      (setq name (concat "   " name)))
	  (setcar index name)
	  (setq index1 (cons (concat "=" name) (cdr index)))
	  (push index index-pod-alist)
	  (push index1 index-unsorted-alist)))))
    (imenu-progress-message prev-pos 100)
    (setq index-alist 
	  (if (default-value 'imenu-sort-function)
	      (sort index-alist (default-value 'imenu-sort-function))
	      (nreverse index-alist)))
    (and index-pod-alist
	 (push (cons "+POD headers+..."
		     (nreverse index-pod-alist))
	       index-alist))
    (and (or index-pack-alist index-meth-alist)
	 (let ((lst index-pack-alist) hier-list pack elt group name)
	   ;; Remove "package ", reverse and uniquify.
	   (while lst
	     (setq elt (car lst) lst (cdr lst) name (substring (car elt) 8))
	     (if (assoc name hier-list) nil
	       (setq hier-list (cons (cons name (cdr elt)) hier-list))))
	   (setq lst index-meth-alist)
	   (while lst
	     (setq elt (car lst) lst (cdr lst))
	     (cond ((string-match "\\(::\\|'\\)[_a-zA-Z0-9]+$" (car elt))
		    (setq pack (substring (car elt) 0 (match-beginning 0)))
		    (if (setq group (assoc pack hier-list)) 
			(if (listp (cdr group))
			    ;; Have some functions already
			    (setcdr group 
				    (cons (cons (substring 
						 (car elt)
						 (+ 2 (match-beginning 0)))
						(cdr elt))
					  (cdr group)))
			  (setcdr group (list (cons (substring 
						     (car elt)
						     (+ 2 (match-beginning 0)))
						    (cdr elt)))))
		      (setq hier-list 
			    (cons (cons pack 
					(list (cons (substring 
						     (car elt)
						     (+ 2 (match-beginning 0)))
						    (cdr elt))))
				  hier-list))))))
	   (push (cons "+Hierarchy+..."
		       hier-list)
		 index-alist)))
    (and index-pack-alist
	 (push (cons "+Packages+..."
		     (nreverse index-pack-alist))
	       index-alist))
    (and (or index-pack-alist index-pod-alist 
	     (default-value 'imenu-sort-function))
	 index-unsorted-alist
	 (push (cons "+Unsorted List+..."
		     (nreverse index-unsorted-alist))
	       index-alist))
    (cperl-imenu-addback index-alist)))

(defvar cperl-compilation-error-regexp-alist 
  ;; This look like a paranoiac regexp: could anybody find a better one? (which WORK).
  '(("^[^\n]* \\(file\\|at\\) \\([^ \t\n]+\\) [^\n]*line \\([0-9]+\\)[\\., \n]"
     2 3))
  "Alist that specifies how to match errors in perl output.")

(if (fboundp 'eval-after-load)
    (eval-after-load
     "mode-compile"
     '(setq perl-compilation-error-regexp-alist
	   cperl-compilation-error-regexp-alist)))


(defvar cperl-faces-init nil)

(defun cperl-windowed-init ()
  "Initialization under windowed version."
  (add-hook 'font-lock-mode-hook
	    (function
	     (lambda ()
	       (if (or
		    (eq major-mode 'perl-mode)
		    (eq major-mode 'cperl-mode))
		   (progn
		     (or cperl-faces-init (cperl-init-faces))))))))

(defvar perl-font-lock-keywords-1 nil
  "Additional expressions to highlight in Perl mode. Minimal set.")
(defvar perl-font-lock-keywords nil
  "Additional expressions to highlight in Perl mode. Default set.")
(defvar perl-font-lock-keywords-2 nil
  "Additional expressions to highlight in Perl mode. Maximal set")

(defun cperl-init-faces ()
  (condition-case nil
      (progn
	(require 'font-lock)
	(and (fboundp 'font-lock-fontify-anchored-keywords)
	     (featurep 'font-lock-extra)
	     (message "You have an obsolete package `font-lock-extra'. Install `choose-color'."))
	(let (t-font-lock-keywords t-font-lock-keywords-1 font-lock-anchored)
	  ;;(defvar cperl-font-lock-enhanced nil
	  ;;  "Set to be non-nil if font-lock allows active highlights.")
	  (if (fboundp 'font-lock-fontify-anchored-keywords)
	      (setq font-lock-anchored t))
	  (setq 
	   t-font-lock-keywords
	   (list
	    (cons
	     (concat
	      "\\(^\\|[^$@%&\\]\\)\\<\\("
	      (mapconcat
	       'identity
	       '("if" "until" "while" "elsif" "else" "unless" "for"
		 "foreach" "continue" "exit" "die" "last" "goto" "next"
		 "redo" "return" "local" "exec" "sub" "do" "dump" "use"
		 "require" "package" "eval" "my" "BEGIN" "END")
	       "\\|")			; Flow control
	      "\\)\\>") 2)		; was "\\)[ \n\t;():,\|&]"
					; In what follows we use `type' style
					; for overwritable buildins
	    (list
	     (concat
	      "\\(^\\|[^$@%&\\]\\)\\<\\("
	      ;; "CORE" "__FILE__" "__LINE__" "abs" "accept" "alarm" "and" "atan2"
	      ;; "bind" "binmode" "bless" "caller" "chdir" "chmod" "chown" "chr"
	      ;; "chroot" "close" "closedir" "cmp" "connect" "continue" "cos"
	      ;; "crypt" "dbmclose" "dbmopen" "die" "dump" "endgrent" "endhostent"
	      ;; "endnetent" "endprotoent" "endpwent" "endservent" "eof" "eq" "exec"
	      ;; "exit" "exp" "fcntl" "fileno" "flock" "fork" "formline" "ge" "getc"
	      ;; "getgrent" "getgrgid" "getgrnam" "gethostbyaddr" "gethostbyname"
	      ;; "gethostent" "getlogin" "getnetbyaddr" "getnetbyname" "getnetent"
	      ;; "getpeername" "getpgrp" "getppid" "getpriority" "getprotobyname"
	      ;; "getprotobynumber" "getprotoent" "getpwent" "getpwnam" "getpwuid"
	      ;; "getservbyname" "getservbyport" "getservent" "getsockname"
	      ;; "getsockopt" "glob" "gmtime" "gt" "hex" "index" "int" "ioctl"
	      ;; "join" "kill" "lc" "lcfirst" "le" "length" "link" "listen"
	      ;; "localtime" "log" "lstat" "lt" "mkdir" "msgctl" "msgget" "msgrcv"
	      ;; "msgsnd" "ne" "not" "oct" "open" "opendir" "or" "ord" "pack" "pipe"
	      ;; "quotemeta" "rand" "read" "readdir" "readline" "readlink"
	      ;; "readpipe" "recv" "ref" "rename" "require" "reset" "reverse"
	      ;; "rewinddir" "rindex" "rmdir" "seek" "seekdir" "select" "semctl"
	      ;; "semget" "semop" "send" "setgrent" "sethostent" "setnetent"
	      ;; "setpgrp" "setpriority" "setprotoent" "setpwent" "setservent"
	      ;; "setsockopt" "shmctl" "shmget" "shmread" "shmwrite" "shutdown"
	      ;; "sin" "sleep" "socket" "socketpair" "sprintf" "sqrt" "srand" "stat"
	      ;; "substr" "symlink" "syscall" "sysread" "system" "syswrite" "tell"
	      ;; "telldir" "time" "times" "truncate" "uc" "ucfirst" "umask" "unlink"
	      ;; "unpack" "utime" "values" "vec" "wait" "waitpid" "wantarray" "warn"
	      ;; "write" "x" "xor"
	      "a\\(bs\\|ccept\\|tan2\\|larm\\|nd\\)\\|" 
	      "b\\(in\\(d\\|mode\\)\\|less\\)\\|"
	      "c\\(h\\(r\\(\\|oot\\)\\|dir\\|mod\\|own\\)\\|aller\\|rypt\\|"
	      "lose\\(\\|dir\\)\\|mp\\|o\\(s\\|n\\(tinue\\|nect\\)\\)\\)\\|"
	      "CORE\\|d\\(ie\\|bm\\(close\\|open\\)\\|ump\\)\\|"
	      "e\\(x\\(p\\|it\\|ec\\)\\|q\\|nd\\(p\\(rotoent\\|went\\)\\|"
	      "hostent\\|servent\\|netent\\|grent\\)\\|of\\)\\|"
	      "f\\(ileno\\|cntl\\|lock\\|or\\(k\\|mline\\)\\)\\|"
	      "g\\(t\\|lob\\|mtime\\|e\\(\\|t\\(p\\(pid\\|r\\(iority\\|"
	      "oto\\(byn\\(ame\\|umber\\)\\|ent\\)\\)\\|eername\\|w"
	      "\\(uid\\|ent\\|nam\\)\\|grp\\)\\|host\\(by\\(addr\\|name\\)\\|"
	      "ent\\)\\|s\\(erv\\(by\\(port\\|name\\)\\|ent\\)\\|"
	      "ock\\(name\\|opt\\)\\)\\|c\\|login\\|net\\(by\\(addr\\|name\\)\\|"
	      "ent\\)\\|gr\\(ent\\|nam\\|gid\\)\\)\\)\\)\\|"
	      "hex\\|i\\(n\\(t\\|dex\\)\\|octl\\)\\|join\\|kill\\|"
	      "l\\(i\\(sten\\|nk\\)\\|stat\\|c\\(\\|first\\)\\|t\\|e"
	      "\\(\\|ngth\\)\\|o\\(caltime\\|g\\)\\)\\|m\\(sg\\(rcv\\|snd\\|"
	      "ctl\\|get\\)\\|kdir\\)\\|n\\(e\\|ot\\)\\|o\\(pen\\(\\|dir\\)\\|"
	      "r\\(\\|d\\)\\|ct\\)\\|p\\(ipe\\|ack\\)\\|quotemeta\\|"
	      "r\\(index\\|and\\|mdir\\|e\\(quire\\|ad\\(pipe\\|\\|lin"
	      "\\(k\\|e\\)\\|dir\\)\\|set\\|cv\\|verse\\|f\\|winddir\\|name"
	      "\\)\\)\\|s\\(printf\\|qrt\\|rand\\|tat\\|ubstr\\|e\\(t\\(p\\(r"
	      "\\(iority\\|otoent\\)\\|went\\|grp\\)\\|hostent\\|s\\(ervent\\|"
	      "ockopt\\)\\|netent\\|grent\\)\\|ek\\(\\|dir\\)\\|lect\\|"
	      "m\\(ctl\\|op\\|get\\)\\|nd\\)\\|h\\(utdown\\|m\\(read\\|ctl\\|"
	      "write\\|get\\)\\)\\|y\\(s\\(read\\|call\\|tem\\|write\\)\\|"
	      "mlink\\)\\|in\\|leep\\|ocket\\(pair\\|\\)\\)\\|t\\(runcate\\|"
	      "ell\\(\\|dir\\)\\|ime\\(\\|s\\)\\)\\|u\\(c\\(\\|first\\)\\|"
	      "time\\|mask\\|n\\(pack\\|link\\)\\)\\|v\\(alues\\|ec\\)\\|"
	      "w\\(a\\(rn\\|it\\(pid\\|\\)\\|ntarray\\)\\|rite\\)\\|"
	      "x\\(\\|or\\)\\|__\\(FILE__\\|LINE__\\)"
	      "\\)\\>") 2 'font-lock-type-face)
	    ;; In what follows we use `other' style
	    ;; for nonoverwritable buildins
	    ;; Somehow 's', 'm' are not autogenerated???
	    (list
	     (concat
	      "\\(^\\|[^$@%&\\]\\)\\<\\("
	      ;; "AUTOLOAD" "BEGIN" "DESTROY" "END" "__END__" "chomp" "chop"
	      ;; "defined" "delete" "do" "each" "else" "elsif" "eval" "exists" "for"
	      ;; "foreach" "format" "goto" "grep" "if" "keys" "last" "local" "map"
	      ;; "my" "next" "no" "package" "pop" "pos" "print" "printf" "push" "q"
	      ;; "qq" "qw" "qx" "redo" "return" "scalar" "shift" "sort" "splice"
	      ;; "split" "study" "sub" "tie" "tr" "undef" "unless" "unshift" "untie"
	      ;; "until" "use" "while" "y"
	      "AUTOLOAD\\|BEGIN\\|cho\\(p\\|mp\\)\\|d\\(e\\(fined\\|lete\\)\\|"
	      "o\\)\\|DESTROY\\|e\\(ach\\|val\\|xists\\|ls\\(e\\|if\\)\\)\\|"
	      "END\\|for\\(\\|each\\|mat\\)\\|g\\(rep\\|oto\\)\\|if\\|keys\\|"
	      "l\\(ast\\|ocal\\)\\|m\\(ap\\|y\\)\\|n\\(ext\\|o\\)\\|"
	      "p\\(ackage\\|rint\\(\\|f\\)\\|ush\\|o\\(p\\|s\\)\\)\\|"
	      "q\\(\\|q\\|w\\|x\\)\\|re\\(turn\\|do\\)\\|s\\(pli\\(ce\\|t\\)\\|"
	      "calar\\|tudy\\|ub\\|hift\\|ort\\)\\|t\\(r\\|ie\\)\\|"
	      "u\\(se\\|n\\(shift\\|ti\\(l\\|e\\)\\|def\\|less\\)\\)\\|"
	      "while\\|y\\|__\\(END\\|DATA\\)__" ;__DATA__ added manually
	      "\\|[sm]"			; Added manually
	      "\\)\\>") 2 'font-lock-other-type-face)
	    ;;		(mapconcat 'identity
	    ;;			   '("#endif" "#else" "#ifdef" "#ifndef" "#if"
	    ;;			     "#include" "#define" "#undef")
	    ;;			   "\\|")
	    '("-[rwxoRWXOezsfdlpSbctugkTBMAC]\\>\\([ \t]+_\\>\\)?" 0
	      font-lock-function-name-face) ; Not very good, triggers at "[a-z]"
	    '("\\<sub[ \t]+\\([^ \t{;]+\\)[ \t]*[{\n]" 1
	      font-lock-function-name-face)
	    '("\\<\\(package\\|require\\|use\\|import\\|no\\|bootstrap\\)[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t;]" ; require A if B;
	      2 font-lock-function-name-face)
	    '("^[ \t]*format[ \t]+\\([a-zA-z_][a-zA-z_0-9:]*\\)[ \t]*=[ \t]*$"
	      1 font-lock-function-name-face)
	    (cond ((featurep 'font-lock-extra)
		   '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}" 
		     (2 font-lock-string-face t)
		     (0 '(restart 2 t)))) ; To highlight $a{bc}{ef}
		  (font-lock-anchored
		   '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
		     (2 font-lock-string-face t)
		     ("\\=[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
		      nil nil
		      (1 font-lock-string-face t))))
		  (t '("\\([]}\\\\%@>*&]\\|\\$[a-zA-Z0-9_:]*\\)[ \t]*{[ \t]*\\(-?[a-zA-Z0-9_:]+\\)[ \t]*}"
		       2 font-lock-string-face t)))
	    '("[ \t{,(]\\(-?[a-zA-Z0-9_:]+\\)[ \t]*=>" 1
	      font-lock-string-face t)
	    '("^[ \t]*\\([a-zA-Z0-9_]+[ \t]*:\\)[ \t]*\\($\\|{\\|\\<\\(until\\|while\\|for\\(each\\)?\\|do\\)\\>\\)" 1 
	      font-lock-reference-face) ; labels
	    '("\\<\\(continue\\|next\\|last\\|redo\\|goto\\)\\>[ \t]+\\([a-zA-Z0-9_:]+\\)" ; labels as targets
	      2 font-lock-reference-face)
	    (cond ((featurep 'font-lock-extra)
		   '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
		     (3 font-lock-variable-name-face)
		     (4 '(another 4 nil
				  ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)\\([ \t]*,\\)?"
				   (1 font-lock-variable-name-face)
				   (2 '(restart 2 nil) nil t))) 
			nil t)))	; local variables, multiple
		  (font-lock-anchored
		   '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
		     (3 font-lock-variable-name-face)
		     ("\\=[ \t]*,[ \t]*\\([$@%*][a-zA-Z0-9_:]+\\)"
		      nil nil
		      (1 font-lock-variable-name-face))))
		  (t '("^[ \t]*\\(my\\|local\\)[ \t]*\\(([ \t]*\\)?\\([$@%*][a-zA-Z0-9_:]+\\)"
		       3 font-lock-variable-name-face)))
	    '("\\<for\\(each\\)?[ \t]*\\(\\$[a-zA-Z_][a-zA-Z_0-9]*\\)[ \t]*("
	      2 font-lock-variable-name-face)))
	  (setq 
	   t-font-lock-keywords-1
	   (and (fboundp 'turn-on-font-lock) ; Check for newer font-lock
		(not (cperl-xemacs-p)) ; not yet as of XEmacs 19.12
		'(("\\(\\([$@]+\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)[ \t]*\\([[{]\\)"
		   1
		   (if (= (- (match-end 2) (match-beginning 2)) 1) 
		       (if (eq (char-after (match-beginning 3)) ?{)
			   font-lock-other-emphasized-face
			 font-lock-emphasized-face) ; arrays and hashes
		     font-lock-variable-name-face) ; Just to put something
		   t)
		  ("\\(\\([@%]\\|\$#\\)[a-zA-Z_:][a-zA-Z0-9_:]*\\)" 1
		   (if (eq (char-after (match-beginning 2)) ?%)
		       font-lock-other-emphasized-face
		     font-lock-emphasized-face)
		   t)			; arrays and hashes
		  ;;("\\([smy]\\|tr\\)\\([^a-z_A-Z0-9]\\)\\(\\([^\n\\]*||\\)\\)\\2")
		       ;;; Too much noise from \s* @s[ and friends
		  ;;("\\(\\<\\([msy]\\|tr\\)[ \t]*\\([^ \t\na-zA-Z0-9_]\\)\\|\\(/\\)\\)" 
		  ;;(3 font-lock-function-name-face t t)
		  ;;(4
		  ;; (if (cperl-slash-is-regexp)
		  ;;    font-lock-function-name-face 'default) nil t))
		  )))
	  (setq perl-font-lock-keywords-1 t-font-lock-keywords
		perl-font-lock-keywords perl-font-lock-keywords-1
		perl-font-lock-keywords-2 (append
					   t-font-lock-keywords
					   t-font-lock-keywords-1)))
	(if (fboundp 'ps-print-buffer) (cperl-ps-print-init))
	(if (or (featurep 'choose-color) (featurep 'font-lock-extra))
	    (font-lock-require-faces
	     (list
	      ;; Color-light    Color-dark      Gray-light      Gray-dark Mono
	      (list 'font-lock-comment-face
		    ["Firebrick"	"OrangeRed" 	"DimGray"	"Gray80"]
		    nil
		    [nil		nil		t		t	t]
		    [nil		nil		t		t	t]
		    nil)
	      (list 'font-lock-string-face
		    ["RosyBrown"	"LightSalmon" 	"Gray50"	"LightGray"]
		    nil
		    nil
		    [nil		nil		t		t	t]
		    nil)
	      (list 'font-lock-keyword-face
		    ["Purple"		"LightSteelBlue" "DimGray"	"Gray90"]
		    nil
		    [nil		nil		t		t	t]
		    nil
		    nil)
	      (list 'font-lock-function-name-face
		    (vector
		     "Blue"		"LightSkyBlue"	"Gray50"	"LightGray"
		     (cdr (assq 'background-color ; if mono
				(frame-parameters))))
		    (vector
		     nil		nil		nil		nil
		     (cdr (assq 'foreground-color ; if mono
				(frame-parameters))))
		    [nil		nil		t		t	t]
		    nil
		    nil)
	      (list 'font-lock-variable-name-face
		    ["DarkGoldenrod"	"LightGoldenrod" "DimGray"	"Gray90"]
		    nil
		    [nil		nil		t		t	t]
		    [nil		nil		t		t	t]
		    nil)
	      (list 'font-lock-type-face
		    ["DarkOliveGreen"	"PaleGreen" 	"DimGray"	"Gray80"]
		    nil
		    [nil		nil		t		t	t]
		    nil
		    [nil		nil		t		t	t]
		    )
	      (list 'font-lock-reference-face
		    ["CadetBlue"	"Aquamarine" 	"Gray50"	"LightGray"]
		    nil
		    [nil		nil		t		t	t]
		    nil
		    [nil		nil		t		t	t]
		    )
	      (list 'font-lock-other-type-face
		    ["chartreuse3"	("orchid1" "orange")
		     nil		"Gray80"]
		    [nil		nil		"gray90"]
		    [nil		nil		nil		t	t]
		    [nil		nil		t		t]
		    [nil		nil		t		t	t]
		    )
	      (list 'font-lock-emphasized-face
		    ["blue"		"yellow" 	nil		"Gray80"]
		    ["lightyellow2"	("navy" "os2blue" "darkgreen")
		     "gray90"]
		    t
		    nil
		    nil)
	      (list 'font-lock-other-emphasized-face
		    ["red"		"red"	 	nil		"Gray80"]
		    ["lightyellow2"	("navy" "os2blue" "darkgreen")
		     "gray90"]
		    t
		    t
		    nil)))
	  (defvar cperl-guessed-background nil
	    "Display characteristics as guessed by cperl.")
	  (or (fboundp 'x-color-defined-p)
	      (defalias 'x-color-defined-p 
		(cond ((fboundp 'color-defined-p) 'color-defined-p)
		      ;; XEmacs >= 19.12
		      ((fboundp 'valid-color-name-p) 'valid-color-name-p)
		      ;; XEmacs 19.11
		      (t 'x-valid-color-name-p))))
	  (defvar font-lock-reference-face 'font-lock-reference-face)
	  (defvar font-lock-variable-name-face 'font-lock-variable-name-face)
	  (or (boundp 'font-lock-type-face)
	      (defconst font-lock-type-face
		'font-lock-type-face
		"Face to use for data types.")
	      )
	  (or (boundp 'font-lock-other-type-face)
	      (defconst font-lock-other-type-face
		'font-lock-other-type-face
		"Face to use for data types from another group.")
	      )
	  (if (not (cperl-xemacs-p)) nil
	    (or (boundp 'font-lock-comment-face)
		(defconst font-lock-comment-face
		  'font-lock-comment-face
		  "Face to use for comments.")
		)
	    (or (boundp 'font-lock-keyword-face)
		(defconst font-lock-keyword-face
		  'font-lock-keyword-face
		  "Face to use for keywords.")
		)
	    (or (boundp 'font-lock-function-name-face)
		(defconst font-lock-function-name-face
		  'font-lock-function-name-face
		  "Face to use for function names.")
		)
	    )
	  ;;(if (featurep 'font-lock)
	  (if (face-equal font-lock-type-face font-lock-comment-face)
	      (defconst font-lock-type-face
		'font-lock-type-face
		"Face to use for basic data types.")
	    )
;;;	  (if (fboundp 'eval-after-load)
;;;	      (eval-after-load "font-lock"
;;;			       '(if (face-equal font-lock-type-face
;;;						font-lock-comment-face)
;;;				    (defconst font-lock-type-face
;;;				      'font-lock-type-face
;;;				      "Face to use for basic data types.")
;;;				  )))	; This does not work :-( Why?!
;;;					; Workaround: added to font-lock-m-h
;;;	  )
	  (or (boundp 'font-lock-other-emphasized-face)
	      (defconst font-lock-other-emphasized-face
		'font-lock-other-emphasized-face
		"Face to use for another type of emphasizing.")
	      )
	  (or (boundp 'font-lock-emphasized-face)
	      (defconst font-lock-emphasized-face
		'font-lock-emphasized-face
		"Face to use for emphasizing.")
	      )
	  ;; Here we try to guess background
	  (let ((background
		 (if (boundp 'font-lock-background-mode)
		     font-lock-background-mode
		   'light)) 
		(face-list (and (fboundp 'face-list) (face-list)))
		is-face)
	    (fset 'is-face
		  (cond ((fboundp 'find-face)
			 (symbol-function 'find-face))
			(face-list
			 (function (lambda (face) (member face face-list))))
			(t
			 (function (lambda (face) (boundp face))))))
	    (defvar cperl-guessed-background
	      (if (and (boundp 'font-lock-display-type)
		       (eq font-lock-display-type 'grayscale))
		  'gray
		background)
	      "Background as guessed by CPerl mode")
	    (if (is-face 'font-lock-type-face) nil
	      (copy-face 'default 'font-lock-type-face)
	      (cond
	       ((eq background 'light)
		(set-face-foreground 'font-lock-type-face
				     (if (x-color-defined-p "seagreen")
					 "seagreen"
				       "sea green")))
	       ((eq background 'dark)
		(set-face-foreground 'font-lock-type-face
				     (if (x-color-defined-p "os2pink")
					 "os2pink"
				       "pink")))
	       (t
		(set-face-background 'font-lock-type-face "gray90"))))
	    (if (is-face 'font-lock-other-type-face)
		nil
	      (copy-face 'font-lock-type-face 'font-lock-other-type-face)
	      (cond
	       ((eq background 'light)
		(set-face-foreground 'font-lock-other-type-face
				     (if (x-color-defined-p "chartreuse3")
					 "chartreuse3"
				       "chartreuse")))
	       ((eq background 'dark)
		(set-face-foreground 'font-lock-other-type-face
				     (if (x-color-defined-p "orchid1")
					 "orchid1"
				       "orange")))))
	    (if (is-face 'font-lock-other-emphasized-face) nil
	      (copy-face 'bold-italic 'font-lock-other-emphasized-face)
	      (cond
	       ((eq background 'light)
		(set-face-background 'font-lock-other-emphasized-face
				     (if (x-color-defined-p "lightyellow2")
					 "lightyellow2"
				       (if (x-color-defined-p "lightyellow")
					   "lightyellow"
					 "light yellow"))))
	       ((eq background 'dark)
		(set-face-background 'font-lock-other-emphasized-face
				     (if (x-color-defined-p "navy")
					 "navy"
				       (if (x-color-defined-p "darkgreen")
					   "darkgreen"
					 "dark green"))))
	       (t (set-face-background 'font-lock-other-emphasized-face "gray90"))))
	    (if (is-face 'font-lock-emphasized-face) nil
	      (copy-face 'bold 'font-lock-emphasized-face)
	      (cond
	       ((eq background 'light)
		(set-face-background 'font-lock-emphasized-face
				     (if (x-color-defined-p "lightyellow2")
					 "lightyellow2"
				       "lightyellow")))
	       ((eq background 'dark)
		(set-face-background 'font-lock-emphasized-face
				     (if (x-color-defined-p "navy")
					 "navy"
				       (if (x-color-defined-p "darkgreen")
					   "darkgreen"
					 "dark green"))))
	       (t (set-face-background 'font-lock-emphasized-face "gray90"))))
	    (if (is-face 'font-lock-variable-name-face) nil
	      (copy-face 'italic 'font-lock-variable-name-face))
	    (if (is-face 'font-lock-reference-face) nil
	      (copy-face 'italic 'font-lock-reference-face))))
	(setq cperl-faces-init t))
    (error nil)))


(defun cperl-ps-print-init ()
  "Initialization of `ps-print' components for faces used in CPerl."
  ;; Guard against old versions
  (defvar ps-underlined-faces nil)
  (defvar ps-bold-faces nil)
  (defvar ps-italic-faces nil)
  (setq ps-bold-faces
	(append '(font-lock-emphasized-face
		  font-lock-keyword-face 
		  font-lock-variable-name-face 
		  font-lock-reference-face 
		  font-lock-other-emphasized-face) 
		ps-bold-faces))
  (setq ps-italic-faces
	(append '(font-lock-other-type-face
		  font-lock-reference-face 
		  font-lock-other-emphasized-face)
		ps-italic-faces))
  (setq ps-underlined-faces
	(append '(font-lock-emphasized-face
		  font-lock-other-emphasized-face 
		  font-lock-other-type-face font-lock-type-face)
		ps-underlined-faces))
  (cons 'font-lock-type-face ps-underlined-faces))


(if (cperl-enable-font-lock) (cperl-windowed-init))

(defun cperl-set-style (style)
  "Set CPerl-mode variables to use one of several different indentation styles.
The arguments are a string representing the desired style.
Available styles are GNU, K&R, BSD and Whitesmith."
  (interactive 
   (let ((list (mapcar (function (lambda (elt) (list (car elt)))) 
		       c-style-alist)))
     (list (completing-read "Enter style: " list nil 'insist))))
  (let ((style (cdr (assoc style c-style-alist))) setting str sym)
    (while style
      (setq setting (car style) style (cdr style))
      (setq str (symbol-name (car setting)))
      (and (string-match "^c-" str)
	   (setq str (concat "cperl-" (substring str 2)))
	   (setq sym (intern-soft str))
	   (boundp sym)
	   (set sym (cdr setting))))))

(defun cperl-check-syntax ()
  (interactive)
  (require 'mode-compile)
  (let ((perl-dbg-flags "-wc"))
    (mode-compile)))

(defun cperl-info-buffer ()
  ;; Returns buffer with documentation. Creats if missing
  (let ((info (get-buffer "*info-perl*")))
    (if info info
      (save-window-excursion
	;; Get Info running
	(require 'info)
	(save-window-excursion
	  (info))
	(Info-find-node cperl-info-page "perlfunc")
	(set-buffer "*info*")
	(rename-buffer "*info-perl*")
	(current-buffer)))))

(defun cperl-word-at-point (&optional p)
  ;; Returns the word at point or at P.
  (save-excursion
    (if p (goto-char p))
    (require 'etags)
    (funcall (or (and (boundp 'find-tag-default-function)
		      find-tag-default-function)
		 (get major-mode 'find-tag-default-function)
		 ;; XEmacs 19.12 has `find-tag-default-hook'; it is
		 ;; automatically used within `find-tag-default':
		 'find-tag-default))))

(defun cperl-info-on-command (command)
  "Shows documentation for Perl command in other window."
  (interactive 
   (let* ((default (cperl-word-at-point))
	  (read (read-string 
		     (format "Find doc for Perl function (default %s): " 
			     default))))
     (list (if (equal read "") 
		   default 
		 read))))

  (let ((buffer (current-buffer))
	(cmd-desc (concat "^" (regexp-quote command) "[^a-zA-Z_0-9]")) ; "tr///"
	pos)
    (if (string-match "^-[a-zA-Z]$" command)
	(setq cmd-desc "^-X[ \t\n]"))
    (set-buffer (cperl-info-buffer))
    (beginning-of-buffer)
    (re-search-forward "^-X[ \t\n]")
    (forward-line -1)
    (if (re-search-forward cmd-desc nil t)
	(progn
	  (setq pos (progn (beginning-of-line)
			   (point)))
	  (pop-to-buffer (cperl-info-buffer))
	  (set-window-start (selected-window) pos))
      (message "No entry for %s found." command))
    (pop-to-buffer buffer)))

(defun cperl-info-on-current-command ()
  "Shows documentation for Perl command at point in other window."
  (interactive)
  (cperl-info-on-command (cperl-word-at-point)))

(defun cperl-imenu-info-imenu-search ()
  (if (looking-at "^-X[ \t\n]") nil
    (re-search-backward
     "^\n\\([-a-zA-Z]+\\)[ \t\n]")
    (forward-line 1)))

(defun cperl-imenu-info-imenu-name ()  
  (buffer-substring
   (match-beginning 1) (match-end 1)))

(defun cperl-imenu-on-info ()
  (interactive)
  (let* ((buffer (current-buffer))
	 imenu-create-index-function
	 imenu-prev-index-position-function 
	 imenu-extract-index-name-function 
	 (index-item (save-restriction
		       (save-window-excursion
			 (set-buffer (cperl-info-buffer))
			 (setq imenu-create-index-function 
			       'imenu-default-create-index-function
			       imenu-prev-index-position-function
			       'cperl-imenu-info-imenu-search
			       imenu-extract-index-name-function
			       'cperl-imenu-info-imenu-name)
			 (imenu-choose-buffer-index)))))
    (and index-item
	 (progn
	   (push-mark)
	   (pop-to-buffer "*info-perl*")
	   (cond
	    ((markerp (cdr index-item))
	     (goto-char (marker-position (cdr index-item))))
	    (t
	     (goto-char (cdr index-item))))
	   (set-window-start (selected-window) (point))
	   (pop-to-buffer buffer)))))

(defun cperl-lineup (beg end &optional step minshift)
  "Lineup construction in a region.
Beginning of region should be at the start of a construction.
All first occurences of this construction in the lines that are
partially contained in the region are lined up at the same column.

MINSHIFT is the minimal amount of space to insert before the construction.
STEP is the tabwidth to position constructions.
If STEP is `nil', `cperl-lineup-step' will be used 
\(or `cperl-indent-level', if `cperl-lineup-step' is `nil').
Will not move the position at the start to the left."
  (interactive "r")
  (let (search col tcol seen b e)
    (save-excursion
      (goto-char end)
      (end-of-line)
      (setq end (point-marker))
      (goto-char beg)
      (skip-chars-forward " \t\f")
      (setq beg (point-marker))
      (indent-region beg end nil)
      (goto-char beg)
      (setq col (current-column))
      (if (looking-at "[a-zA-Z0-9_]")
	  (if (looking-at "\\<[a-zA-Z0-9_]+\\>")
	      (setq search
		    (concat "\\<" 
			    (regexp-quote 
			     (buffer-substring (match-beginning 0)
					       (match-end 0))) "\\>"))
	    (error "Cannot line up in a middle of the word"))
	(if (looking-at "$")
	    (error "Cannot line up end of line"))
	(setq search (regexp-quote (char-to-string (following-char)))))
      (setq step (or step cperl-lineup-step cperl-indent-level))
      (or minshift (setq minshift 1))
      (while (progn
	       (beginning-of-line 2)
	       (and (< (point) end) 
		    (re-search-forward search end t)
		    (goto-char (match-beginning 0))))
	(setq tcol (current-column) seen t)
	(if (> tcol col) (setq col tcol)))
      (or seen
	  (error "The construction to line up occured only once"))
      (goto-char beg)
      (setq col (+ col minshift))
      (if (/= (% col step) 0) (setq step (* step (1+ (/ col step)))))
      (while 
	  (progn
	    (setq e (point))
	    (skip-chars-backward " \t")
	    (delete-region (point) e)
	    (indent-to-column col); (make-string (- col (current-column)) ?\ ))
	    (beginning-of-line 2) 
	    (and (< (point) end) 
		 (re-search-forward search end t)
		 (goto-char (match-beginning 0)))))))) ; No body

(defun cperl-etags (&optional add all files)
  "Run etags with appropriate options for Perl files.
If optional argument ALL is `recursive', will process Perl files
in subdirectories too."
  (interactive)
  (let ((cmd "etags")
	(args '("-l" "none" "-r" "/\\<\\(package\\|sub\\)[ \\t]+\\(\\([a-zA-Z0-9:_]*::\\)?\\([a-zA-Z0-9_]+\\)[ \\t]*\\([{#]\\|$\\)\\)/\\4/"))
	res)
    (if add (setq args (cons "-a" args)))
    (or files (setq files (list buffer-file-name)))
    (cond
     ((eq all 'recursive)
      ;;(error "Not implemented: recursive")
      (setq args (append (list "-e" 
			       "sub wanted {push @ARGV, $File::Find::name if /\\.[Pp][Llm]$/}
				use File::Find;
				find(\\&wanted, '.');
				exec @ARGV;" 
			       cmd) args)
	    cmd "perl"))
     (all 
      ;;(error "Not implemented: all")
      (setq args (append (list "-e" 
			       "push @ARGV, <*.PL *.pl *.pm>;
				exec @ARGV;" 
			       cmd) args)
	    cmd "perl"))
     (t
      (setq args (append args files))))
    (setq res (apply 'call-process cmd nil nil nil args))
    (or (eq res 0)
	(message "etags returned \"%s\"" res))))

(defun cperl-toggle-auto-newline ()
  "Toggle the state of `cperl-auto-newline'."
  (interactive)
  (setq cperl-auto-newline (not cperl-auto-newline))
  (message "Newlines will %sbe auto-inserted now." 
	   (if cperl-auto-newline "" "not ")))

(defun cperl-toggle-abbrev ()
  "Toggle the state of automatic keyword expansion in CPerl mode."
  (interactive)
  (abbrev-mode (if abbrev-mode 0 1))
  (message "Perl control structure will %sbe auto-inserted now." 
	   (if abbrev-mode "" "not ")))


(defun cperl-toggle-electric ()
  "Toggle the state of parentheses doubling in CPerl mode."
  (interactive)
  (setq cperl-electric-parens (if (cperl-val 'cperl-electric-parens) 'null t))
  (message "Parentheses will %sbe auto-doubled now." 
	   (if (cperl-val 'cperl-electric-parens) "" "not ")))

;;;; Tags file creation.

(defvar cperl-tmp-buffer " *cperl-tmp*")

(defun cperl-setup-tmp-buf ()
  (set-buffer (get-buffer-create cperl-tmp-buffer))
  (set-syntax-table cperl-mode-syntax-table)
  (buffer-disable-undo)
  (auto-fill-mode 0))

(defun cperl-xsub-scan ()
  (require 'cl)
  (require 'imenu)
  (let ((index-alist '()) 
	(prev-pos 0) index index1 name package prefix)
    (goto-char (point-min))
    (imenu-progress-message prev-pos 0)
    ;; Search for the function
    (progn ;;save-match-data
      (while (re-search-forward
	      "^\\([ \t]*MODULE\\>[^\n]*\\<PACKAGE[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9:]*\\)\\>\\|\\([a-zA-Z_][a-zA-Z_0-9]*\\)(\\|[ \t]*BOOT:\\)"
	      nil t)
	(imenu-progress-message prev-pos)
	(cond
	 ((match-beginning 2)	; SECTION
	  (setq package (buffer-substring (match-beginning 2) (match-end 2)))
	  (goto-char (match-beginning 0))
	  (skip-chars-forward " \t")
	  (forward-char 1)
	  (if (looking-at "[^\n]*\\<PREFIX[ \t]*=[ \t]*\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\>")
	      (setq prefix (buffer-substring (match-beginning 1) (match-end 1)))
	    (setq prefix nil)))
	 ((not package) nil)		; C language section
	 ((match-beginning 3)		; XSUB
	  (goto-char (1+ (match-beginning 3)))
	  (setq index (imenu-example--name-and-position))
	  (setq name (buffer-substring (match-beginning 3) (match-end 3)))
	  (if (and prefix (string-match (concat "^" prefix) name))
	      (setq name (substring name (length prefix))))
	  (cond ((string-match "::" name) nil)
		(t
		 (setq index1 (cons (concat package "::" name) (cdr index)))
		 (push index1 index-alist)))
	  (setcar index name)
	  (push index index-alist))
	 (t				; BOOT: section
	  ;; (beginning-of-line)
	  (setq index (imenu-example--name-and-position))
	  (setcar index (concat package "::BOOT:"))
	  (push index index-alist)))))
    (imenu-progress-message prev-pos 100)
    ;;(setq index-alist 
    ;;      (if (default-value 'imenu-sort-function)
    ;;          (sort index-alist (default-value 'imenu-sort-function))
    ;;          (nreverse index-alist)))
    index-alist))

(defun cperl-find-tags (file xs)
  (let (ind (b (get-buffer cperl-tmp-buffer)) lst elt pos ret)
    (save-excursion
      (if b (set-buffer b)
	  (cperl-setup-tmp-buf))
      (erase-buffer)
      (setq file (car (insert-file-contents file)))
      (message "Scanning file %s..." file)
      (if xs
	  (setq lst (cperl-xsub-scan))
	(setq ind (imenu-example--create-perl-index))
	(setq lst (cdr (assoc "+Unsorted List+..." ind))))
      (setq lst 
	    (mapcar 
	     (function 
	      (lambda (elt)
		(cond ((string-match "^[_a-zA-Z]" (car elt))
		       (goto-char (cdr elt))
		       (list (car elt) 
			     (point) (count-lines 1 (point))
			     (buffer-substring (progn
						 (skip-chars-forward 
						  ":_a-zA-Z0-9")
						 (or (eolp) (forward-char 1))
						 (point))
					       (progn
						 (beginning-of-line)
						 (point))))))))
		    lst))
      (erase-buffer)
      (while lst
	(setq elt (car lst) lst (cdr lst))
	(if elt
	    (progn
	      (insert (elt elt 3) 
		      127
		      (if (string-match "^package " (car elt))
			  (substring (car elt) 8)
			(car elt) )
		      1
		      (number-to-string (elt elt 1))
		      ","
		      (number-to-string (elt elt 2))
		      "\n")
	      (if (and (string-match "^[_a-zA-Z]+::" (car elt))
		       (string-match "^sub[ \t]+\\([_a-zA-Z]+\\)[^:_a-zA-Z]"
				     (elt elt 3)))
		  ;; Need to insert the name without package as well
		  (setq lst (cons (cons (substring (elt elt 3) 
						   (match-beginning 1)
						   (match-end 1))
					(cdr elt))
				  lst))))))
      (setq pos (point))
      (goto-char 1)
      (insert "\f\n" file "," (number-to-string (1- pos)) "\n")
      (setq ret (buffer-substring 1 (point-max)))
      (erase-buffer)
      (message "Scanning file %s finished" file)
      ret)))

(defun cperl-write-tags (&optional file erase recurse dir inbuffer)
  ;; If INBUFFER, do not select buffer, and do not save
  ;; If ERASE is `ignore', do not erase, and do not try to delete old info.
  (require 'etags)
  (if file nil
    (setq file (if dir default-directory (buffer-file-name)))
    (if (and (not dir) (buffer-modified-p)) (error "Save buffer first!")))
  (let ((tags-file-name "TAGS")
	(case-fold-search (eq system-type 'emx))
	xs)
    (save-excursion
      (cond (inbuffer nil)		; Already there
	    ((file-exists-p tags-file-name)
	     (visit-tags-table-buffer tags-file-name))
	    (t (set-buffer (find-file-noselect tags-file-name))))
      (cond
       (dir
	(cond ((eq erase 'ignore))
	      (erase
	       (erase-buffer)
	       (setq erase 'ignore)))
	(let ((files 
	       (directory-files file t (if recurse nil "\\.[Pp][Llm]$") t)))
	  (mapcar (function (lambda (file)
			      (cond
			       ((string-match "/\\.\\.?$" file) nil)
			       ((not (file-directory-p file))
				(if (string-match "\\.\\([Pp][Llm]\\|xs\\)$" file)
				    (cperl-write-tags file erase recurse nil t)))
			       ((not recurse) nil)
			       (t (cperl-write-tags file erase recurse t t)))))
		  files))
	)
       (t
	(setq xs (string-match "\\.xs$" file))
	(cond ((eq erase 'ignore) nil)
	      (erase (erase-buffer))
	      (t
	       (goto-char 1)
	       (if (search-forward (concat "\f\n" file ",") nil t)
		   (progn
		     (search-backward "\f\n")
		     (delete-region (point)
				    (progn 
				      (forward-char 1)
				      (search-forward "\f\n" nil 'toend)
				      (point)))
		     (goto-char 1)))))
	(insert (cperl-find-tags file xs))))
      (if inbuffer nil		; Delegate to the caller
	(save-buffer 0)		; No backup
	(initialize-new-tags-table)))))

(defvar cperl-tags-hier-regexp-list
  "^\\(\\(package\\)\\>\\|sub\\>[^\n]+::\\|[a-zA-Z_][a-zA-Z_0-9:]*(\C-?[^\n]+::\\|[ \t]*BOOT:\C-?[^\n]+::\\)")

(defvar cperl-hierarchy '(() ())
  "Global hierarchy of classes")

(defun cperl-tags-hier-fill ()
  ;; Suppose we are in a tag table cooked by cperl.
  (goto-char 1)
  (let (type pack name pos line chunk ord cons1 file str info fileind)
    (while (re-search-forward cperl-tags-hier-regexp-list nil t)
      (setq pos (match-beginning 0) 
	    pack (match-beginning 2))
      (beginning-of-line)
      (if (looking-at "\\([^\n]+\\)\C-?\\([^\n]+\\)\C-a\\([0-9]+\\),\\([0-9]+\\)")
	  (progn
	    (setq ;;str (buffer-substring (match-beginning 1) (match-end 1))
		  name (buffer-substring (match-beginning 2) (match-end 2))
		  ;;pos (buffer-substring (match-beginning 3) (match-end 3))
		  line (buffer-substring (match-beginning 4) (match-end 4))
		  ord (if pack 1 0)
		  info (etags-snarf-tag) ; Moves to beginning of the next line
		  file (file-of-tag)
		  fileind (format "%s:%s" file line))
	    ;; Move back
	    (forward-char -1)
	    ;; Make new member of hierarchy name ==> file ==> pos if needed
	    (if (setq cons1 (assoc name (nth ord cperl-hierarchy)))
		;; Name known
		(setcdr cons1 (cons (cons fileind (vector file info))
				    (cdr cons1)))
	      ;; First occurence of the name, start alist
	      (setq cons1 (cons name (list (cons fileind (vector file info)))))
	      (if pack 
		  (setcar (cdr cperl-hierarchy)
			  (cons cons1 (nth 1 cperl-hierarchy)))
		(setcar cperl-hierarchy
			(cons cons1 (car cperl-hierarchy)))))))
      (end-of-line))))

(defun cperl-tags-hier-init (&optional update)
  "Show hierarchical menu of classes and methods.
Finds info about classes by a scan of loaded TAGS files.
Supposes that the TAGS files contain fully qualified function names.
One may build such TAGS files from CPerl mode menu."
  (interactive)
  (require 'etags)
  (require 'imenu)
  (if (or update (null (nth 2 cperl-hierarchy)))
      (let (pack name cons1 to l1 l2 l3 l4
		 (remover (function (lambda (elt) ; (name (file1...) (file2..))
				      (or (nthcdr 2 elt)
					  ;; Only in one file
					  (setcdr elt (cdr (nth 1 elt))))))))
	;; (setq cperl-hierarchy '(() () ())) ; Would write into '() later!
	(setq cperl-hierarchy (list l1 l2 l3))
	(or tags-table-list
	    (call-interactively 'visit-tags-table))
	(message "Updating list of classes...")
	(mapcar 
	 (function
	  (lambda (tagsfile)
	    (set-buffer (get-file-buffer tagsfile))
	    (cperl-tags-hier-fill)))
	 tags-table-list)
	(mapcar remover (car cperl-hierarchy))
	(mapcar remover (nth 1 cperl-hierarchy))
	(setq to (list nil (cons "Packages: " (nth 1 cperl-hierarchy))
		       (cons "Methods: " (car cperl-hierarchy))))
	(cperl-tags-treeify to 1)
	(setcar (nthcdr 2 cperl-hierarchy)
		(cperl-menu-to-keymap (cons '("+++UPDATE+++" . -999) (cdr to))))
	(message "Updating list of classes: done, requesting display...")
	;;(cperl-imenu-addback (nth 2 cperl-hierarchy))
	))
  (or (nth 2 cperl-hierarchy)
      (error "No items found"))
  (setq update
;;;	(imenu-choose-buffer-index "Packages: " (nth 2 cperl-hierarchy))
	(if window-system
	    (x-popup-menu t (nth 2 cperl-hierarchy))
	  (require 'tmm)
	  (tmm-prompt t (nth 2 cperl-hierarchy))))
  (if (and update (listp update))
      (progn (while (cdr update) (setq update (cdr update)))
	     (setq update (car update)))) ; Get the last from the list
  (if (vectorp update) 
      (progn
	(find-file (elt update 0))
	(etags-goto-tag-location (elt update 1))))
  (if (eq update -999) (cperl-tags-hier-init t)))

(defun cperl-tags-treeify (to level)
  ;; cadr of to is read-write. On start it is a cons
  (let* ((regexp (concat "^\\(" (mapconcat 
				 'identity
				 (make-list level "[_a-zA-Z0-9]+")
				 "::")
			 "\\)\\(::\\)?"))
	 (packages (cdr (nth 1 to)))
	 (methods (cdr (nth 2 to)))
	 l1 head tail cons1 cons2 ord writeto packs recurse
	 root-packages root-functions ms many_ms same_name ps
	 (move-deeper
	  (function 
	   (lambda (elt)
	     (cond ((and (string-match regexp (car elt))
			 (or (eq ord 1) (match-end 2)))
		    (setq head (substring (car elt) 0 (match-end 1))
			  tail (if (match-end 2) (substring (car elt) 
							    (match-end 2)))
			  recurse t)
		    (if (setq cons1 (assoc head writeto)) nil
		      ;; Need to init new head
		      (setcdr writeto (cons (list head (list "Packages: ")
						  (list "Methods: "))
					    (cdr writeto)))
		      (setq cons1 (nth 1 writeto)))
		    (setq cons2 (nth ord cons1)) ; Either packs or meths
		    (setcdr cons2 (cons elt (cdr cons2))))
		   ((eq ord 2)
		    (setq root-functions (cons elt root-functions)))
		   (t
		    (setq root-packages (cons elt root-packages))))))))
    (setcdr to l1)			; Init to dynamic space
    (setq writeto to)
    (setq ord 1)
    (mapcar move-deeper packages)
    (setq ord 2)
    (mapcar move-deeper methods)
    (if recurse
	(mapcar (function (lambda (elt)
			  (cperl-tags-treeify elt (1+ level))))
		(cdr to)))
    ;; Now add back functions removed from display
    (mapcar (function (lambda (elt)
			(setcdr to (cons elt (cdr to)))))
	    root-functions)
    ;; Now add back packages removed from display
    (mapcar (function (lambda (elt)
			(setcdr to (cons (cons (concat "package " (car elt)) 
					       (cdr elt)) 
					 (cdr to)))))
	    root-packages)
    ;;Now clean up leaders with one child only
    (mapcar (function (lambda (elt)
			(if (not (and (listp (cdr elt)) 
				      (eq (length elt) 2))) nil
			    (setcar elt (car (nth 1 elt)))
			    (setcdr elt (cdr (nth 1 elt))))))
	    (cdr to))
    ))

;;;(x-popup-menu t
;;;   '(keymap "Name1" 
;;;	    ("Ret1" "aa")
;;;	    ("Head1" "ab"  
;;;	     keymap "Name2" 
;;;	     ("Tail1" "x") ("Tail2" "y"))))

(defun cperl-list-fold (list name limit)
  (let (list1 list2 elt1 (num 0))
    (if (<= (length list) limit) list
      (setq list1 nil list2 nil)
      (while list
	(setq num (1+ num) 
	      elt1 (car list)
	      list (cdr list))
	(if (<= num imenu-max-items)
	    (setq list2 (cons elt1 list2))
	  (setq list1 (cons (cons name
				  (nreverse list2))
			    list1)
		list2 (list elt1)
		num 1)))
      (nreverse (cons (cons name
			    (nreverse list2))
		      list1)))))

(defun cperl-menu-to-keymap (menu &optional name)
  (let (list)
    (cons 'keymap 
	  (mapcar 
	   (function 
	    (lambda (elt)
	      (cond ((listp (cdr elt))
		     (setq list (cperl-list-fold
				 (cdr elt) (car elt) imenu-max-items))
		     (cons nil
			   (cons (car elt)
				 (cperl-menu-to-keymap list))))
		    (t
		     (list (cdr elt) (car elt))))))
	   (cperl-list-fold menu "Root" imenu-max-items)))))


(defvar cperl-bad-style-regexp
  (mapconcat 'identity
   '("[^-\n\t <>=+!.&|(*/'`\"#^][-=+<>!|&^]" ; char sign
     "[-<>=+^&|]+[^- \t\n=+<>~]"	; sign+ char
     )
   "\\|")
  "Finds places such that insertion of a whitespace may help a lot.")

(defvar cperl-not-bad-style-regexp 
  (mapconcat 'identity
   '("[^-\t <>=+]\\(--\\|\\+\\+\\)"	; var-- var++
     "[a-zA-Z0-9][|&][a-zA-Z0-9$]"	; abc|def abc&def are often used.
     "&[(a-zA-Z0-9$]"			; &subroutine &(var->field)
     "<\\$?\\sw+\\(\\.\\sw+\\)?>"	; <IN> <stdin.h>
     "-[a-zA-Z][ \t]+[_$\"'`]"		; -f file
     "-[0-9]"				; -5
     "\\+\\+"				; ++var
     "--"				; --var
     ".->"				; a->b
     "->"				; a SPACE ->b
     "\\[-"				; a[-1]
     "^="				; =head
     "||"
     "&&"
     "[CBIXSLFZ]<\\(\\sw\\|\\s \\|\\s_\\|[\n]\\)*>" ; C<code like text>
     "-[a-zA-Z0-9]+[ \t]*=>"			; -option => value
     ;; Unaddressed trouble spots: = -abc, f(56, -abc) --- specialcased below
     ;;"[*/+-|&<.]+="
     )
   "\\|")
  "If matches at the start of match found by `my-bad-c-style-regexp',
insertion of a whitespace will not help.")

(defvar found-bad)

(defun cperl-find-bad-style ()
  "Find places in the buffer where insertion of a whitespace may help.
Prompts user for insertion of spaces.
Currently it is tuned to C and Perl syntax."
  (interactive)
  (let (found-bad (p (point)))
    (setq last-nonmenu-event 13)	; To disable popup
    (beginning-of-buffer)
    (map-y-or-n-p "Insert space here? "
		  (function (lambda (arg) (insert " ")))
		  'cperl-next-bad-style
		  '("location" "locations" "insert a space into") 
		  '((?\C-r (lambda (arg)
			     (let ((buffer-quit-function
				    'exit-recursive-edit))
			       (message "Exit with Esc Esc")
			       (recursive-edit)
			       t))	; Consider acted upon
			   "edit, exit with Esc Esc") 
		    (?e (lambda (arg)
			  (let ((buffer-quit-function
				 'exit-recursive-edit))
			    (message "Exit with Esc Esc")
			    (recursive-edit)
			    t))		; Consider acted upon
			"edit, exit with Esc Esc"))
		  t)
    (if found-bad (goto-char found-bad)
      (goto-char p)
      (message "No appropriate place found"))))

(defun cperl-next-bad-style ()
  (let (p (not-found t) (point (point)) found)
    (while (and not-found
		(re-search-forward cperl-bad-style-regexp nil 'to-end))
      (setq p (point))
      (goto-char (match-beginning 0))
      (if (or
	   (looking-at cperl-not-bad-style-regexp)
	   ;; Check for a < -b and friends
	   (and (eq (following-char) ?\-)
		(save-excursion
		  (skip-chars-backward " \t\n")
		  (memq (preceding-char) '(?\= ?\> ?\< ?\, ?\(, ?\[, ?\{))))
	   ;; Now check for syntax type
	   (save-match-data
	     (setq found (point))
	     (beginning-of-defun)
	     (let ((pps (parse-partial-sexp (point) found)))
	       (or (nth 3 pps) (nth 4 pps) (nth 5 pps)))))
	  (goto-char (match-end 0))
	(goto-char (1- p))
	(setq not-found nil
	      found-bad found)))
    (not not-found)))