prog-modes / p4.el

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
;;; p4.el --- Simple Perforce-Emacs Integration
;;
;; $Id$

;;; Commentary:
;;
;;    Applied the GNU G.P.L. to this file - rv 3/27/1997

;;    Programs for  Emacs <-> Perforce Integration.
;;    Copyright (C) 1996, 1997	Eric Promislow
;;    Copyright (C) 1997-2003	Rajesh Vaidheeswarran
;;
;;    This program 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 of the License, or
;;    (at your option) any later version.
;;
;;    This program 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 this program; if not, write to the Free Software
;;    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;
;;    If you have any problems to report, or suggestions, please send them
;;    to p4el-bugs@lists.sourceforge.net

;; LCD Archive Entry:
;; p4|Rajesh Vaidheeswarran|rv@NoSpAm.lOsEtHiS.dsmit.com|
;; P4 SCM Integration into Emacs/XEmacs|
;; 2003/09/12|10.3|not_assigned_yet|

;; WARNING:
;; --------
;;
;;    % p4 edit foo.c
;;    ... make changes to foo.c in emacs
;;    % p4 submit
;;     ... keep the writable copy of foo.c in emacs.  Start making changes
;;     to it.  Discover that you can't save it.	 If you do M-x:p4-edit,
;;     you'll lose your changes.  You need to do a 'p4 edit' at the
;;     command-line.
;;

;; NOTES:
;; ------
;;
;; It is best if you take this file and byte compile it. To do that, you
;; need to do the following:
;;
;; % emacs -batch -f batch-byte-compile /full/path/to/file/p4.el
;;
;; This creates a binary file p4.elc in the path. Add the path to your
;; load-path variable in .emacs like this:
;;
;; (setq load-path (cons "/full/path/to/file" load-path))
;;
;; Then add the library like this:
;;
;; (load-library "p4")
;;

;;; Code:

(defvar p4-emacs-version "10.3" "The Current P4-Emacs Integration Revision.")

;; Find out what type of emacs we are running in. We will be using this
;; quite a few times in this program.
(eval-and-compile
  (defvar p4-running-emacs nil
    "If the current Emacs is not XEmacs, then, this is non-nil.")
  (defvar p4-running-xemacs nil
    "If the current Emacs is XEmacs/Lucid, then, this is non-nil.")
  (if (string-match "XEmacs\\|Lucid" emacs-version)
      (setq p4-running-xemacs t)
    (setq p4-running-emacs t)))

;; Pick up a couple of missing function defs
(if p4-running-xemacs
    (eval-when-compile
      (require 'timer)
      (require 'dired)))

(defvar p4-emacs-maintainer
  "p4.el maintainers <p4el-bugs@lists.sourceforge.net>"
  "The maintainer(s) of the emacs-p4 integration. Used for bug reports.")

(defvar p4-web-page "http://p4el.sourceforge.net/" "The home of p4.el.")

;; For flavors of Emacs which don't define `defgroup' and `defcustom'.
(eval-when-compile
  (if (not (fboundp 'defgroup))
      (defmacro defgroup (sym memb doc &rest args)
	"Null macro for defgroup in all versions of Emacs that don't define
defgroup"
	t))
  (if (not (fboundp 'defcustom))
      (defmacro defcustom (sym val doc &rest args)
	"Macro to alias defcustom to defvar in all versions of Emacs that
don't define defcustom"
	`(defvar ,sym ,val ,doc))))

(defgroup p4 nil "Perforce VC System." :group 'tools)

;; This can be set to wherever 'p4' lies using p4-set-p4-executable
(eval-and-compile
  (defun p4-windows-os ()
    (memq system-type '(ms-dos windows-nt)))

  (defcustom p4-executable
    (let ((lst (append
		exec-path
		(list "/usr/local/bin/p4"
		      (concat (getenv "HOME") "/bin/p4")
		      "p4")))
	  (p4-progname (if (p4-windows-os) "p4.exe" "p4"))
	  p4ex)
      (while (and lst (not p4ex))
	(let ((tmp (concat (file-name-as-directory (car lst))
			   p4-progname)))
	  (if (and (file-executable-p tmp)
		   (not (file-directory-p tmp)))
	      (setq p4ex tmp))
	  (setq lst (cdr lst))))
      p4ex)
    "This is the p4 executable.
To set this, use the function  `p4-set-p4-executable' or `customize'"
    :type 'string
    :group 'p4))

;; This is a string with default arguments to pass to "p4 diff",
;; "p4 diff2", "p4 describe", etc.
(defcustom p4-default-diff-options "-du"
  "Type of p4 diff output to be displayed. \(regular or context or
unified.\)"
  :type 'string
  :group 'p4)

(defcustom p4-default-depot-completion-prefix "//depot/"
  "Prefix to be used for completion prompt when prompting user for a depot
file."
  :type 'string
  :group 'p4)

;; Set this variable to nil to turn off colorized diff buffers.
(defcustom p4-colorized-diffs t
  "Set this to nil to disable colorized diffs."
  :type 'boolean
  :group 'p4)

;; Set whether P4CONFIG should be used exclusively for VC checking
(defcustom p4-use-p4config-exclusively nil
  "Whether P4 mode should use P4CONFIG exclusively to check whether a file
is under P4 version control. If set to nil, `p4-check-mode' is always
called; otherwise, it checks to see if the file named by P4CONFIG exists in
this or a parent directory, and if so, only then runs p4-check-mode.

This provides for a much faster `p4-find-file-hook'."
  :type 'boolean
  :group 'p4)

;; Auto-refresh?
(defcustom p4-auto-refresh t
  "Set this to automatically refresh p4 submitted files in buffers."
  :type 'boolean
  :group 'p4)

;; Check for empty diffs at submit time
(defcustom p4-check-empty-diffs t
  "Set this to check for files with empty diffs before submitting."
  :type 'boolean
  :group 'p4)

(defcustom p4-verbose t
  "When set, p4 will pop up the output buffer with the result of the
command."
  :type 'boolean
  :group 'p4)

;; Follow Symlinks?
(defcustom p4-follow-symlinks nil
  "When set, p4 will call `file-truename' on all opened files."
  :type 'boolean
  :group 'p4)

(defcustom p4-mode-hook nil
  "Hook run by `p4-mode'."
  :type 'sexp
  :group 'p4)

(eval-and-compile
  (defvar p4-output-buffer-name "*P4 Output*" "P4 Output Buffer."))

;; Set this variable in .emacs if you want p4-set-client-name to complete
;; your client name for you.
(defvar p4-my-clients nil
  "This variable holds the alist of p4 clients that the function
`p4-set-client-name' can complete on.

Set this variable *only* if you don't want P4 to complete on all the clients
in the P4 server.

This is a alist, and should be set using the function
`p4-set-my-clients'. For example, in your .emacs:

\(load-library \"p4\"\)
\(p4-set-my-clients \'(client1 client2 client3)\)")

;; Set this variable in .emacs if you want to alter the completion
;; behavior of p4-set-client-name.

(defcustom p4-strict-complete t
  "Set this variable in .emacs \(or using `customize'\) if you want to alter
the completion behavior of `p4-set-client-name'.
"
  :type 'boolean
  :group 'p4)

(if (not (getenv "P4PORT"))
    (setenv "P4PORT" "perforce:1666"))

(defvar p4-notify-list (getenv "P4NOTIFY") "The P4 Notify List.")

(defcustom p4-sendmail-program (if (boundp 'sendmail-program)
				   sendmail-program
				 nil)
  "The sendmail program. To set this use `customize'."
  :type 'string
  :group 'p4)

(defcustom p4-user-email (if (boundp 'user-mail-address)
			     user-mail-address nil)
  "The e-mail address of the current user. This is used with the
notification system, and must be set if notification should take place. To
set this, use `customize'."
  :type 'string
  :group 'p4)

(defcustom p4-notify nil
  "If this is t then the users in the notification list set by
`p4-set-notify-list' will get a notification of any P4 change submitted from
within emacs."
  :type 'boolean
  :group 'p4)

;; This can be set with p4-toggle-vc-mode
(defcustom p4-do-find-file t
  "If non-nil, the `p4-find-file-hook' will run when opening files."
  :type 'boolean
  :group 'p4)

;; Now add a hook to find-file-hooks
(add-hook 'find-file-hooks 'p4-find-file-hook)
;; .. and one to kill-buffer-hook
(add-hook 'kill-buffer-hook 'p4-kill-buffer-hook)

;; Tell Emacs about this new kind of minor mode
(defvar p4-mode nil "Is this file under p4?")
(make-variable-buffer-local 'p4-mode)
(put 'p4-mode 'permanent-local t)

(defvar p4-offline-mode nil "Is this file under p4 but handled in offline mode?")
(make-variable-buffer-local 'p4-offline-mode)
(put 'p4-offline-mode 'permanent-local t)

(defvar p4-minor-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-x\C-q" 'p4-toggle-read-only)
    map)
  "Keymap for p4 minor mode")
(fset 'p4-minor-map p4-minor-map)
(or (assoc 'p4-mode minor-mode-alist)
    (setq minor-mode-alist (cons '(p4-mode p4-mode)
				 minor-mode-alist)))
(or (assoc 'p4-mode minor-mode-map-alist)
    (setq minor-mode-map-alist
	  (cons '(p4-mode . p4-minor-map) minor-mode-map-alist)))
(or (assoc 'p4-offline-mode minor-mode-alist)
    (setq minor-mode-alist (cons '(p4-offline-mode p4-offline-mode)
				 minor-mode-alist)))
(or (assoc 'p4-offline-mode minor-mode-map-alist)
    (setq minor-mode-map-alist
	  (cons '(p4-offline-mode . p4-minor-map) minor-mode-map-alist)))

(defvar p4-async-minor-mode nil
  "The minor mode for editing p4 asynchronous command buffers.")
(make-variable-buffer-local 'p4-async-minor-mode)
(defvar p4-async-minor-map (make-sparse-keymap) "Keymap for p4 async minor mode")
(fset 'p4-async-minor-map p4-async-minor-map)

(or (assoc 'p4-async-minor-mode minor-mode-alist)
    (setq minor-mode-alist
	  (cons '(p4-async-minor-mode " P4") minor-mode-alist)))

(or (assoc 'p4-async-minor-mode minor-mode-map-alist)
    (setq minor-mode-map-alist
	  (cons '(p4-async-minor-mode . p4-async-minor-map) minor-mode-map-alist)))

(defvar p4-current-command nil)
(make-variable-buffer-local 'p4-current-command)
(put 'p4-current-command 'permanent-local t)
(set-default 'p4-current-command nil)

(defvar p4-current-args nil)
(make-variable-buffer-local 'p4-current-args)
(put 'p4-current-args 'permanent-local t)
(set-default 'p4-current-args nil)

;; To check if the current buffer's modeline and menu need to be altered
(defvar p4-vc-check nil)
(make-variable-buffer-local 'p4-vc-check)
(put 'p4-vc-check 'permanent-local t)
(set-default 'p4-vc-check nil)

(defvar p4-set-client-hooks nil
  "List of functions to be called after a p4 client is changed.
The buffer's local variables (if any) will have been processed before the
functions are called.")

(if p4-running-emacs (require 'timer))

(defvar p4-timer nil "Timer object that will be set to cleanup the caches
periodically.")

(defcustom p4-cleanup-time 600 "seconds after which `p4-cache-cleanup' will
check for dirty caches."
  :type 'integer
  :group 'p4)

(defcustom p4-cleanup-cache t "`p4-cache-cleanup' will cleanup the
branches/clients/dirs/labels caches once in a while if this is non-nil."
  :type 'boolean
  :group 'p4)

(defvar p4-all-buffer-files nil "An associated list of all buffers and
their files under p4 version control. This is to enable autorefreshing of
p4 submitted files being visited by the buffer.")

(defvar p4-file-refresh-timer nil "Timer object that will be set to refresh
the files in Emacs buffers that have been modified by a `p4-submit'.")

(defcustom p4-file-refresh-timer-time 60 "seconds after which
`p4-file-refresh' will check for modified files in Emacs buffers. Set this
variable to 0 to disable periodic refreshing."
  :type 'integer
  :group 'p4)

(defvar p4-async-command-hook nil
  "This hook is run after an async buffer has been set up by
`p4-async-process-command'")

(defvar p4-window-config-stack nil
  "Stack of saved window configurations.")

(defcustom p4-window-config-stack-size 20 "Maximum stack size
for saved window configurations."
  :type 'integer
  :group 'p4)

(defcustom p4-exec-arg-len-max 20000 "Maximum total length of all
arguments to p4 commands."
  :type 'integer
  :group 'p4)

(defvar p4-basic-map
  (let ((map (make-sparse-keymap)))
    (cond (p4-running-xemacs
	   (define-key map [button2] 'p4-buffer-mouse-clicked)
	   (define-key map [button3] 'p4-buffer-mouse-clicked-3))
	  (p4-running-emacs
	   (define-key map [mouse-2] 'p4-buffer-mouse-clicked)
	   (define-key map [mouse-3] 'p4-buffer-mouse-clicked-3)))
    (define-key map [return] 'p4-buffer-commands)
    (define-key map "\r" 'p4-buffer-commands)
    (define-key map "q"	 'p4-quit-current-buffer)
    (define-key map "k"	 'p4-scroll-down-1-line)
    (define-key map "j"	 'p4-scroll-up-1-line)
    (define-key map "b"	 'p4-scroll-down-1-window)
    (define-key map [backspace] 'p4-scroll-down-1-window)
    (define-key map " "	 'p4-scroll-up-1-window)
    (define-key map "<"	 'p4-top-of-buffer)
    (define-key map ">"	 'p4-bottom-of-buffer)
    (define-key map "="	 'p4-delete-other-windows)
    map))

(defun p4-make-derived-map (base-map)
  (let (map)
    (cond (p4-running-xemacs
	   (setq map (make-sparse-keymap))
	   (set-keymap-parents map (list base-map)))
	  (p4-running-emacs
	   (setq map (cons 'keymap base-map))))
    map))

(defvar p4-filelog-map
  (let ((map (p4-make-derived-map p4-basic-map)))
    (define-key map "d"	 'p4-diff2)
    (define-key map "f"	 'p4-find-file-other-window)
    (define-key map "s"	 'p4-filelog-short-format)
    (define-key map "l"	 'p4-filelog-long-format)
    (define-key map "k"	 'p4-scroll-down-1-line-other-w)
    (define-key map "j"	 'p4-scroll-up-1-line-other-w)
    (define-key map "b"	 'p4-scroll-down-1-window-other-w)
    (define-key map [backspace] 'p4-scroll-down-1-window-other-w)
    (define-key map " "	 'p4-scroll-up-1-window-other-w)
    (define-key map "<"	 'p4-top-of-buffer-other-w)
    (define-key map ">"	 'p4-bottom-of-buffer-other-w)
    (define-key map "="	 'p4-delete-other-windows)
    (define-key map "n"	 'p4-goto-next-change)
    (define-key map "p"	 'p4-goto-prev-change)
    (define-key map "N" (lookup-key map "p"))
    map)
  "The key map to use for selecting filelog properties.")

(defvar p4-opened-map
  (let ((map (p4-make-derived-map p4-basic-map)))
    (define-key map "n"	 'p4-next-depot-file)
    (define-key map "p"	 'p4-prev-depot-file)
    (define-key map "N" (lookup-key map "p"))
    map)
  "The key map to use for selecting opened files.")

(defvar p4-diff-map
  (let ((map (p4-make-derived-map p4-basic-map)))
    (define-key map "n"	 'p4-goto-next-diff)
    (define-key map "p"	 'p4-goto-prev-diff)
    (define-key map "N" (lookup-key map "p"))
    (define-key map "d"	 'p4-next-depot-diff)
    (define-key map "u"	 'p4-prev-depot-diff)
    map))

(defvar p4-print-rev-map
  (let ((map (p4-make-derived-map p4-basic-map)))
    (define-key map "n"	 'p4-next-change-rev-line)
    (define-key map "p"	 'p4-prev-change-rev-line)
    (define-key map "N" (lookup-key map "p"))
    (define-key map "l"	 'p4-toggle-line-wrap)
    map)
  "The key map to use for browsing print-revs buffers.")

;;; All functions start here.

;; A generic function that we use to execute p4 commands
(eval-and-compile
  (defun p4-exec-p4 (output-buffer args &optional clear-output-buffer)
    "Internal function called by various p4 commands.
Executes p4 in the current buffer's current directory
with output to a dedicated output buffer.
If successful, adds the P4 menu to the current buffer.
Does auto re-highlight management (whatever that is)."
    (save-excursion
      (if (eq major-mode 'dired-mode)
	  (let ((dir (dired-current-directory)))
	    (set-buffer output-buffer)
	    (setq default-directory dir)))
      (if clear-output-buffer
	  (progn
	    (set-buffer output-buffer)
	    (delete-region (point-min) (point-max))))
      (let ((result
	     (apply 'call-process (p4-check-p4-executable) nil
		    output-buffer
		    nil			; update display?
		    "-d" default-directory  ;override "PWD" env var
		    args)))
	(p4-menu-add)
	(if (and p4-running-emacs
		 (boundp 'hilit-auto-rehighlight))
	    (setq hilit-auto-rehighlight nil))
	result)))
  (defun p4-call-p4-here (&rest args)
    "Internal function called by various p4 commands.
Executes p4 in the current buffer (generally a temp)."
    (apply 'call-process (p4-check-p4-executable) nil
	   t
	   nil			; update display?
	   "-d" default-directory  ;override "PWD" env var
	   args)))

(defun p4-push-window-config ()
  "Push the current window configuration on the `p4-window-config-stack'
stack."
  (interactive)
  (setq p4-window-config-stack
	(cons (current-window-configuration)
	      p4-window-config-stack))
  (while (> (length p4-window-config-stack) p4-window-config-stack-size)
    (setq p4-window-config-stack
	  (reverse (cdr (reverse p4-window-config-stack))))))

(defun p4-pop-window-config (num)
  "Pop `num' elements from the `p4-window-config-stack' stack and use
the last popped element to restore the window configuration."
  (interactive "p")
  (while (> num 0)
    (if (eq p4-window-config-stack nil)
	(error "window config stack empty"))
    (set-window-configuration (car p4-window-config-stack))
    (setq p4-window-config-stack (cdr p4-window-config-stack))
    (setq num (1- num)))
  (message "window config popped (stack size %d)"
	   (length p4-window-config-stack)))


;; The menu definition is in the XEmacs format. Emacs parses and converts
;; this definition to its own menu creation commands.

(defalias 'p4-toggle-vc-mode-off 'p4-toggle-vc-mode)
(defalias 'p4-toggle-vc-mode-on 'p4-toggle-vc-mode)

(eval-and-compile
  (defvar p4-menu-def
    '(["Specify Arguments..." universal-argument t]
      ["--" nil nil]
      ["Add Current to P4" p4-add
       (and (p4-buffer-file-name) (not p4-mode))]
      ["Check out/Edit"    p4-edit
       (and (p4-buffer-file-name-2) (or (not p4-mode) buffer-read-only))]
      ["Re-open"	       p4-reopen
       (and (p4-buffer-file-name-2) (or (not p4-mode) (not buffer-read-only)))]
      ["Revert File"  p4-revert
       (and (p4-buffer-file-name-2) (or (not p4-mode) (not buffer-read-only)))]
      ["Delete File from Depot"  p4-delete
       (and (p4-buffer-file-name-2) (or (not p4-mode) buffer-read-only))]
      ["Rename Depot File" p4-rename
       (and (p4-buffer-file-name-2) (or (not p4-mode) buffer-read-only))]
      ["Submit Changes"  p4-submit t]
      ["--" nil nil]
      ["Sync/Get Files from Depot" p4-get t]
      ["--" nil nil]
      ["Show Opened Files"	p4-opened t]
      ["Filelog" p4-filelog (p4-buffer-file-name-2)]
      ["Changes" p4-changes t]
      ["Describe Change" p4-describe t]
      ["--" nil nil]
      ["Diff 2 Versions" p4-diff2 (p4-buffer-file-name-2)]
      ["Diff Current" p4-diff t]
      ["Diff All Opened Files" p4-diff-all-opened t]
      ["Diff Current with Ediff"   p4-ediff
       (and (p4-buffer-file-name) (not buffer-read-only) p4-mode)]
      ["Diff 2 Versions with Ediff"   p4-ediff2 (p4-buffer-file-name-2)]
      ["--" nil nil]
      ["Schedule Integrations" p4-integ t]
      ["Resolve Conflicts" p4-resolve t]
      ["--" nil nil]
      ["Print" p4-print (p4-buffer-file-name-2)]
      ["Print with Revision History" p4-blame
       (p4-buffer-file-name-2)]
      ["Find File using Depot Spec" p4-depot-find-file
       p4-do-find-file]
      ["--" nil nil]
      ["Edit a Branch Specification" p4-branch t]
      ["Edit a Label Specification" p4-label t]
      ["Edit a Client Specification" p4-client t]
      ["Edit a User Specification" p4-user t]
      ["--" nil nil]
      ["Show Version" p4-emacs-version t]
      ["Disable P4 VC Check"  p4-toggle-vc-mode-off
       p4-do-find-file]
      ["Enable P4 VC Check"	 p4-toggle-vc-mode-on
       (not p4-do-find-file)]
      ["--" nil nil]
      ["Set P4 Config"  p4-set-client-config p4-do-find-file]
      ["Get Current P4 Config"  p4-get-client-config
       p4-do-find-file]
      ["--" nil nil]
      ["Set P4 Client"  p4-set-client-name p4-do-find-file]
      ["Get Current P4 Client"  p4-get-client-name
       p4-do-find-file]
      ["--" nil nil]
      ["Set P4 Server/Port"	 p4-set-p4-port p4-do-find-file]
      ["Get Current P4 Server/Port"	 p4-get-p4-port
       p4-do-find-file]
      ["--" nil nil]
      ["Set P4 Notification List"  p4-set-notify-list
       p4-mode]
      ["Get P4 Notification List"  p4-get-notify-list p4-notify]
      ["--" nil nil]
      ["Describe Key Bindings"  p4-describe-bindings t]
      ["Check for later versions of p4.el" p4-browse-web-page t]
      ["--" nil nil]
      ["Report Bug in p4.el"  p4-bug-report t])
    "The P4 menu definition")

  (cond (p4-running-xemacs
	 ;; Menu Support for XEmacs
	 (require 'easymenu)
	 (defun p4-mode-menu (modestr)
	   (cons modestr p4-menu-def)))

	(p4-running-emacs
	 ;; Menu support for Emacs
	 (or (lookup-key global-map [menu-bar])
	     (define-key global-map [menu-bar] (make-sparse-keymap "menu-bar")))
	 (defvar menu-bar-p4-menu (make-sparse-keymap "P4"))
	 (setq menu-bar-final-items (cons 'p4-menu menu-bar-final-items))
	 (define-key global-map [menu-bar p4-menu]
	   (cons "P4" menu-bar-p4-menu))
	 (let ((m (reverse p4-menu-def))
	       (separator-number 0))
	   (while m
	     (let ((menu-text (elt (car m) 0))
		   (menu-action (elt (car m) 1))
		   (menu-pred (elt (car m) 2)))
	       (if menu-action
		   (progn
		     (define-key menu-bar-p4-menu (vector menu-action)
		       (cons menu-text menu-action))
		     (put menu-action 'menu-enable menu-pred))
		 (define-key menu-bar-p4-menu
		   (vector (make-symbol
			    (concat "separator-"
				    (int-to-string separator-number))))
		   '("--"))
		 (setq separator-number (1+ separator-number))))
	     (setq m (cdr m))))))

  (defun p4-depot-output (command &optional args)
    "Executes p4 command inside a buffer.
Returns the buffer."
    (let ((buffer (generate-new-buffer p4-output-buffer-name)))
      (p4-exec-p4 buffer (cons command args) t)
      buffer))

  (defun p4-check-p4-executable ()
    "Check if the `p4-executable' is nil, and if so, prompt the user for a
valid `p4-executable'."
    (interactive)
    (if (not p4-executable)
	(call-interactively 'p4-set-p4-executable)
      p4-executable))

  (defun p4-menu-add ()
    "To add the P4 menu bar button for files that are already not in
the P4 depot or in the current client view.."
    (interactive)
    (cond (p4-running-xemacs
	   (if (not (boundp 'p4-mode))
	       (setq p4-mode nil))
	   (easy-menu-add (p4-mode-menu "P4"))))
    t)

  (defun p4-help-text (cmd text)
    (setq cmd nil)
    (if cmd
	(let ((buf (generate-new-buffer p4-output-buffer-name))
	      (help-text ""))
	  (if (= (p4-exec-p4 buf (list "help" cmd) t) 0)
	      (setq help-text (save-excursion
				(set-buffer buf)
				(buffer-string))))
	  (kill-buffer buf)
	  (concat text help-text))
      text))

  ;; To set the path to the p4 executable
  (defun p4-set-p4-executable (p4-exe-name)
    "Set the path to the correct P4 Executable.

To set this as a part of the .emacs, add the following to your .emacs:

\(load-library \"p4\"\)
\(p4-set-p4-executable \"/my/path/to/p4\"\)

Argument P4-EXE-NAME The new value of the p4 executable, with full path."
    (interactive "fFull path to your P4 executable: " )
    (setq p4-executable p4-exe-name)
    p4-executable))

;; The kill-buffer hook for p4.
(defun p4-kill-buffer-hook ()
  "To Remove a file and its associated buffer from our global list of P4
controlled files."
  (if p4-vc-check
      (p4-refresh-refresh-list (p4-buffer-file-name)
			       (buffer-name))))

(defmacro defp4cmd (fkn &rest all-args)
  (let ((args (car all-args))
	(help-cmd (cadr all-args))
	(help-txt (eval (cadr (cdr all-args))))
	(body (cdr (cddr all-args))))
    `(defalias ',fkn
       ,(append (list 'lambda args
		      (p4-help-text help-cmd help-txt))
		body))))

(defun p4-noinput-buffer-action (cmd
				 do-revert
				 show-output
				 &optional arguments preserve-buffer)
  "Internal function called by various p4 commands."
  (save-excursion
    (save-excursion
      (if (not preserve-buffer)
	  (progn
	    (get-buffer-create p4-output-buffer-name);; We do these two lines
	    (kill-buffer p4-output-buffer-name)))    ;; to ensure no duplicates
      (p4-exec-p4 (get-buffer-create p4-output-buffer-name)
		  (append (list cmd) arguments)
		  t))
    (p4-partial-cache-cleanup cmd)
    (if show-output
	(if (and
	     (eq show-output 's)
	     (= (save-excursion
		  (set-buffer p4-output-buffer-name)
		  (count-lines (point-min) (point-max)))
		1)
	     (not (save-excursion
		    (set-buffer p4-output-buffer-name)
		    (goto-char (point-min))
		    (looking-at "==== "))))
	    (save-excursion
	      (set-buffer p4-output-buffer-name)
	      (message (buffer-substring (point-min)
					 (save-excursion
					   (goto-char (point-min))
					   (end-of-line)
					   (point)))))
	  (p4-push-window-config)
	  (if (not (one-window-p))
	      (delete-other-windows))
	  (display-buffer p4-output-buffer-name t))))
  (if (and do-revert (p4-buffer-file-name))
      (revert-buffer t t)))

;; The p4 edit command
(defp4cmd p4-edit (show-output)
  "edit" "To open the current depot file for edit, type \\[p4-edit].\n"
  (interactive (list p4-verbose))
  (let ((args (p4-buffer-file-name))
	refresh-after)
    (if (or current-prefix-arg (not args))
	(progn
	  (setq args (if (p4-buffer-file-name-2)
			 (p4-buffer-file-name-2)
		       ""))
	  (setq args (p4-make-list-from-string
		      (p4-read-arg-string "p4 edit: " (cons args 0))))
	  (setq refresh-after t))
      (setq args (list args)))
    (p4-noinput-buffer-action "edit" t (and show-output 's) args)
    (if refresh-after
	(p4-refresh-files-in-buffers)))
  (p4-check-mode)
  (p4-update-opened-list))

;; The p4 reopen command
(defp4cmd p4-reopen (show-output)
  "reopen"
  "To change the type or changelist number of an opened file, type \\[p4-reopen].

Argument SHOW-OUTPUT displays the *P4 Output* buffer on executing the
command if t.\n"

  (interactive (list p4-verbose))
  (let ((args (if (p4-buffer-file-name-2)
		  (p4-buffer-file-name-2)
		"")))
    (setq args (p4-make-list-from-string
		(p4-read-arg-string "p4 reopen: " (cons args 0))))
    (p4-noinput-buffer-action "reopen" t (and show-output 's) args))
  (p4-check-mode)
  (p4-update-opened-list))

;; The p4 revert command
(defp4cmd p4-revert (show-output)
  "revert" "To revert all change in the current file, type \\[p4-revert].\n"
  (interactive (list p4-verbose))
  (let ((args (p4-buffer-file-name))
	refresh-after)
    (if (or current-prefix-arg (not args))
	(progn
	  (setq args (if (p4-buffer-file-name-2)
			 (p4-buffer-file-name-2)
		       ""))
	  (setq args (p4-make-list-from-string
		      (p4-read-arg-string "p4 revert: " args)))
	  (setq refresh-after t))
      (setq args (list args)))
    (if (yes-or-no-p "Really revert changes? ")
	(progn
	  (p4-noinput-buffer-action "revert" t (and show-output 's) args)
	  (if refresh-after
	      (progn
		(p4-refresh-files-in-buffers)
		(p4-check-mode-all-buffers))
	    (p4-check-mode))
	  (p4-update-opened-list)))))

;; The p4 lock command
(defp4cmd p4-lock ()
  "lock" "To lock an opened file against changelist submission, type \\[p4-lock].\n"
  (interactive)
  (let ((args (list (p4-buffer-file-name-2))))
    (if (or current-prefix-arg (not (p4-buffer-file-name-2)))
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 lock: "
					(p4-buffer-file-name-2)))))
    (p4-noinput-buffer-action "lock" t 's args)
    (p4-update-opened-list)))

;; The p4 unlock command
(defp4cmd p4-unlock ()
  "unlock" "To release a locked file but leave open, type \\[p4-unlock].\n"
  (interactive)
  (let ((args (list (p4-buffer-file-name-2))))
    (if (or current-prefix-arg (not (p4-buffer-file-name-2)))
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 unlock: "
					(p4-buffer-file-name-2)))))
    (p4-noinput-buffer-action "unlock" t 's args)
    (p4-update-opened-list)))

;; The p4 diff command
(defp4cmd p4-diff ()
  "diff" "To diff the current file and topmost depot version, type \\[p4-diff].\n"
  (interactive)
  (let ((args (p4-make-list-from-string p4-default-diff-options)))
    (if (p4-buffer-file-name-2)
	(setq args (append args
			   (list (p4-buffer-file-name-2)))))
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 diff: " p4-default-diff-options))))
    (p4-noinput-buffer-action "diff" nil 's args)
    (p4-activate-diff-buffer "*P4 diff*")))

(defun p4-diff-all-opened ()
  (interactive)
  (p4-noinput-buffer-action "diff" nil 's
			    (p4-make-list-from-string p4-default-diff-options))
  (p4-activate-diff-buffer "*P4 diff*"))


(defun p4-get-file-rev (default-name rev)
  (if (string-match "^\\([0-9]+\\|none\\|head\\|have\\)$" rev)
      (setq rev (concat "#" rev)))
  (cond ((string-match "^[#@]" rev)
	 (concat default-name rev))
	((string= "" rev)
	 default-name)
	(t
	 rev)))

;; The p4 diff2 command
(defp4cmd p4-diff2 (version1 version2)
  "diff2" "Display diff of two depot files.

When visiting a depot file, type \\[p4-diff2] and enter the versions.\n"
  (interactive
   (let ((rev (get-char-property (point) 'rev)))
     (if (and (not rev) (p4-buffer-file-name-2))
	 (let ((rev-num 0))
	   (setq rev (p4-is-vc nil (p4-buffer-file-name-2)))
	   (if rev
	       (setq rev-num (string-to-number rev)))
	   (if (> rev-num 1)
	       (setq rev (number-to-string (1- rev-num)))
	     (setq rev nil))))
     (list (p4-read-arg-string "First Depot File or Version# to diff: " rev)
	   (p4-read-arg-string "Second Depot File or Version# to diff: "))))
  (let (diff-version1
	diff-version2
	(diff-options (p4-make-list-from-string p4-default-diff-options)))
    (if current-prefix-arg
	(setq diff-options (p4-make-list-from-string
			    (p4-read-arg-string "Optional Args: "
						p4-default-diff-options))))
    ;; try to find out if this is a revision number, or a depot file
    (setq diff-version1 (p4-get-file-rev (p4-buffer-file-name-2) version1))
    (setq diff-version2 (p4-get-file-rev (p4-buffer-file-name-2) version2))

    (p4-noinput-buffer-action "diff2" nil t
			      (append diff-options
				      (list diff-version1
					    diff-version2)))
    (p4-activate-diff-buffer "*P4 diff2*")))

;; p4-ediff for all those who diff using ediff
(defun p4-ediff ()
  "Use ediff to compare file with its original client version."
  (interactive)
  (require 'ediff)
  (if current-prefix-arg
      (call-interactively 'p4-ediff2)
    (progn
      (p4-noinput-buffer-action "print" nil nil
				(list "-q"
				      (concat (p4-buffer-file-name) "#have")))
      (let ((local (current-buffer))
	    (depot (get-buffer-create p4-output-buffer-name)))
	(ediff-buffers local
		       depot
		       `((lambda ()
			   (make-local-variable 'ediff-cleanup-hook)
			   (setq ediff-cleanup-hook
				 (cons (lambda ()
					 (kill-buffer ,depot)
					 (p4-menu-add))
				       ediff-cleanup-hook)))))))))

(defp4cmd p4-ediff2 (version1 version2)
  "ediff2" "Use ediff to display two versions of a depot file.

When visiting a depot file, type \\[p4-ediff2] and enter the versions.\n"
  (interactive
   (let ((rev (get-char-property (point) 'rev)))
     (if (and (not rev) (p4-buffer-file-name-2))
	 (let ((rev-num 0))
	   (setq rev (p4-is-vc nil (p4-buffer-file-name-2)))
	   (if rev
	       (setq rev-num (string-to-number rev)))
	   (if (> rev-num 1)
	       (setq rev (number-to-string (1- rev-num)))
	     (setq rev nil))))
     (list (p4-read-arg-string "First Depot File or Version# to diff: " rev)
	   (p4-read-arg-string "Second Depot File or Version# to diff: "))))
  (let* ((file-name (p4-buffer-file-name-2))
         (basename (file-name-nondirectory file-name))
         (bufname1 (concat "*P4 ediff " basename "#" version1  "*"))
         (bufname2 (concat "*P4 ediff " basename "#" version2  "*"))
         (diff-version1 (p4-get-file-rev file-name version1))
         (diff-version2 (p4-get-file-rev file-name version2)))
    (p4-noinput-buffer-action "print" nil nil (list "-q" diff-version1))
    (set-buffer p4-output-buffer-name)
    (rename-buffer bufname1 t)
    (p4-noinput-buffer-action "print" nil nil (list "-q" diff-version2))
    (set-buffer p4-output-buffer-name)
    (rename-buffer bufname2 t)
    (let ((buffer-version-1 (get-buffer-create bufname1))
          (buffer-version-2 (get-buffer-create bufname2)))
      (ediff-buffers buffer-version-1
                     buffer-version-2
                     `((lambda ()
                         (make-local-variable 'ediff-cleanup-hook)
                         (setq ediff-cleanup-hook
                               (cons (lambda ()
                                       (kill-buffer ,buffer-version-1)
                                       (kill-buffer ,buffer-version-2)
                                       (p4-menu-add))
                                     ediff-cleanup-hook))))))))
;; The p4 add command
(defp4cmd p4-add ()
  "add" "To add the current file to the depot, type \\[p4-add].\n"
  (interactive)
  (let ((args (p4-buffer-file-name))
	refresh-after)
    (if (or current-prefix-arg (not args))
	(progn
	  (setq args (if (p4-buffer-file-name-2)
			 (p4-buffer-file-name-2)
		       ""))
	  (setq args (p4-make-list-from-string
		      (p4-read-arg-string "p4 add: " (cons args 0))))
	  (setq refresh-after t))
      (setq args (list args)))
    (p4-noinput-buffer-action "add" nil 's args)
    (if refresh-after
	(p4-check-mode-all-buffers)
      (p4-check-mode)))
  (p4-update-opened-list))


;; The p4 delete command
(defp4cmd p4-delete ()
  "delete" "To delete the current file from the depot, type \\[p4-delete].\n"
  (interactive)
  (let ((args (p4-buffer-file-name)))
    (if (or current-prefix-arg (not args))
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 delete: "
					(p4-buffer-file-name-2))))
      (setq args (list args)))
    (if (yes-or-no-p "Really delete from depot? ")
	(p4-noinput-buffer-action "delete" nil 's args)))
  (p4-check-mode)
  (p4-update-opened-list))

;; The p4 filelog command
(defp4cmd p4-filelog ()
  "filelog"
  "To view a history of the change made to the current file, type \\[p4-filelog].\n"
  (interactive)
  (let ((file-name (p4-buffer-file-name-2)))
    (if (or current-prefix-arg (not file-name))
	(setq file-name (p4-make-list-from-string
			 (p4-read-arg-string "p4 filelog: " file-name)))
      (setq file-name (list file-name)))
    (p4-file-change-log "filelog" file-name)))

(defun p4-set-extent-properties (start end prop-list)
  (cond (p4-running-xemacs
	 (let ((ext (make-extent start end)))
	   (while prop-list
	     (set-extent-property ext (caar prop-list) (cdar prop-list))
	     (setq prop-list (cdr prop-list)))))
	(p4-running-emacs
	 (let ((ext (make-overlay start end)))
	   (while prop-list
	     (overlay-put ext (caar prop-list) (cdar prop-list))
	     (setq prop-list (cdr prop-list)))))))

(defun p4-create-active-link (start end prop-list)
  (p4-set-extent-properties start end
			    (append (list (cons 'face 'bold)
					  (cons 'mouse-face 'highlight))
				    prop-list)))

(defun p4-move-buffer-point-to-top (buf-name)
  (if (get-buffer-window buf-name)
      (save-selected-window
	(select-window (get-buffer-window buf-name))
	(goto-char (point-min)))))

(defun p4-file-change-log (cmd file-list-spec)
  (let ((p4-filelog-buffer
	 (concat "*P4 " cmd ": "
		 (p4-list-to-string file-list-spec) "*")))
    (p4-noinput-buffer-action cmd nil t (cons "-l" file-list-spec))
    (p4-activate-file-change-log-buffer p4-filelog-buffer)))

(defun p4-activate-file-change-log-buffer (bufname)
  (let (p4-cur-rev p4-cur-change p4-cur-action
	p4-cur-user p4-cur-client)
    (p4-activate-print-buffer bufname nil)
    (set-buffer bufname)
    (setq buffer-read-only nil)
    (goto-char (point-min))
    (while (re-search-forward (concat
			       "^\\(\\.\\.\\. #\\([0-9]+\\) \\)?[Cc]hange "
			       "\\([0-9]+\\) \\([a-z]+\\)?.*on.*by "
			       "\\([^ @]+\\)@\\([^ \n]+\\).*\n"
			       "\\(\\(\\([ \t].*\\)?\n\\)*\\)") nil t)
      (let ((rev-match 2)
	    (ch-match 3)
	    (act-match 4)
	    (user-match 5)
	    (cl-match 6)
	    (desc-match 7))
	(setq p4-cur-rev (match-string rev-match))
	(setq p4-cur-change (match-string ch-match))
	(setq p4-cur-action (match-string act-match))
	(setq p4-cur-user (match-string user-match))
	(setq p4-cur-client (match-string cl-match))

	(if (match-beginning rev-match)
	    (p4-create-active-link (match-beginning rev-match)
				   (match-end rev-match)
				   (list (cons 'rev p4-cur-rev))))
	(p4-create-active-link (match-beginning ch-match)
			       (match-end ch-match)
			       (list (cons 'change p4-cur-change)))
	(if (match-beginning act-match)
	    (p4-create-active-link (match-beginning act-match)
				   (match-end act-match)
				   (list (cons 'action p4-cur-action)
					 (cons 'rev p4-cur-rev))))
	(p4-create-active-link (match-beginning user-match)
			       (match-end user-match)
			       (list (cons 'user p4-cur-user)))
	(p4-create-active-link (match-beginning cl-match)
			       (match-end cl-match)
			       (list (cons 'client p4-cur-client)))
	(p4-set-extent-properties (match-beginning desc-match)
				  (match-end desc-match)
				  (list (cons 'invisible t)
					(cons 'isearch-open-invisible t)))))
    (p4-find-change-numbers bufname (point-min) (point-max))
    (use-local-map p4-filelog-map)
    (setq buffer-invisibility-spec (list))
    (setq buffer-read-only t)
    (p4-move-buffer-point-to-top bufname)))

;; Scan specified region for references to change numbers
;; and make the change numbers clickable.
(defun p4-find-change-numbers (buffer start end)
  (save-excursion
    (set-buffer buffer)
    (goto-char start)
    (while (re-search-forward "\\(changes?\\|submit\\|p4\\)[:#]?[ \t\n]+" end t)
      (while (looking-at
	      (concat "\\([#@]\\|number\\|no\\.\\|\\)[ \t\n]*"
		      "\\([0-9]+\\)[-, \t\n]*"
		      "\\(and/or\\|and\\|&\\|or\\|\\)[ \t\n]*"))
	(let ((ch-start (match-beginning 2))
	      (ch-end (match-end 2))
	      (ch-str (match-string 2))
	      (next (match-end 0)))
	  (set-text-properties 0 (length ch-str) nil ch-str)
	  (p4-create-active-link ch-start ch-end (list (cons 'change ch-str)))
	  (goto-char next))))))

;; The p4 files command
(defp4cmd p4-files ()
  "files" "List files in the depot. Type, \\[p4-files].\n"
  (interactive)
  (let ((args (p4-buffer-file-name-2)))
    (if (or current-prefix-arg (not args))
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 files: " (p4-buffer-file-name-2))))
      (setq args (list args)))
    (p4-noinput-buffer-action "files" nil t args)
    (save-excursion
      (set-buffer p4-output-buffer-name)
      (p4-find-change-numbers p4-output-buffer-name (point-min) (point-max)))
    (p4-make-depot-list-buffer
     (concat "*P4 Files: (" (p4-current-client) ") " (car args) "*"))))


(defvar p4-server-version-cache nil)

(defun p4-get-server-version ()
  "To get the version number of the p4 server."
  (let ((p4-port (p4-current-server-port))
	ser-ver pmin)
    (setq ser-ver (cdr (assoc p4-port p4-server-version-cache)))
    (if (not ser-ver)
	(save-excursion
	  (get-buffer-create p4-output-buffer-name)
	  (set-buffer p4-output-buffer-name)
	  (goto-char (point-max))
	  (setq pmin (point))
	  (if (zerop (p4-call-p4-here "info"))
	      (progn
		(goto-char pmin)
		(re-search-forward
		 "^Server version: .*\/.*\/\\(\\([0-9]+\\)\.[0-9]+\\)\/.*(.*)$")
		(setq ser-ver (string-to-number (match-string 2)))
		(setq p4-server-version-cache (cons (cons p4-port ser-ver)
						    p4-server-version-cache))
		(delete-region pmin (point-max))))))
    ser-ver))

(defun p4-get-client-root (client-name)
  "To get the current value of Client's root type \\[p4-get-client-root].
   This can be used by any other macro that requires this value."
  (let (p4-client-root pmin)
    (save-excursion
      (get-buffer-create p4-output-buffer-name)
      (set-buffer p4-output-buffer-name)
      (goto-char (point-max))
      (setq pmin (point))
      (if (zerop (p4-call-p4-here "client" "-o" client-name))
	  (progn
	    (goto-char pmin)
	    (re-search-forward "^Root:[ \t]+\\(.*\\)$")
	    (setq p4-client-root (p4-canonize-client-root (match-string 1)))
	    (delete-region pmin (point-max)))))
    p4-client-root))

(defun p4-canonize-client-root (p4-client-root)
  "Canonizes client root"
  (let ((len (length p4-client-root)))
    ;; For Windows, since the client root may be terminated with
    ;; a \ as in c:\ or drive:\foo\bar\, we need to strip the
    ;; trailing \ .
    (if (and (p4-windows-os)
	     (> len 1)
	     (equal (substring p4-client-root (1- len) len) "\\"))
	(setq p4-client-root (substring p4-client-root 0 (1- len))))
    p4-client-root))

(defun p4-map-depot-files (file-list)
  "Map a list of files in the depot on the current client.
Return a list of pairs, where each pair consists of a depot
name and a client name."
  (let (file-map)
    (while file-list
      (let (sub-list (arg-len 0) elt)
	(while (and file-list (< arg-len p4-exec-arg-len-max))
	  (setq elt (car file-list))
	  (setq file-list (cdr file-list))
	  (setq sub-list (cons elt sub-list))
	  (setq arg-len (+ arg-len (length elt) 1)))
	(setq file-map (append file-map
			       (p4-map-depot-files-int sub-list)))))
    file-map))

(defun p4-map-depot-files-int (file-list)
  (let* ((current-client (p4-current-client))
	 (client-root (p4-get-client-root current-client))
	 (re-current-client (regexp-quote current-client))
	 (re-client-root (regexp-quote client-root))
	 files pmin)
    (save-excursion
      (get-buffer-create p4-output-buffer-name)
      (set-buffer p4-output-buffer-name)
      (goto-char (point-max))
      (setq pmin (point))
      (insert "\n")
      (apply 'p4-call-p4-here "where" file-list)
      (goto-char pmin)
      (if (< (p4-get-server-version) 98)
	  (while (re-search-forward
		  (concat "^\\([^\n]+\\) //" re-current-client
			  "\\(.*\\)$") nil t)
	    (setq files (cons
			 (cons
			  (match-string 1)
			  (concat client-root (match-string 2)))
			 files)))
	(while (re-search-forward
		(concat "^\\([^\n]+\\) //" re-current-client
			"\\([^\n]+\\) \\(" re-client-root ".*\\)$") nil t)
	  (setq files (cons
		       (cons
			(match-string 1) (match-string 3)) files))))
      (delete-region pmin (point-max)))
    files))

(make-face 'p4-depot-unmapped-face)
(set-face-foreground 'p4-depot-unmapped-face "grey30")

(make-face 'p4-depot-deleted-face)
(set-face-foreground 'p4-depot-deleted-face "red")

(make-face 'p4-depot-added-face)
(set-face-foreground 'p4-depot-added-face "blue")

(make-face 'p4-depot-branch-op-face)
(set-face-foreground 'p4-depot-branch-op-face "blue4")

(defun p4-make-depot-list-buffer (bufname &optional print-buffer)
  "Take the p4-output-buffer-name buffer, rename it to bufname, and
make all depot file names active, so that clicking them opens
the corresponding client file."
  (let (args files depot-regexp)
    (set-buffer p4-output-buffer-name)
    (goto-char (point-min))
    (setq depot-regexp
	  (if print-buffer
	      "\\(^\\)\\(//[^/@# ][^/@#]*/[^@#]+\\)#[0-9]+ - "
	    "^\\(\\.\\.\\. [^/\n]*\\|==== \\)?\\(//[^/@# ][^/@#]*/[^#\n]*\\)"))
    (while (re-search-forward depot-regexp nil t)
      (setq args (cons (match-string 2) args)))
    (setq files (p4-map-depot-files args))
    (get-buffer-create bufname);; We do these two lines
    (kill-buffer bufname);; to ensure no duplicates
    (set-buffer p4-output-buffer-name)
    (rename-buffer bufname t)
    (goto-char (point-min))
    (while (re-search-forward depot-regexp nil t)
      (let ((p4-client-file (cdr (assoc (match-string 2) files)))
	    (p4-depot-file (match-string 2))
	    (start (match-beginning 2))
	    (end (match-end 2))
	    (branching-op-p (and (match-string 1)
				 (string-match "\\.\\.\\. \\.\\.\\..*"
					       (match-string 1))))
	    prop-list)
	(if (and p4-client-file
		 (file-readable-p p4-client-file))
	    (setq prop-list (list (cons 'link-client-name
					p4-client-file)))
	  (setq prop-list (list (cons 'link-depot-name
				      p4-depot-file))))
	;; some kind of operation related to branching/integration
	(if branching-op-p
	    (setq prop-list (append (list
				     (cons 'history-for p4-depot-file)
				     (cons 'face
					   'p4-depot-branch-op-face))
				    prop-list)))
	(cond
	 ((not p4-client-file)
	  (p4-set-extent-properties
	   start end
	   (append (list (cons 'face 'p4-depot-unmapped-face))
		   prop-list)))
	 ((save-excursion
	    (goto-char end)
	    (looking-at ".* deleted?[ \n]"))
	  (p4-set-extent-properties
	   start end
	   (append (list (cons 'face 'p4-depot-deleted-face))
		   prop-list)))
	 ((save-excursion
	    (goto-char end)
	    (looking-at ".* \\(add\\|branch\\)\\(ed\\)?[ \n]"))
	  (p4-create-active-link
	   start end
	   (append (list (cons 'face 'p4-depot-added-face))
		   prop-list)))
	 (t
	  (p4-create-active-link start end prop-list)))))
    (use-local-map p4-opened-map)
    (setq buffer-read-only t)
    (p4-move-buffer-point-to-top bufname)))

;; The p4 print command
(defp4cmd p4-print ()
  "print" "To print a depot file to a buffer, type \\[p4-print].\n"
  (interactive)
  (let ((arg-string (p4-buffer-file-name-2))
	(rev (get-char-property (point) 'rev))
	(change (get-char-property (point) 'change)))
    (cond (rev
	   (setq arg-string (concat arg-string "#" rev)))
	  (change
	   (setq arg-string (concat arg-string "@" change))))
    (if (or current-prefix-arg (not arg-string))
	(setq arg-string (p4-make-list-from-string
			  (p4-read-arg-string "p4 print: " arg-string)))
      (setq arg-string (list arg-string)))
    (p4-noinput-buffer-action "print" nil t arg-string)
    (p4-activate-print-buffer "*P4 print*" t)))

;; Insert text in a buffer, but make sure that the inserted text doesn't
;; inherit any properties from surrounding text. This is needed for xemacs
;; because the insert function makes the inserted text inherit properties.
(defun p4-insert-no-properties (str)
  (let ((start (point))
	end)
    (insert str)
    (setq end (point))
    (set-text-properties start end nil)))

(defun p4-font-lock-buffer (buf-name)
  (save-excursion
    (let (file-name (first-line ""))
      (set-buffer buf-name)
      (goto-char (point-min))
      (if (looking-at "^//[^#@]+/\\([^/#@]+\\)")
	  (progn
	    (setq file-name (match-string 1))
	    (forward-line 1)
	    (setq first-line (buffer-substring (point-min) (point)))
	    (delete-region (point-min) (point))))
      (setq buffer-file-name file-name)
      (set-auto-mode)
      (setq buffer-file-name nil)
      (condition-case nil
	  (font-lock-fontify-buffer)
	(error nil))
      (fundamental-mode)
      (if (and p4-running-emacs
	       (boundp 'hilit-auto-rehighlight))
	  (setq hilit-auto-rehighlight nil))
      (goto-char (point-min))
      (p4-insert-no-properties first-line))))

(defun p4-activate-print-buffer (buffer-name print-buffer)
  (if print-buffer
      (p4-font-lock-buffer p4-output-buffer-name))
  (p4-make-depot-list-buffer buffer-name print-buffer)
  (let ((depot-regexp
	 (if print-buffer
	     "^\\(//[^/@# ][^/@#]*/\\)[^@#]+#[0-9]+ - "
	   "^\\(//[^/@# ][^/@#]*/\\)")))
    (save-excursion
      (set-buffer buffer-name)
      (setq buffer-read-only nil)
      (goto-char (point-min))
      (while (re-search-forward depot-regexp nil t)
	(let ((link-client-name (get-char-property (match-end 1)
						   'link-client-name))
	      (link-depot-name (get-char-property (match-end 1)
						  'link-depot-name))
	      (start (match-beginning 1))
	      (end (point-max)))
	  (save-excursion
	    (if (re-search-forward depot-regexp nil t)
		(setq end (match-beginning 1))))
	  (if link-client-name
	      (p4-set-extent-properties start end
					(list (cons 'block-client-name
						    link-client-name))))
	  (if link-depot-name
	      (p4-set-extent-properties start end
					(list (cons 'block-depot-name
						    link-depot-name))))))
      (setq buffer-read-only t))))

(defconst p4-blame-change-regex
  (concat "^\\.\\.\\. #"     "\\([0-9]+\\)"   ;; revision
	  "\\s-+change\\s-+" "\\([0-9]+\\)"   ;; change
	  "\\s-+"            "\\([^ \t]+\\)"  ;; type
	  "\\s-+on\\s-+"     "\\([^ \t]+\\)"  ;; date	   
	  "\\s-+by\\s-+"     "\\([^ \t]+\\)"  ;; author
	  "@"))

(defconst p4-blame-branch-regex
  "^\\.\\.\\. \\.\\.\\. branch from \\(//[^#]*\\)#")

(defconst p4-blame-revision-regex
  (concat "^\\([0-9]+\\),?"
	  "\\([0-9]*\\)"
	  "\\([acd]\\)"
	  "\\([0-9]+\\),?"
	  "\\([0-9]*\\)"))

(defconst p4-blame-index-regex
  (concat " *\\([0-9]+\\)"               ;; change
	  " *\\([0-9]+\\)"               ;; revision
	  " *\\([0-9]+/[0-9]+/[0-9]+\\)" ;; date
	  "\\s-+\\([^:]*\\)"             ;; author
	  ":"))          

(defconst P4-REV  0)
(defconst P4-DATE 1)
(defconst P4-AUTH 2)
(defconst P4-FILE 3)

(defun p4-blame ()
  "To Print a depot file with revision history to a buffer,
type \\[p4-blame]"
  (interactive)
  (let ((arg-string (p4-buffer-file-name-2))
	(rev (get-char-property (point) 'rev))
	(change (get-char-property (point) 'change)))
    (cond (rev
	   (setq arg-string (concat arg-string "#" rev)))
	  (change
	   (setq arg-string (concat arg-string "@" change))))
    (if (or current-prefix-arg (not arg-string))
	(setq arg-string (p4-read-arg-string "p4 print-revs: " arg-string)))
    (p4-blame-int arg-string)))

(defalias 'p4-print-with-rev-history 'p4-blame)

(defun p4-blame-int (file-spec)
  (get-buffer-create p4-output-buffer-name);; We do these two lines
  (kill-buffer p4-output-buffer-name)      ;; to ensure no duplicates
  (let ((file-name file-spec)
	(buffer (get-buffer-create p4-output-buffer-name))
	head-name  ;; file spec of the head revision for this blame assignment
	branch-p   ;; have we tracked into a branch?
	cur-file   ;; file name of the current branch during blame assignment
	change ch-alist fullname head-rev headseen)

    ;; we asked for blame constrained by a change number
    (if (string-match "\\(.*\\)@\\([0-9]+\\)" file-spec)
	(progn
	  (setq file-name (match-string 1 file-spec))
	  (setq change (string-to-int (match-string 2 file-spec)))))

    ;; we asked for blame constrained by a revision
    (if (string-match "\\(.*\\)#\\([0-9]+\\)" file-spec)
	(progn
	  (setq file-name (match-string 1 file-spec))
	  (setq head-rev (string-to-int (match-string 2 file-spec)))))

    ;; make sure the filespec is unambiguous
    (p4-exec-p4 buffer (list "files" file-name) t)
    (save-excursion
      (set-buffer buffer)
      (if (> (count-lines (point-min) (point-max)) 1)
	  (error "File pattern maps to more than one file.")))

    ;; get the file change history:
    (p4-exec-p4 buffer (list "filelog" "-i" file-spec) t)
    (setq fullname (p4-read-depot-output buffer)
	  cur-file  fullname
	  head-name fullname)

    ;; parse the history:
    (save-excursion
      (set-buffer buffer)
      (goto-char (point-min))
      (while (< (point) (point-max))

	;; record the current file name (and the head file name,
	;; if we have not yet seen one):
	(if (looking-at "^\\(//.*\\)$")
	    (setq cur-file (match-string 1)))

	;; a non-branch change:
	(if (looking-at p4-blame-change-regex)
	    (let ((rev (string-to-int (match-string 1)))
		  (ch (string-to-int (match-string 2)))
		  (op (match-string 3))
		  (date (match-string 4))
		  (author (match-string 5)))
	      (cond
	       ;; after the change constraint, OR
	       ;; after the revision constraint _for this file_
	       ;;   [remember, branches complicate this]:
	       ((or (and change   (< change ch))
		    (and head-rev (< head-rev rev)
			 (string= head-name cur-file))) nil)
	       
	       ;; file has been deleted, can't assign blame:
	       ((string= op "delete") 
		(if (not headseen) (goto-char (point-max))))

	       ;; OK, we actually want to look at this one:
	       (t
		(setq ch-alist
		      (cons
		       (cons ch (list rev date author cur-file)) ch-alist))
		(if (not head-rev) (setq head-rev rev))
		(setq headseen t)) ))

	  ;; not if we have entered a branch (this used to be used, isn't
	  ;; right now - maybe again later:
	  (if (and headseen (looking-at p4-blame-branch-regex))
	      (setq branch-p t)) )
	(forward-line)))
    
    (if (< (length ch-alist) 1)
	(error "Head revision not available"))
  
    (let ((base-ch (int-to-string (caar ch-alist)))
	  (ch-buffer (get-buffer-create "p4-ch-buf"))
	  (tmp-alst (copy-alist ch-alist)))
      (p4-exec-p4 ch-buffer
		  (list "print" "-q" (concat cur-file "@" base-ch)) t)
      (save-excursion
	(set-buffer ch-buffer)
	(goto-char (point-min))
	(while (re-search-forward ".*\n" nil t)
	  (replace-match (concat base-ch "\n"))))
      (while (> (length tmp-alst) 1)
	(let ((ch-1 (car (car  tmp-alst)))
	      (ch-2 (car (cadr tmp-alst)))
	      (file1 (nth P4-FILE (cdr (car  tmp-alst))))
	      (file2 (nth P4-FILE (cdr (cadr tmp-alst))))
	      ins-string)
	  (setq ins-string (format "%d\n" ch-2))
	  (p4-exec-p4 buffer (list "diff2"
				   (format "%s@%d" file1 ch-1)
				   (format "%s@%d" file2 ch-2)) t)
	  (save-excursion
	    (set-buffer buffer)
	    (goto-char (point-max))
	    (while (re-search-backward p4-blame-revision-regex nil t)
	      (let ((la (string-to-int (match-string 1)))
		    (lb (string-to-int (match-string 2)))
		    (op (match-string 3))
		    (ra (string-to-int (match-string 4)))
		    (rb (string-to-int (match-string 5))))
		(if (= lb 0)
		    (setq lb la))
		(if (= rb 0)
		    (setq rb ra))
		(cond ((string= op "a")
		       (setq la (1+ la)))
		      ((string= op "d")
		       (setq ra (1+ ra))))
		(save-excursion
		  (set-buffer ch-buffer)
		  (goto-line la)
		  (let ((beg (point)))
		    (forward-line (1+ (- lb la)))
		    (delete-region beg (point)))
		  (while (<= ra rb)
		    (insert ins-string)
		    (setq ra (1+ ra)))))))
	  (setq tmp-alst (cdr tmp-alst))))
      (p4-noinput-buffer-action "print" nil t
				(list (format "%s#%d" fullname head-rev))
				t)
      (p4-font-lock-buffer p4-output-buffer-name)
      (let (line cnum (old-cnum 0) change-data
	    xth-rev xth-date xth-auth xth-file)
	(save-excursion
	  (set-buffer buffer)
	  (goto-line 2)
	  (move-to-column 0)
	  (p4-insert-no-properties "Change  Rev       Date  Author\n")
	  (while (setq line (p4-read-depot-output ch-buffer))
	    (setq cnum (string-to-int line))
	    (if (= cnum old-cnum)
		(p4-insert-no-properties (format "%29s : " ""))

	      ;; extract the change data from our alist: remember,
	      ;; `eq' works for integers so we can use assq here:
	      (setq change-data (cdr (assq cnum ch-alist))
		    xth-rev     (nth P4-REV  change-data)
		    xth-date    (nth P4-DATE change-data)
		    xth-auth    (nth P4-AUTH change-data)
		    xth-file    (nth P4-FILE change-data))
	      
	      (p4-insert-no-properties
	       (format "%6d %4d %10s %7s: " cnum xth-rev xth-date xth-auth))
	      (move-to-column 0)
	      (if (looking-at p4-blame-index-regex)
		  (let ((nth-cnum (match-string 1))
			(nth-revn (match-string 2))
			(nth-user (match-string 4)))
		    (p4-create-active-link (match-beginning 1)
					   (match-end 1)
					   (list (cons 'change nth-cnum)))
		    ;; revision needs to be linked to a file now that we
		    ;; follow integrations (branches):
		    (p4-create-active-link (match-beginning 2)
					   (match-end 2)
					   (list (cons 'rev  nth-revn)
						 (cons 'link-depot-name xth-file)))
		    (p4-create-active-link (match-beginning 4)
					   (match-end 4)
					   (list (cons 'user nth-user)))
		    ;; truncate the user name:
		    (let ((start (+ (match-beginning 4) 7))
			  (end (match-end 4)))
		      (if (> end start)
			  (delete-region start end))))))
	    (setq old-cnum cnum)
	    (forward-line))))

      (kill-buffer ch-buffer))
    (let ((buffer-name (concat "*P4 print-revs " file-name "*")))
      (p4-activate-print-buffer buffer-name nil)
      (save-excursion
	(set-buffer buffer-name)
	(setq truncate-lines t)
	(use-local-map p4-print-rev-map)))))

;; The p4 refresh command
(defp4cmd p4-refresh ()
  "sync" "Refresh the contents of an unopened file. \\[p4-refresh].

This is equivalent to \"sync -f\"
"
  (interactive)
  (let ((args (p4-buffer-file-name)))
    (if (or current-prefix-arg (not args))
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 refresh: ")))
      (setq args (list args)))
    (p4-noinput-buffer-action "refresh" nil t args)
    (p4-refresh-files-in-buffers)
    (p4-make-depot-list-buffer
     (concat "*P4 Refresh: (" (p4-current-client) ") " (car args) "*"))))

;; The p4 get/sync command
(defp4cmd p4-sync ()
  "sync"
  "To synchronise the local view with the depot, type \\[p4-get].\n"
  (interactive)
  (p4-get))

(defp4cmd p4-get ()
  "sync"
  "To synchronise the local view with the depot, type \\[p4-get].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string (p4-read-arg-string "p4 get: "))))
    (p4-noinput-buffer-action "get" nil t args)
    (p4-refresh-files-in-buffers)
    (p4-make-depot-list-buffer
     (concat "*P4 Get: (" (p4-current-client) ") " (car args) "*"))))

;; The p4 have command
(defp4cmd p4-have ()
  "have" "To list revisions last gotten, type \\[p4-have].\n"
  (interactive)
  (let ((args (list "...")))
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 have: " (p4-buffer-file-name-2)))))
    (p4-noinput-buffer-action "have" nil t args)
    (p4-make-depot-list-buffer
     (concat "*P4 Have: (" (p4-current-client) ") " (car args) "*"))))

;; The p4 changes command
(defp4cmd p4-changes ()
  "changes" "To list changes, type \\[p4-changes].\n"
  (interactive)
  (let ((arg-list (list "-m" "200" "...")))
    (if current-prefix-arg
	(setq arg-list (p4-make-list-from-string
			(p4-read-arg-string "p4 changes: " "-m 200"))))
    (p4-file-change-log "changes" arg-list)))

;; The p4 help command
(defp4cmd p4-help (arg)
  "help" "To print help message, type \\[p4-help].

Argument ARG command for which help is needed.
"
  (interactive (list (p4-make-list-from-string
		      (p4-read-arg-string "Help on which command: "
					  nil "help"))))
  (p4-noinput-buffer-action "help" nil t arg)
  (p4-make-basic-buffer "*P4 help*"))

(defun p4-make-basic-buffer (buf-name &optional map)
  "rename `p4-output-buffer-name' to buf-name \(which will be killed first if
it already exists\), set its local map to map, if specified, or
`p4-basic-map' otherwise. Makes the buffer read only."
  (get-buffer-create buf-name)
  (kill-buffer buf-name)
  (set-buffer p4-output-buffer-name)
  (goto-char (point-min))
  (rename-buffer buf-name t)
  (use-local-map (if (keymapp map) map p4-basic-map))
  (setq buffer-read-only t)
  (p4-move-buffer-point-to-top buf-name))

;; The p4 info command
(defp4cmd p4-info ()
  "info" "To print out client/server information, type \\[p4-info].\n"
  (interactive)
  (p4-noinput-buffer-action "info" nil t)
  (p4-make-basic-buffer "*P4 info*"))

;; The p4 integrate command
(defp4cmd p4-integ ()
  "integ" "To schedule integrations between branches, type \\[p4-integ].\n"
  (interactive)
  (let ((args (p4-make-list-from-string
	       (p4-read-arg-string "p4 integ: " "-b "))))
    (p4-noinput-buffer-action "integ" nil t args)
    (p4-make-depot-list-buffer "*P4 integ*")))

(defp4cmd p4-resolve ()
  "resolve"
  "To merge open files with other revisions or files, type \\[p4-resolve].\n"
  (interactive)
  (let (buffer args (buf-name "*p4 resolve*"))
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 resolve: " nil))))
    (setq buffer (get-buffer buf-name))
    (if (and (buffer-live-p buffer)
	     (not (comint-check-proc buffer)))
	(save-excursion
	  (let ((cur-dir default-directory))
	    (set-buffer buffer)
	    (cd cur-dir)
	    (goto-char (point-max))
	    (insert "\n--------\n\n"))))
    (setq args (cons "resolve" args))
    (setq buffer (apply 'make-comint "p4 resolve" p4-executable nil "-d" default-directory args))
    (set-buffer buffer)
    (comint-mode)
    (display-buffer buffer)
    (select-window (get-buffer-window buffer))
    (goto-char (point-max))))

(defp4cmd p4-rename ()
  "rename" "To rename a file in the depot, type \\[p4-rename].

This command will execute the integrate/delete commands automatically.
"
  (interactive)
  (let (from-file to-file)
    (setq from-file (p4-read-arg-string "rename from: " (p4-buffer-file-name-2)))
    (setq to-file (p4-read-arg-string "rename to: " (p4-buffer-file-name-2)))
    (p4-noinput-buffer-action "integ" nil t (list from-file to-file))
    (p4-exec-p4 (get-buffer-create p4-output-buffer-name)
		(list "delete" from-file)
		nil)))

(defun p4-scroll-down-1-line ()
  "Scroll down one line"
  (interactive)
  (scroll-down 1))

(defun p4-scroll-up-1-line ()
  "Scroll up one line"
  (interactive)
  (scroll-up 1))

(defun p4-scroll-down-1-window ()
  "Scroll down one window"
  (interactive)
  (scroll-down
   (- (window-height) next-screen-context-lines)))

(defun p4-scroll-up-1-window ()
  "Scroll up one window"
  (interactive)
  (scroll-up
   (- (window-height) next-screen-context-lines)))

(defun p4-top-of-buffer ()
  "Top of buffer"
  (interactive)
  (goto-char (point-min)))

(defun p4-bottom-of-buffer ()
  "Bottom of buffer"
  (interactive)
  (goto-char (point-max)))

(defun p4-delete-other-windows ()
  "Make buffer full height"
  (interactive)
  (delete-other-windows))

(defun p4-goto-next-diff ()
  "Next diff"
  (interactive)
  (goto-char (window-start))
  (if (= (point) (point-max))
      (error "At bottom"))
  (forward-line 1)
  (re-search-forward "^====" nil "")
  (beginning-of-line)
  (set-window-start (selected-window) (point)))

(defun p4-goto-prev-diff ()
  "Previous diff"
  (interactive)
  (if (= (point) (point-min))
      (error "At top"))
  (goto-char (window-start))
  (re-search-backward "^====" nil "")
  (set-window-start (selected-window) (point)))

(defun p4-next-depot-file ()
  "Next file"
  (interactive)
  (goto-char (window-start))
  (if (= (point) (point-max))
      (error "At bottom"))
  (forward-line 1)
  (re-search-forward "^//[^/@# ][^/@#]*/[^@#]+#[0-9]+ - " nil "")
  (beginning-of-line)
  (set-window-start (selected-window) (point)))

(defun p4-prev-depot-file ()
  "Previous file"
  (interactive)
  (if (= (point) (point-min))
      (error "At top"))
  (goto-char (window-start))
  (re-search-backward "^//[^/@# ][^/@#]*/[^@#]+#[0-9]+ - " nil "")
  (set-window-start (selected-window) (point)))


(defun p4-next-depot-diff ()
  "Next diff"
  (interactive)
  (goto-char (window-start))
  (if (= (point) (point-max))
      (error "At bottom"))
  (forward-line 1)
  (re-search-forward "^\\(@@\\|\\*\\*\\* \\|[0-9]+[,acd]\\)" nil "")
  (beginning-of-line)
  (set-window-start (selected-window) (point)))

(defun p4-prev-depot-diff ()
  "Previous diff"
  (interactive)
  (if (= (point) (point-min))
      (error "At top"))
  (goto-char (window-start))
  (re-search-backward "^\\(@@\\|\\*\\*\\* \\|[0-9]+[,acd]\\)" nil "")
  (set-window-start (selected-window) (point)))

(defun p4-moveto-print-rev-column (old-column)
  (let ((colon (save-excursion
		 (move-to-column 0)
		 (if (looking-at "[^:\n]*:")
		     (progn
		       (goto-char (match-end 0))
		       (current-column))
		   0))))
    (move-to-column old-column)
    (if (and (< (current-column) colon)
	     (re-search-forward "[^ ][ :]" nil t))
	(goto-char (match-beginning 0)))))

(defun p4-next-change-rev-line ()
  "Next change/revision line"
  (interactive)
  (let ((c (current-column)))
    (move-to-column 1)
    (re-search-forward "^ *[0-9]+ +[0-9]+[^:]+:" nil "")
    (p4-moveto-print-rev-column c)))

(defun p4-prev-change-rev-line ()
  "Previous change/revision line"
  (interactive)
  (let ((c (current-column)))
    (forward-line -1)
    (move-to-column 32)
    (re-search-backward "^ *[0-9]+ +[0-9]+[^:]*:" nil "")
    (p4-moveto-print-rev-column c)))

(defun p4-toggle-line-wrap ()
  "Toggle line wrap mode"
  (interactive)
  (setq truncate-lines (not truncate-lines))
  (save-window-excursion
    (recenter)))

(defun p4-quit-current-buffer (pnt)
  "Quit a buffer"
  (interactive "d")
  (if (not (one-window-p))
      (delete-window)
    (bury-buffer)))

(defun p4-buffer-mouse-clicked (event)
  "Function to translate the mouse clicks in a P4 filelog buffer to
character events"
  (interactive "e")
  (let (win pnt)
    (cond (p4-running-xemacs
	   (setq win (event-window event))
	   (setq pnt (event-point event)))
	  (p4-running-emacs
	   (setq win (posn-window (event-end event)))
	   (setq pnt (posn-point (event-start event)))))
    (select-window win)
    (goto-char pnt)
    (p4-buffer-commands pnt)))

(defun p4-buffer-mouse-clicked-3 (event)
  "Function to translate the mouse clicks in a P4 filelog buffer to
character events"
  (interactive "e")
  (let (win pnt)
    (cond (p4-running-xemacs
	   (setq win (event-window event))
	   (setq pnt (event-point event)))
	  (p4-running-emacs
	   (setq win (posn-window (event-end event)))
	   (setq pnt (posn-point (event-start event)))))
    (select-window win)
    (goto-char pnt)
    (let ((link-name (or (get-char-property pnt 'link-client-name)
			 (get-char-property pnt 'link-depot-name)))
	  (rev (get-char-property pnt 'rev)))
      (cond (link-name
	     (p4-diff))
	    (rev
	     (p4-diff2 rev "#head"))
	    (t
	     (error "No file to diff!"))))))

(defun p4-buffer-commands (pnt)
  "Function to get a given property and do the appropriate command on it"
  (interactive "d")
  (let ((rev (get-char-property pnt 'rev))
	(change (get-char-property pnt 'change))
	(action (get-char-property pnt 'action))
	(user (get-char-property pnt 'user))
	(client (get-char-property pnt 'client))
	(label (get-char-property pnt 'label))
	(branch (get-char-property pnt 'branch))
	(filename (p4-buffer-file-name-2)))
    (cond ((and (not action) rev)
	   (let ((fn1 (concat filename "#" rev)))
	     (p4-noinput-buffer-action "print" nil t (list fn1))
	     (p4-activate-print-buffer "*P4 print*" t)))
	  (action
	   (let* ((rev2 (int-to-string (1- (string-to-int rev))))
		  (fn1 (concat filename "#" rev))
		  (fn2 (concat filename "#" rev2)))
	     (if (> (string-to-int rev2) 0)
		 (progn
		   (p4-noinput-buffer-action
		    "diff2" nil t
		    (append (p4-make-list-from-string
			     p4-default-diff-options)
			    (list fn2 fn1)))
		   (p4-activate-diff-buffer "*P4 diff*"))
	       (error "There is no earlier revision to diff."))))
	  (change (p4-describe-internal
		   (append (p4-make-list-from-string p4-default-diff-options)
			   (list change))))
	  (user (p4-async-process-command "user" nil
					  (concat
					   "*P4 User: " user "*")
					  "user" (list user)))
	  (client (p4-async-process-command
		   "client" "Description:\n\t"
		   (concat "*P4 Client: " client "*") "client" (list client)))
	  (label (p4-label (list label)))
	  (branch (p4-branch (list branch)))

	  ;; Check if a "filename link" or an active "diff buffer area" was
	  ;; selected.
	  (t
	   (let ((link-client-name (get-char-property pnt 'link-client-name))
		 (link-depot-name (get-char-property pnt 'link-depot-name))
		 (block-client-name (get-char-property pnt 'block-client-name))
		 (block-depot-name (get-char-property pnt 'block-depot-name))
		 (p4-history-for (get-char-property pnt 'history-for))
		 (first-line (get-char-property pnt 'first-line))
		 (start (get-char-property pnt 'start)))
	     (cond
	      (p4-history-for
	       (p4-file-change-log "filelog" (list p4-history-for)))
	      ((or link-client-name link-depot-name)
	       (p4-find-file-or-print-other-window
		link-client-name link-depot-name))
	      ((or block-client-name block-depot-name)
	       (if first-line
		   (let ((c (max 0 (- pnt
				      (save-excursion
					(goto-char pnt)
					(beginning-of-line)
					(point))
				      1)))
			 (r first-line))
		     (save-excursion
		       (goto-char start)
		       (while (re-search-forward "^[ +>].*\n" pnt t)
			 (setq r (1+ r))))
		     (p4-find-file-or-print-other-window
		      block-client-name block-depot-name)
		     (goto-line r)
		     (if (not block-client-name)
			 (forward-line 1))
		     (beginning-of-line)
		     (goto-char (+ (point) c)))
		 (p4-find-file-or-print-other-window
		  block-client-name block-depot-name)))
	      (t
	       (error "There is no file at that cursor location!"))))))))

(defun p4-find-file-or-print-other-window (client-name depot-name)
  (if client-name
      (find-file-other-window client-name)
    (p4-noinput-buffer-action "print" nil t
			      (list depot-name))
    (p4-activate-print-buffer depot-name t)
    (other-window 1)))

(defun p4-find-file-other-window ()
  "Open/print file"
  (interactive)
  (let ((link-client-name (get-char-property (point) 'link-client-name))
	(link-depot-name (get-char-property (point) 'link-depot-name))
	(block-client-name (get-char-property (point) 'block-client-name))
	(block-depot-name (get-char-property (point) 'block-depot-name)))
    (cond ((or link-client-name link-depot-name)
	   (p4-find-file-or-print-other-window
	    link-client-name link-depot-name)
	   (other-window 1))
	  ((or block-client-name block-depot-name)
	   (p4-find-file-or-print-other-window
	    block-client-name block-depot-name)
	   (other-window 1)))))

(defun p4-filelog-short-format ()
  "Short format"
  (interactive)
  (setq buffer-invisibility-spec t)
  (redraw-display))

(defun p4-filelog-long-format ()
  "Long format"
  (interactive)
  (setq buffer-invisibility-spec (list))
  (redraw-display))

(defun p4-scroll-down-1-line-other-w ()
  "Scroll other window down one line"
  (interactive)
  (scroll-other-window -1))

(defun p4-scroll-up-1-line-other-w ()
  "Scroll other window up one line"
  (interactive)
  (scroll-other-window 1))

(defun p4-scroll-down-1-window-other-w ()
  "Scroll other window down one window"
  (interactive)
  (scroll-other-window
   (- next-screen-context-lines (window-height))))

(defun p4-scroll-up-1-window-other-w ()
  "Scroll other window up one window"
  (interactive)
  (scroll-other-window
   (- (window-height) next-screen-context-lines)))

(defun p4-top-of-buffer-other-w ()
  "Top of buffer, other window"
  (interactive)
  (other-window 1)
  (goto-char (point-min))
  (other-window -1))

(defun p4-bottom-of-buffer-other-w ()
  "Bottom of buffer, other window"
  (interactive)
  (other-window 1)
  (goto-char (point-max))
  (other-window -1))

(defun p4-goto-next-change ()
  "Next change"
  (interactive)
  (let ((c (current-column)))
    (forward-line 1)
    (while (get-char-property (point) 'invisible)
      (forward-line 1))
    (move-to-column c)))

(defun p4-goto-prev-change ()
  "Previous change"
  (interactive)
  (let ((c (current-column)))
    (forward-line -1)
    (while (get-char-property (point) 'invisible)
      (forward-line -1))
    (move-to-column c)))


;; Activate special handling for a buffer generated with a diff-like command
(make-face 'p4-diff-file-face)
(set-face-background 'p4-diff-file-face "gray90")

(make-face 'p4-diff-head-face)
(set-face-background 'p4-diff-head-face "gray95")

(make-face 'p4-diff-ins-face)
(set-face-foreground 'p4-diff-ins-face "blue")

(make-face 'p4-diff-del-face)
(set-face-foreground 'p4-diff-del-face "red")

(make-face 'p4-diff-change-face)
(set-face-foreground 'p4-diff-change-face "dark green")

(defun p4-buffer-set-face-property (regexp face-property)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward regexp nil t)
      (let ((start (match-beginning 0))
	    (end (match-end 0)))
	(p4-set-extent-properties start end
				  (list (cons 'face face-property)))))))

(defun p4-activate-diff-buffer (buffer-name)
  (p4-make-depot-list-buffer buffer-name)
  (save-excursion
    (set-buffer buffer-name)
    (setq buffer-read-only nil)
    (if p4-colorized-diffs
	(progn
	  (p4-buffer-set-face-property "^=.*\n" 'p4-diff-file-face)
	  (p4-buffer-set-face-property "^[@*].*" 'p4-diff-head-face)
	  (p4-buffer-set-face-property "^\\([+>].*\n\\)+" 'p4-diff-ins-face)
	  (p4-buffer-set-face-property "^\\([-<].*\n\\)+" 'p4-diff-del-face)
	  (p4-buffer-set-face-property "^\\(!.*\n\\)+" 'p4-diff-change-face)))

    (goto-char (point-min))
    (while (re-search-forward "^\\(==== //\\).*\n"
			      nil t)
      (let* ((link-client-name (get-char-property (match-end 1) 'link-client-name))
	     (link-depot-name (get-char-property (match-end 1) 'link-depot-name))
	     (start (match-beginning 0))
	     (end (save-excursion
		    (if (re-search-forward "^==== " nil t)
			(match-beginning 0)
		      (point-max)))))
	(if link-client-name
	    (p4-set-extent-properties start end
				      (list (cons 'block-client-name
						  link-client-name))))
	(if link-depot-name
	    (p4-set-extent-properties start end
				      (list (cons 'block-depot-name
						  link-depot-name))))))

    (goto-char (point-min))
    (while (re-search-forward
	    (concat "^[@0-9].*\\([cad+]\\)\\([0-9]*\\).*\n"
		    "\\(\\(\n\\|[^@0-9\n].*\n\\)*\\)") nil t)
      (let ((first-line (string-to-int (match-string 2)))
	    (start (match-beginning 3))
	    (end (match-end 3)))
	(p4-set-extent-properties start end
				  (list (cons 'first-line first-line)
					(cons 'start start)))))

    (goto-char (point-min))
    (let ((stop
	   (if (re-search-forward "^\\(\\.\\.\\.\\|====\\)" nil t)
	       (match-beginning 0)
	     (point-max))))
      (p4-find-change-numbers buffer-name (point-min) stop))

    (goto-char (point-min))
    (if (looking-at "^Change [0-9]+ by \\([^ @]+\\)@\\([^ \n]+\\)")
	(let ((user-match 1)
	      (cl-match 2)
	      cur-user cur-client)
	  (setq cur-user (match-string user-match))
	  (setq cur-client (match-string cl-match))
	  (p4-create-active-link (match-beginning user-match)
				 (match-end user-match)
				 (list (cons 'user cur-user)))
	  (p4-create-active-link (match-beginning cl-match)
				 (match-end cl-match)
				 (list (cons 'client cur-client)))))

    (use-local-map p4-diff-map)
    (setq buffer-read-only t)))


;; The p4 describe command
(defp4cmd p4-describe ()
  "describe" "To get a description for a change number, type \\[p4-describe].\n"
  (interactive)
  (let ((arg-string (p4-make-list-from-string
		     (read-string "p4 describe: "
				  (concat p4-default-diff-options " ")))))
    (p4-describe-internal arg-string)))

;; Internal version of the p4 describe command
(defun p4-describe-internal (arg-string)
  (p4-noinput-buffer-action
   "describe" nil t arg-string)
  (p4-activate-diff-buffer
   (concat "*P4 describe: " (p4-list-to-string arg-string) "*")))

;; The p4 opened command
(defp4cmd p4-opened ()
  "opened"
  "To display list of files opened for pending change, type \\[p4-opened].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 opened: "
					(p4-buffer-file-name-2)))))
    (p4-opened-internal args)))

(defun p4-opened-internal (args)
  (let ((p4-client (p4-current-client)))
    (p4-noinput-buffer-action "opened" nil t args)
    (p4-make-depot-list-buffer (concat "*Opened Files: " p4-client "*"))))

(defun p4-update-opened-list ()
  (if (get-buffer-window (concat "*Opened Files: " (p4-current-client) "*"))
      (progn
	(setq current-prefix-arg nil)
	(p4-opened-internal nil))))

(defun p4-regexp-create-links (buffer-name regexp property)
  (save-excursion
    (set-buffer buffer-name)
    (setq buffer-read-only nil)
    (goto-char (point-min))
    (while (re-search-forward regexp nil t)
      (let ((start (match-beginning 1))
	    (end (match-end 1))
	    (str (match-string 1)))
	(p4-create-active-link start end (list (cons property str)))))
    (setq buffer-read-only t)))

;; The p4 users command
(defp4cmd p4-users ()
  "users" "To display list of known users, type \\[p4-users].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 users: " nil "user"))))
    (p4-noinput-buffer-action "users" nil t args))
  (p4-make-basic-buffer "*P4 users*")
  (p4-regexp-create-links "*P4 users*" "^\\([^ ]+\\).*\n" 'user))

;; The p4 jobs command
(defp4cmd p4-jobs ()
  "jobs" "To display list of jobs, type \\[p4-jobs].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string (p4-read-arg-string "p4 jobs: "))))
    (p4-noinput-buffer-action "jobs" nil t args))
  (p4-make-basic-buffer "*P4 jobs*"))

;; The p4 fix command
(defp4cmd p4-fix ()
  "fix" "To mark jobs as being fixed by a changelist number, type \\[p4-fix].\n"
  (interactive)
  (let ((args (p4-make-list-from-string (p4-read-arg-string "p4 fix: "
							    nil "job"))))
    (p4-noinput-buffer-action "fix" nil t args)))

;; The p4 fixes command
(defp4cmd p4-fixes ()
  "fixes" "To list what changelists fix what jobs, type \\[p4-fixes].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string (p4-read-arg-string "p4 fixes: "))))
    (p4-noinput-buffer-action "fixes" nil t args)
    (p4-make-basic-buffer "*P4 fixes*")))

;; The p4 where command
(defp4cmd p4-where ()
  "where"
  "To show how local file names map into depot names, type \\[p4-where].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 where: "
					(p4-buffer-file-name-2)))))
    (p4-noinput-buffer-action "where" nil 's args)))


(defun p4-async-process-command (p4-this-command &optional
						 p4-regexp
						 p4-this-buffer
						 p4-out-command
						 p4-in-args
						 p4-out-args)
  "Internal function to call an asynchronous process with a local buffer,
instead of calling an external client editor to run within emacs.

Arguments:
P4-THIS-COMMAND is the command that called this internal function.

P4-REGEXP is the optional regular expression to search for to set the cursor
on.

P4-THIS-BUFFER is the optional buffer to create. (Default is *P4 <command>*).

P4-OUT-COMMAND is the optional command that will be used as the command to
be called when `p4-async-call-process' is called.

P4-IN-ARGS is the optional argument passed that will be used as the list of
arguments to the P4-THIS-COMMAND.

P4-OUT-ARGS is the optional argument passed that will be used as the list of
arguments to P4-OUT-COMMAND."
  (let ((dir default-directory))
    (if p4-this-buffer
	(set-buffer (get-buffer-create p4-this-buffer))
      (set-buffer (get-buffer-create (concat "*P4 " p4-this-command "*"))))
    (setq p4-current-command p4-this-command)
    (cd dir))
  (if (zerop (apply 'call-process-region (point-min) (point-max)
		    (p4-check-p4-executable) t t nil
		    "-d" default-directory
		    p4-current-command "-o"
		    p4-in-args))
      (progn
	(goto-char (point-min))
	(insert (concat "# Created using " (p4-emacs-version) ".\n"
			"# Type C-c C-c to submit changes and exit buffer.\n"
			"# Type C-x k to kill current changes.\n"
			"#\n"))
	(if p4-regexp (re-search-forward p4-regexp))
	(indented-text-mode)
	(setq p4-async-minor-mode t)
	(setq fill-column 79)
	(p4-push-window-config)
	(switch-to-buffer-other-window (current-buffer))
	(if p4-out-command
	    (setq p4-current-command p4-out-command))
	(setq p4-current-args p4-out-args)
	(setq buffer-offer-save t)

	(define-key p4-async-minor-map "\C-c\C-c" 'p4-async-call-process)
	(run-hooks 'p4-async-command-hook)
	(set-buffer-modified-p nil)
	(message "C-c C-c to finish editing and exit buffer."))
    (error "%s %s -o failed to complete successfully."
	   (p4-check-p4-executable) p4-current-command)))

(defun p4-async-call-process ()
  "Internal function called by `p4-async-process-command' to process the
buffer after editing is done using the minor mode key mapped to `C-c C-c'."
  (interactive)
  (message "p4 %s ..." p4-current-command)
  (let ((max (point-max)) msg
	(current-command p4-current-command)
	(current-args p4-current-args))
    (goto-char max)
    (if (zerop (apply 'call-process-region (point-min)
		      max (p4-check-p4-executable)
		      nil '(t t) nil
		      "-d" default-directory
		      current-command "-i"
		      current-args))
	(progn
	  (goto-char max)
	  (setq msg (buffer-substring max (point-max)))
	  (delete-region max (point-max))
	  (save-excursion
	    (set-buffer (get-buffer-create p4-output-buffer-name))
	    (delete-region (point-min) (point-max))
	    (insert msg))
	  (kill-buffer nil)
	  (display-buffer p4-output-buffer-name)
	  (p4-partial-cache-cleanup current-command)
	  (message "p4 %s done." current-command)
	  (if (equal current-command "submit")
	      (progn
		(p4-refresh-files-in-buffers)
		(p4-check-mode-all-buffers)
		(if p4-notify
		    (p4-notify p4-notify-list)))))
      (error "%s %s -i failed to complete successfully."
	     (p4-check-p4-executable)
	     current-command))))

(defun p4-cmd-line-flags (args)
  (memq t (mapcar (lambda (x) (not (not (string-match "^-" x))))
		  args)))

;; The p4 change command
(defp4cmd p4-change ()
  "change" "To edit the change specification, type \\[p4-change].\n"
  (interactive)
  (let (args
	(change-buf-name "*P4 New Change*"))
    (if (buffer-live-p (get-buffer change-buf-name))
	(switch-to-buffer-other-window (get-buffer change-buf-name))
      (if current-prefix-arg
	  (setq args (p4-make-list-from-string
		      (p4-read-arg-string "p4 change: " nil))))
      (if (p4-cmd-line-flags args)
	  (p4-noinput-buffer-action "change" nil t args)
	(p4-async-process-command "change" "Description:\n\t"
				  change-buf-name nil args)))))

;; The p4 client command
(defp4cmd p4-client ()
  "client" "To edit a client specification, type \\[p4-client].\n"
  (interactive)
  (let (args
	(client-buf-name "*P4 client*"))
    (if (buffer-live-p (get-buffer client-buf-name))
	(switch-to-buffer-other-window (get-buffer client-buf-name))
      (if current-prefix-arg
	  (setq args (p4-make-list-from-string
		      (p4-read-arg-string "p4 client: " nil "client"))))
      (if (p4-cmd-line-flags args)
	  (p4-noinput-buffer-action "client" nil t args)
	(p4-async-process-command "client" "\\(Description\\|View\\):\n\t"
				  client-buf-name nil args)))))

(defp4cmd p4-clients ()
  "clients" "To list all clients, type \\[p4-clients].\n"
  (interactive)
  (p4-noinput-buffer-action "clients" nil t nil)
  (p4-make-basic-buffer "*P4 clients*")
  (p4-regexp-create-links "*P4 clients*" "^Client \\([^ ]+\\).*\n" 'client))

(defp4cmd p4-branch (args)
  "branch" "Edit a P4-BRANCH specification using \\[p4-branch]."
  (interactive (list
		(p4-make-list-from-string
		 (p4-read-arg-string "p4 branch: " nil "branch"))))
  (if (or (null args) (equal args (list "")))
      (error "Branch must be specified!")
    (if (p4-cmd-line-flags args)
	(p4-noinput-buffer-action "branch" nil t args)
      (p4-async-process-command "branch" "Description:\n\t"
				(concat "*P4 Branch: "
					(car (reverse args)) "*")
				"branch" args))))

(defp4cmd p4-branches ()
  "branches" "To list all branches, type \\[p4-branches].\n"
  (interactive)
  (p4-noinput-buffer-action "branches" nil t nil)
  (p4-make-basic-buffer "*P4 branches*")
  (p4-regexp-create-links "*P4 branches*" "^Branch \\([^ ]+\\).*\n" 'branch))

(defp4cmd p4-label (args)
  "label" "Edit a P4-label specification using \\[p4-label].\n"
  (interactive (list
		(p4-make-list-from-string
		 (p4-read-arg-string "p4 label: " nil "label"))))
  (if (or (null args) (equal args (list "")))
      (error "label must be specified!")
    (if (p4-cmd-line-flags args)
	(p4-noinput-buffer-action "label" nil t args)
      (p4-async-process-command "label" "Description:\n\t"
				(concat "*P4 label: "
					(car (reverse args)) "*")
				"label" args))))

(defp4cmd p4-labels ()
  "labels" "To display list of defined labels, type \\[p4-labels].\n"
  (interactive)
  (p4-noinput-buffer-action "labels" nil t nil)
  (p4-make-basic-buffer "*P4 labels*")
  (p4-regexp-create-links "*P4 labels*" "^Label \\([^ ]+\\).*\n" 'label))

;; The p4 labelsync command
(defp4cmd p4-labelsync ()
  "labelsync"
  "To synchronize a label with the current client contents, type \\[p4-labelsync].\n"
  (interactive)
  (let ((args (p4-make-list-from-string
	       (p4-read-arg-string "p4 labelsync: "))))
    (p4-noinput-buffer-action "labelsync" nil t args))
  (p4-make-depot-list-buffer "*P4 labelsync*"))

(defun p4-filter-out (pred lst)
  (let (res)
    (while lst
      (if (not (funcall pred (car lst)))
	  (setq res (cons (car lst) res)))
      (setq lst (cdr lst)))
    (reverse res)))

;; The p4 submit command
(defp4cmd p4-submit (&optional arg)
  "submit" "To submit a pending change to the depot, type \\[p4-submit].\n"
  (interactive "P")
  (let (args
	(submit-buf-name "*P4 Submit*")
	(change-list (if (integerp arg) arg)))
    (if (buffer-live-p (get-buffer submit-buf-name))
	(switch-to-buffer-other-window (get-buffer submit-buf-name))
      (if change-list
	  (setq args (list "-c" (int-to-string change-list)))
	(if current-prefix-arg
	    (setq args (p4-make-list-from-string
			(p4-read-arg-string "p4 submit: " nil)))))
      (setq args (p4-filter-out (lambda (x) (string= x "-c")) args))
      (p4-save-opened-files)
      (if (or (not (and p4-check-empty-diffs (p4-empty-diff-p)))
	      (progn
		(ding t)
		(yes-or-no-p
		 "File with empty diff opened for edit. Submit anyway? ")))
	  (p4-async-process-command "change" "Description:\n\t"
				    submit-buf-name "submit" args)))))

;; The p4 user command
(defp4cmd p4-user ()
  "user" "To create or edit a user specification, type \\[p4-user].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 user: " nil "user"))))
    (if (p4-cmd-line-flags args)
	(p4-noinput-buffer-action "user" nil t args)
      (p4-async-process-command "user" nil nil nil args))))

;; The p4 job command
(defp4cmd p4-job ()
  "job" "To create or edit a job, type \\[p4-job].\n"
  (interactive)
  (let (args)
    (if current-prefix-arg
	(setq args (p4-make-list-from-string
		    (p4-read-arg-string "p4 job: " nil "job"))))
    (if (p4-cmd-line-flags args)
	(p4-noinput-buffer-action "job" nil t args)
      (p4-async-process-command "job" "Description:\n\t" nil nil args))))

;; The p4 jobspec command
(defp4cmd p4-jobspec ()
  "jobspec" "To edit the job template, type \\[p4-jobspec].\n"
  (interactive)
  (p4-async-process-command "jobspec"))

;; A function to set the current P4 client name
(defun p4-set-client-name (p4-new-client-name)
  "To set the current value of P4CLIENT, type \\[p4-set-client-name].

This will change the current client from the previous client to the new
given value.

Setting this value to nil would disable P4 Version Checking.

`p4-set-client-name' will complete any client names set using the function
`p4-set-my-clients'. The strictness of completion will depend on the
variable `p4-strict-complete' (default is t).

Argument P4-NEW-CLIENT-NAME The new client to set to. The default value is
the current client."
  (interactive (list
		(completing-read "Change Client to: "
				 (if p4-my-clients
				     p4-my-clients
				   'p4-clients-completion)
				 nil p4-strict-complete (p4-current-client))
		))
  (if (or (null p4-new-client-name) (equal p4-new-client-name "nil"))
      (progn
	(setenv "P4CLIENT" nil)
	(if (not (getenv "P4CONFIG"))
	    (message
	     "P4 Version check disabled. Set a valid client name to enable."
	     )))
    (setenv "P4CLIENT" p4-new-client-name)
    (message "P4CLIENT changed to %s" p4-new-client-name)
    (run-hooks 'p4-set-client-hooks)))

(defun p4-get-client-config ()
  "To get the current value of the environment variable P4CONFIG,
type \\[p4-get-client-config].

This will be the current configuration that is in use for access through
Emacs P4."

  (interactive)
  (message "P4CONFIG is %s" (getenv "P4CONFIG")))

(defun p4-set-client-config (p4config)
  "To set the P4CONFIG variable, for use with the current versions of the p4
client.

P4CONFIG is a more flexible mechanism wherein p4 will find the current
client automatically by checking the config file found at the root of a
directory \(recursing all the way to the top\).

In this scenario, a P4CLIENT variable need not be explicitly set.
"
  (interactive "sP4 Config: ")
  (if (or (null p4config) (equal p4config ""))
      (message "P4CONFIG not changed.")
    (setenv "P4CONFIG" p4config)
    (message "P4CONFIG changed to %s" p4config)))

(defun p4-set-my-clients (client-list)
  "To set the client completion list used by `p4-set-client-name', use
this function in your .emacs (or any lisp interaction buffer).

This will change the current client list from the previous list to the new
given value.

Setting this value to nil would disable client completion by
`p4-set-client-name'.

The strictness of completion will depend on the variable
`p4-strict-complete' (default is t).

Argument CLIENT-LIST is the 'list' of clients.

To set your clients using your .emacs, use the following:

\(load-library \"p4\"\)
\(p4-set-my-clients \'(client1 client2 client3)\)"
  (setq p4-my-clients nil)
  (let (p4-tmp-client-var)
    (while client-list
      (setq p4-tmp-client-var (format "%s" (car client-list)))
      (setq client-list (cdr client-list))
      (setq p4-my-clients (append p4-my-clients
				  (list (list p4-tmp-client-var)))))))

;; A function to get the current P4PORT
(defun p4-get-p4-port ()
  "To get the current value of the environment variable P4PORT, type \
\\[p4-get-p4-port].

This will be the current server/port that is in use for access through Emacs
P4."
  (interactive)
  (let ((port (p4-current-server-port)))
    (message "P4PORT is [local: %s], [global: %s]" port (getenv "P4PORT"))
    port))

;; A function to set the current P4PORT
(defun p4-set-p4-port (p4-new-p4-port)
  "To set the current value of P4PORT, type \\[p4-set-p4-port].

This will change the current server from the previous server to the new
given value.

Argument P4-NEW-P4-PORT The new server:port to set to. The default value is
the current value of P4PORT."
  (interactive (list (let
			 ((symbol (read-string "Change server:port to: "
					       (getenv "P4PORT"))))
		       (if (equal symbol "")
			   (getenv "P4PORT")
			 symbol))))
  (if (or (null p4-new-p4-port) (equal p4-new-p4-port "nil"))
      (progn
	(setenv "P4PORT" nil)
	(if (not (getenv "P4CONFIG"))
	    (message
	     "P4 Version check disabled. Set a valid server:port to enable.")))
    (setenv "P4PORT" p4-new-p4-port)
    (message "P4PORT changed to %s" p4-new-p4-port)))

;; The find-file hook for p4.
(defun p4-find-file-hook ()
  "To check while loading the file, if it is a P4 version controlled file."
  (if (or (getenv "P4CONFIG") (getenv "P4CLIENT"))
      (p4-detect-p4)))

(defun p4-refresh-refresh-list (buffile bufname)
  "Refresh the list of files to be refreshed."
  (setq p4-all-buffer-files (delete (list buffile bufname)
				    p4-all-buffer-files))
  (if (not p4-all-buffer-files)
      (progn
	(if (and p4-running-emacs (timerp p4-file-refresh-timer))
	    (cancel-timer p4-file-refresh-timer))
	(if (and p4-running-xemacs p4-file-refresh-timer)
	    (disable-timeout p4-file-refresh-timer))
	(setq p4-file-refresh-timer nil))))

;; Set keymap. We use the C-x p Keymap for all perforce commands
(defvar p4-prefix-map
  (let ((map (make-sparse-keymap)))
    (define-key map "a" 'p4-add)
    (define-key map "b" 'p4-bug-report)
    (define-key map "B" 'p4-branch)
    (define-key map "c" 'p4-client)
    (define-key map "C" 'p4-changes)
    (define-key map "d" 'p4-diff2)
    (define-key map "D" 'p4-describe)
    (define-key map "e" 'p4-edit)
    (define-key map "E" 'p4-reopen)
    (define-key map "\C-f" 'p4-depot-find-file)
    (define-key map "f" 'p4-filelog)
    (define-key map "F" 'p4-files)
    (define-key map "g" 'p4-get-client-name)
    (define-key map "G" 'p4-get)
    (define-key map "h" 'p4-help)
    (define-key map "H" 'p4-have)
    (define-key map "i" 'p4-info)
    (define-key map "I" 'p4-integ)
    (define-key map "j" 'p4-job)
    (define-key map "J" 'p4-jobs)
    (define-key map "l" 'p4-label)
    (define-key map "L" 'p4-labels)
    (define-key map "\C-l" 'p4-labelsync)
    (define-key map "m" 'p4-rename)
    (define-key map "n" 'p4-notify)
    (define-key map "o" 'p4-opened)
    (define-key map "p" 'p4-print)
    (define-key map "P" 'p4-set-p4-port)
    (define-key map "q" 'p4-pop-window-config)
    (define-key map "r" 'p4-revert)
    (define-key map "R" 'p4-refresh)
    (define-key map "\C-r" 'p4-resolve)
    (define-key map "s" 'p4-set-client-name)
    (define-key map "S" 'p4-submit)
    (define-key map "t" 'p4-toggle-vc-mode)
    (define-key map "u" 'p4-user)
    (define-key map "U" 'p4-users)
    (define-key map "v" 'p4-emacs-version)
    (define-key map "V" 'p4-blame)
    (define-key map "w" 'p4-where)
    (define-key map "x" 'p4-delete)
    (define-key map "X" 'p4-fix)
    (define-key map "=" 'p4-diff)
    (define-key map "-" 'p4-ediff)
    (define-key map "?" 'p4-describe-bindings)
    map)
  "The Prefix for P4 Library Commands.")

(if (not (keymapp (lookup-key global-map "\C-xp")))
    (define-key global-map "\C-xp" p4-prefix-map))

;; For users interested in notifying a change, a notification list can be
;; set up using this function.
(defun p4-set-notify-list (p4-new-notify-list &optional p4-supress-stat)
  "To set the current value of P4NOTIFY, type \\[p4-set-notify-list].

This will change the current notify list from the existing list to the new
given value.

An empty string will disable notification.

Argument P4-NEW-NOTIFY-LIST is new value of the notification list.
Optional argument P4-SUPRESS-STAT when t will suppress display of the status
message. "

  (interactive (list (let
			 ((symbol (read-string
				   "Change Notification List to: "
				   p4-notify-list)))
		       (if (equal symbol "")
			   nil
			 symbol))))
  (let ((p4-old-notify-list p4-notify-list))
    (setenv "P4NOTIFY" p4-new-notify-list)
    (setq p4-notify-list p4-new-notify-list)
    (setq p4-notify (not (null p4-new-notify-list)))
    (if (not p4-supress-stat)
	(message "Notification list changed from '%s' to '%s'"
		 p4-old-notify-list p4-notify-list))))

;; To get the current notification list.
(defun p4-get-notify-list ()
  "To get the current value of the environment variable P4NOTIFY,
type \\[p4-get-notify-list].

   This will be the current notification list that is in use for mailing
   change notifications through Emacs P4."

  (interactive)
  (message "P4NOTIFY is %s" p4-notify-list))

(defun p4-notify (users)
  "To notify a list of users of a change submission manually, type
\\[p4-notify].

To do auto-notification, set the notification list with `p4-set-notify-list'
and on each submission, the users in the list will be notified of the
change.

Since this uses the sendmail program, it is mandatory to set the correct
path to the sendmail program in the variable `p4-sendmail-program'.

Also, it is mandatory to set the user's email address in the variable
`p4-user-email'.

Argument USERS The users to notify to. The default value is the notification
list."
  (interactive (list (let
			 ((symbol (read-string "Notify whom? "
					       p4-notify-list)))
		       (if (equal symbol "")
			   nil
			 symbol))))
  (p4-set-notify-list users t)
  (if (and p4-sendmail-program p4-user-email)
      (p4-do-notify)
    (message "Please set p4-sendmail-program and p4-user-email variables.")))

(defun p4-do-notify ()
  "This is the internal notification function called by `p4-notify'."
  (save-excursion
    (if (and p4-notify-list (not (equal p4-notify-list "")))
	(save-excursion
	  (set-buffer (get-buffer-create p4-output-buffer-name))
	  (goto-char (point-min))
	  (if (re-search-forward "[0-9]+.*submitted" (point-max) t)
	      (let (p4-matched-change)
		(setq p4-matched-change (substring (match-string 0) 0 -10))
		(set-buffer (get-buffer-create "*P4 Notify*"))
		(delete-region (point-min) (point-max))
		(call-process-region (point-min) (point-max)
				     (p4-check-p4-executable)
				     t t nil
				     "-d" default-directory
				     "describe" "-s"
				     p4-matched-change)
		(switch-to-buffer "*P4 Notify*")
		(goto-char (point-min))
		(let (p4-chg-desc)
		  (if (re-search-forward "^Change.*$" (point-max) t)
		      (setq p4-chg-desc (match-string 0))
		    (setq p4-chg-desc (concat
				       "Notification of Change "
				       p4-matched-change)))
		  (goto-char (point-min))
		  (insert
		   "From: " p4-user-email "\n"
		   "To: P4 Notification Recipients:;\n"
		   "Subject: " p4-chg-desc "\n")
		  (call-process-region (point-min) (point-max)
				       p4-sendmail-program t t nil
				       "-odi" "-oi" p4-notify-list)

		  (kill-buffer nil)))
	    (save-excursion
	      (set-buffer (get-buffer-create p4-output-buffer-name))
	      (goto-char (point-max))
	      (insert "\np4-do-notify: No Change Submissions found."))))
      (save-excursion
	(set-buffer (get-buffer-create p4-output-buffer-name))
	(goto-char (point-max))
	(insert "\np4-do-notify: Notification list not set.")))))

;; Function to return the current version.
(defun p4-emacs-version ()
  "Return the current Emacs-P4 Integration version."
  (interactive)
  (message (concat (cond (p4-running-xemacs "X")) "Emacs-P4 Integration v%s")
	   p4-emacs-version))

(defun p4-find-p4-config-file ()
  (let ((p4config (getenv "P4CONFIG"))
	(p4-cfg-dir (cond ((p4-buffer-file-name)
			   (file-name-directory
			    (file-truename (p4-buffer-file-name))))
			  (t (file-truename default-directory)))))
    (if (not p4config)
	nil
      (let (found at-root)
	(while (not (or found at-root))
	  (let ((parent-dir (file-name-directory
			     (directory-file-name
			      p4-cfg-dir))))
	    (if (file-exists-p (concat p4-cfg-dir p4config))
		(setq found (concat p4-cfg-dir p4config)))
	    (setq at-root (string-equal parent-dir p4-cfg-dir))
	    (setq p4-cfg-dir parent-dir)))
	found))))

(defun p4-detect-p4 ()
  (if (or (not p4-use-p4config-exclusively)
	  (p4-find-p4-config-file))
      (p4-check-mode)))

(defun p4-get-add-branch-files (&optional name-list)
  (let ((output-buffer (p4-depot-output "opened" name-list))
	files depot-map)
    (save-excursion
      (set-buffer output-buffer)
      (goto-char (point-min))
      (while (re-search-forward "^\\(//[^/@#]+/[^#\n]*\\)#[0-9]+ - add " nil t)
	(setq files (cons (cons (match-string 1) "Add")
			  files)))
      (goto-char (point-min))
      (while (re-search-forward "^\\(//[^/@#]+/[^#\n]*\\)#[0-9]+ - branch " nil t)
	(setq files (cons (cons (match-string 1) "Branch")
			  files))))
    (kill-buffer output-buffer)
    (setq depot-map (p4-map-depot-files (mapcar 'car files)))
    (mapcar (lambda (x) (cons (cdr (assoc (car x) depot-map))
			      (cdr x))) files)))

(defun p4-get-have-files (file-list)
  (let ((output-buffer (p4-depot-output "have" file-list))
	line files depot-map elt)
    (while (setq line (p4-read-depot-output output-buffer))
      (if (string-match "^\\(//[^/@#]+/[^#\n]*\\)#\\([0-9]+\\) - " line)
	  (setq files (cons (cons (match-string 1 line)
				  (match-string 2 line))
			    files))))
    (kill-buffer output-buffer)
    (setq depot-map (p4-map-depot-files (mapcar 'car files)))
    (setq files (mapcar (lambda (x) (cons (cdr (assoc (car x) depot-map))
					  (cdr x))) files))
    (while file-list
      (setq elt (car file-list))
      (setq file-list (cdr file-list))
      (if (not (assoc elt files))
	  (setq files (cons (cons elt nil) files))))
    files))

;; A function to check if the file being opened is version controlled by p4.
(defun p4-is-vc (&optional file-mode-cache filename)
  "If a file is controlled by P4 then return version else return nil."
  (if (not filename)
      (setq filename (p4-buffer-file-name)))
  (let (version done)
    (let ((el (assoc filename file-mode-cache)))
      (setq done el)
      (setq version (cdr el)))
    (if (and (not done) filename)
	(let ((output-buffer (p4-depot-output "have" (list filename)))
	      line)
	  (setq line (p4-read-depot-output output-buffer))
	  (kill-buffer output-buffer)
	  (if (string-match "^//[^/@#]+/[^#\n]*#\\([0-9]+\\) - " line)
	      (setq version (match-string 1 line)))
	  (setq done version)))
    (if (and (not done) (not file-mode-cache))
	(progn
	  (setq file-mode-cache
		(p4-get-add-branch-files (and filename (list filename))))
	  (setq version (cdr (assoc filename file-mode-cache)))))
    version))

(defun p4-check-mode (&optional file-mode-cache)
  "Check to see whether we should export the menu map to this buffer.

Turning on P4 mode calls the hooks in the variable `p4-mode-hook' with
no args."
  (setq p4-mode nil)
  (if p4-do-find-file
      (progn
	(setq p4-vc-check (p4-is-vc file-mode-cache))
	(if p4-vc-check
	    (progn
	      (p4-menu-add)
	      (setq p4-mode (concat " P4:" p4-vc-check))))
	(p4-force-mode-line-update)
	(let ((buffile (p4-buffer-file-name))
	      (bufname (buffer-name)))
	  (if (and p4-vc-check (not (member (list buffile bufname)
					    p4-all-buffer-files)))
	      (add-to-list 'p4-all-buffer-files (list buffile bufname))))
	(if (and (not p4-file-refresh-timer) (not (= p4-file-refresh-timer-time 0)))
	    (setq p4-file-refresh-timer
		  (cond (p4-running-emacs
			 (run-at-time nil p4-file-refresh-timer-time
				      'p4-refresh-files-in-buffers))
			(p4-running-xemacs
			 (add-timeout p4-file-refresh-timer-time
				      'p4-refresh-files-in-buffers nil
				      p4-file-refresh-timer-time)))))
	;; run hooks
	(and p4-vc-check (run-hooks 'p4-mode-hook))
	p4-vc-check)))

(defun p4-refresh-files-in-buffers (&optional arg)
  "Check to see if all the files that are under P4 version control are
actually up-to-date, if in buffers, or need refreshing."
  (interactive)
  (let ((p4-all-my-files p4-all-buffer-files) buffile bufname thiselt)
    (while p4-all-my-files
      (setq thiselt (car p4-all-my-files))
      (setq p4-all-my-files (cdr p4-all-my-files))
      (setq buffile (car thiselt))
      (setq bufname (cadr thiselt))
      (if (buffer-live-p (get-buffer bufname))
	  (save-excursion
	    (let ((buf (get-buffer bufname)))
	      (set-buffer buf)
	      (if p4-auto-refresh
		  (if (not (buffer-modified-p buf))
		      (if (not (verify-visited-file-modtime buf))
			  (if (file-readable-p buffile)
			      (revert-buffer t t)
			    (p4-check-mode))))
		(if (file-readable-p buffile)
		    (find-file-noselect buffile t)
		  (p4-check-mode)))
	      (setq buffer-read-only (not (file-writable-p
					   (p4-buffer-file-name))))))
	(p4-refresh-refresh-list buffile bufname)))))

(defun p4-check-mode-all-buffers ()
  "Call p4-check-mode for all buffers under P4 version control"
  (let ((p4-all-my-files p4-all-buffer-files) buffile bufname thiselt
	file-mode-cache)
    (if (and p4-all-my-files p4-do-find-file)
	(setq file-mode-cache
	      (append (p4-get-add-branch-files)
		      (p4-get-have-files (mapcar 'car p4-all-my-files)))))
    (while p4-all-my-files
      (setq thiselt (car p4-all-my-files))
      (setq p4-all-my-files (cdr p4-all-my-files))
      (setq buffile (car thiselt))
      (setq bufname (cadr thiselt))
      (if (buffer-live-p (get-buffer bufname))
	  (save-excursion
	    (set-buffer (get-buffer bufname))
	    (p4-check-mode file-mode-cache))
	(p4-refresh-refresh-list buffile bufname)))))

;; Force mode line updation for different Emacs versions
(defun p4-force-mode-line-update ()
  "To Force the mode line update for different flavors of Emacs."
  (cond (p4-running-xemacs
	 (redraw-modeline))
	(p4-running-emacs
	 (force-mode-line-update))))

;; In case, the P4 server is not available, or when operating off-line, the
;; p4-find-file-hook becomes a pain... this functions toggles the use of the
;; hook when opening files.

(defun p4-toggle-vc-mode ()
  "In case, the P4 server is not available, or when working off-line, toggle
the VC check on/off when opening files."
  (interactive)
  (setq p4-do-find-file (not p4-do-find-file))
  (message (concat "P4 mode check " (if p4-do-find-file
					"enabled."
				      "disabled."))))

;; Wrap C-x C-q to allow p4-edit/revert and also to ensure that
;; we don't stomp on vc-toggle-read-only.

(defun p4-toggle-read-only (&optional arg)
  "If p4-mode is non-nil, \\[p4-toggle-read-only] toggles between `p4-edit'
and `p4-revert'. If ARG is non-nil, p4-offline-mode will be enabled for this
buffer before the toggling takes place. In p4-offline-mode, toggle between
making the file writable and write protected."
  (interactive "P")
  (if (and arg p4-mode)
      (setq p4-mode nil
	    p4-offline-mode t))
  (cond
   (p4-mode
    (if buffer-read-only
	(p4-edit p4-verbose)
      (p4-revert p4-verbose)))
   (p4-offline-mode
    (toggle-read-only)
    (if buffer-file-name
	(let ((mode (file-modes buffer-file-name)))
	  (if buffer-read-only
	      (setq mode (logand mode (lognot 128)))
	    (setq mode (logior mode 128)))
	  (set-file-modes buffer-file-name mode))))))

(defun p4-browse-web-page ()
  "Browse the p4.el web page."
  (interactive)
  (require 'browse-url)
  (browse-url p4-web-page))

(defun p4-bug-report ()
  (interactive)
  (if (string-match " 19\\." (emacs-version))
      ;; unfortunately GNU Emacs 19.x doesn't have compose-mail
      (mail nil p4-emacs-maintainer (concat "BUG REPORT: "
					    (p4-emacs-version)))
    (compose-mail p4-emacs-maintainer (concat "BUG REPORT: "
					      (p4-emacs-version))))
  (goto-char (point-min))
  (re-search-forward (concat "^" (regexp-quote mail-header-separator) "\n"))
  ;; Insert warnings for novice users.
  (insert
   "This bug report will be sent to the P4-Emacs Integration Maintainer,\n"
   p4-emacs-maintainer "\n\n")
  (insert (concat (emacs-version) "\n\n"))
  (insert "A brief description of the problem and how to reproduce it:\n")
  (save-excursion
    (let ((message-buf (get-buffer
			(cond (p4-running-xemacs " *Message-Log*")
			      (p4-running-emacs "*Messages*")))))
      (if message-buf
	  (let (beg-pos
		(end-pos (point-max)))
	    (save-excursion
	      (set-buffer message-buf)
	      (goto-char end-pos)
	      (forward-line -10)
	      (setq beg-pos (point)))
	    (insert "\n\nRecent messages:\n")
	    (insert-buffer-substring message-buf beg-pos end-pos))))))

(defun p4-describe-bindings ()
  "A function to list the key bindings for the p4 prefix map"
  (interactive)
  (save-excursion
    (p4-push-window-config)
    (let ((map (make-sparse-keymap))
	  (p4-bindings-buffer "*P4 key bindings*"))
      (get-buffer-create p4-bindings-buffer)
      (cond
       (p4-running-xemacs
	(set-buffer p4-bindings-buffer)
	(delete-region (point-min) (point-max))
	(insert "Key Bindings for P4 Mode\n------------------------\n")
	(describe-bindings-internal p4-prefix-map))
       (p4-running-emacs
	(kill-buffer p4-bindings-buffer)
	(describe-bindings "\C-xp")
	(set-buffer "*Help*")
	(rename-buffer p4-bindings-buffer)))
      (define-key map "q" 'p4-quit-current-buffer)
      (use-local-map map)
      (display-buffer p4-bindings-buffer))))

;; Break up a string into a list of words
;; (p4-make-list-from-string "ab c de  f") -> ("ab" "c" "de" "f")
(defun p4-make-list-from-string (str)
  (let (lst)
    (while (or (string-match "^ *\"\\([^\"]*\\)\"" str)
	       (string-match "^ *\'\\([^\']*\\)\'" str)
	       (string-match "^ *\\([^ ]+\\)" str))
      (setq lst (append lst (list (match-string 1 str))))
      (setq str (substring str (match-end 0))))
    lst))

(defun p4-list-to-string (lst)
  (mapconcat (lambda (x) x) lst " "))

;; Return the file name associated with a buffer. If the real buffer file
;; name doesn't exist, try special filename tags set in some of the p4
;; buffers.
(defun p4-buffer-file-name-2 ()
  (cond ((p4-buffer-file-name))
	((get-char-property (point) 'link-client-name))
	((get-char-property (point) 'link-depot-name))
	((get-char-property (point) 'block-client-name))
	((get-char-property (point) 'block-depot-name))
	((if (and (fboundp 'dired-get-filename)
		  (dired-get-filename nil t))
	     (p4-follow-link-name (dired-get-filename nil t))))))

(defun p4-buffer-file-name ()
  (cond (buffer-file-name
	 (p4-follow-link-name buffer-file-name))
	(t nil)))

(defun p4-follow-link-name (name)
  (if p4-follow-symlinks
      (file-truename name)
    name))

(defvar p4-depot-filespec-history nil
  "History for p4-depot filespecs.")

(defvar p4-depot-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a filespec and
cdr is the list of anwers")

(defvar p4-branches-history nil
  "History for p4 clients.")

(defvar p4-branches-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a client and
cdr is the list of answers??")

(defvar p4-clients-history nil
  "History for p4 clients.")

(defvar p4-clients-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a client and
cdr is the list of answers??")

(defvar p4-jobs-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a client and
cdr is the list of answers??")

(defvar p4-labels-history nil
  "History for p4 clients.")

(defvar p4-labels-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a client and
cdr is the list of answers??")

(defvar p4-users-completion-cache nil
  "Cache for `p4-depot-completion'.
It is a list of lists whose car is a client and
cdr is the list of answers??")

(defvar p4-arg-string-history nil
  "History for p4 command arguments")

(defun p4-depot-completion-search (filespec cmd)
  "Look into `p4-depot-completion-cache' for filespec.
Filespec is the candidate for completion, so the
exact file specification is \"filespec*\".

If found in cache, return a list whose car is FILESPEC and cdr is the list
of matches.
If not found in cache, return nil.
So the 'no match' answer is different from 'not in cache'."
  (let ((l (cond
	    ((equal cmd "branches") p4-branches-completion-cache)
	    ((equal cmd "clients") p4-clients-completion-cache)
	    ((equal cmd "dirs") p4-depot-completion-cache)
	    ((equal cmd "jobs") p4-jobs-completion-cache)
	    ((equal cmd "labels") p4-labels-completion-cache)
	    ((equal cmd "users") p4-users-completion-cache)))
	dir list)

    (if (and p4-cleanup-cache (not p4-timer))
	(setq p4-timer (cond (p4-running-emacs
			      (run-at-time p4-cleanup-time nil
					   'p4-cache-cleanup))
			     (p4-running-xemacs
			      (add-timeout p4-cleanup-time 'p4-cache-cleanup
					   nil nil)))))
    (while l
      (if (string-match (concat "^" (car (car l)) "[^/]*$") filespec)
	  (progn
	    ;; filespec is included in cache
	    (if (string= (car (car l)) filespec)
		(setq list (cdr (car l)))
	      (setq dir (cdr (car l)))
	      (while dir
		(if (string-match (concat "^" filespec) (car dir))
		    (setq list (cons (car dir) list)))
		(setq dir (cdr dir))))
	    (setq l nil
		  list (cons filespec list))))
      (setq l (cdr l)))
    list))

(defun p4-cache-cleanup (&optional arg)
  "Cleanup all the completion caches."
  (message "Cleaning up the p4 caches ...")
  (setq p4-branches-completion-cache nil)
  (setq p4-clients-completion-cache nil)
  (setq p4-depot-completion-cache nil)
  (setq p4-jobs-completion-cache nil)
  (setq p4-labels-completion-cache nil)
  (setq p4-users-completion-cache nil)
  (if (and p4-running-emacs (timerp p4-timer)) (cancel-timer p4-timer))
  (if (and p4-running-xemacs p4-timer) (disable-timeout p4-timer))
  (setq p4-timer nil)
  (message "Cleaning up the p4 caches ... done."))

(defun p4-partial-cache-cleanup (type)
  "Cleanup a specific completion cache."
  (cond ((string= type "branch")
	 (setq p4-branches-completion-cache nil))
	((string= type "client")
	 (setq p4-clients-completion-cache nil))
	((or (string= type "submit") (string= type "change"))
	 (setq p4-depot-completion-cache nil))
	((string= type "job")
	 (setq p4-jobs-completion-cache nil))
	((string= type "label")
	 (setq p4-labels-completion-cache nil))
	((string= type "user")
	 (setq p4-users-completion-cache nil))))

(defun p4-read-depot-output (buffer &optional regexp)
  "Reads first line of BUFFER and returns it.
Read lines are deleted from buffer.

If optional REGEXP is passed in, return the substring of the first line that
matched the REGEXP."

  (save-excursion
    (set-buffer buffer)
    (goto-char (point-min))
    (forward-line)

    (let ((line (buffer-substring (point-min) (point))))
      (if (string= line "")
	  nil
	(delete-region (point-min) (point))
	(if (and regexp (string-match regexp line))
	    (setq line (substring line (match-beginning 1) (match-end 1))))

	;; remove trailing newline
	(if (equal (substring line (1- (length line)) (length line)) "\n")
	    (substring line 0 (1- (length line)))
	  line)))))

(defun p4-completion-helper (filespec cmd var regexp)
  (let (output-buffer line list)
    (message "Making %s completion list..." cmd)
    (setq output-buffer (p4-depot-output cmd))
    (while (setq line (p4-read-depot-output
		       output-buffer regexp))
      (if line
	  (setq list (cons line list))))
    (kill-buffer output-buffer)
    (set var
	 (cons (cons filespec list) (eval var)))
    list))

(defun p4-depot-completion-build (filespec cmd)
  "Ask Perforce for a list of files and directories beginning with FILESPEC."
  (let (output-buffer line list)
    (cond
     ((equal cmd "branches")
      (setq list (p4-completion-helper
		  filespec cmd 'p4-branches-completion-cache
		  "^Branch \\([^ \n]*\\) [0-9][0-9][0-9][0-9]/.*$")))
     ((equal cmd "clients")
      (setq list (p4-completion-helper
		  filespec cmd 'p4-clients-completion-cache
		  "^Client \\([^ \n]*\\) [0-9][0-9][0-9][0-9]/.*$")))

     ((equal cmd "dirs")
      (message "Making p4 completion list...")
      (setq output-buffer (p4-depot-output cmd
					   (list (concat filespec "*"))))
      (while (setq line (p4-read-depot-output output-buffer))
	(if (not (string-match "no such file" line))
	    (setq list (cons (concat line "/") list))))
      (kill-buffer output-buffer)
      (setq output-buffer (p4-depot-output "files"
					   (list (concat filespec "*"))))
      (while (setq line (p4-read-depot-output output-buffer))
	(if (string-match "^\\(.+\\)#[0-9]+ - " line)
	    (setq list (cons (match-string 1 line) list))))
      (kill-buffer output-buffer)
      (setq p4-depot-completion-cache
	    (cons (cons filespec list) p4-depot-completion-cache)))

     ((equal cmd "jobs")
      (setq list (p4-completion-helper
		  filespec cmd 'p4-jobs-completion-cache
		  "\\([^ \n]*\\) on [0-9][0-9][0-9][0-9]/.*$")))
     ((equal cmd "labels")
      (setq list (p4-completion-helper
		  filespec cmd 'p4-labels-completion-cache
		  "^Label \\([^ \n]*\\) [0-9][0-9][0-9][0-9]/.*$")))
     ((equal cmd "users")
      (setq list (p4-completion-helper
		  filespec cmd 'p4-users-completion-cache
		  "^\\([^ ]+\\).*$"))))
    (message nil)
    (cons filespec list)))

(defun p4-completion-builder (type)
  `(lambda (string predicate action)
     ,(concat "Completion function for Perforce " type ".

Using the mouse in completion buffer on a client will select it
and exit, unlike standard selection. This is because
`choose-completion-string' (in simple.el) has a special code for
file name selection.")
     (let (list)
       ,(if (string= type "dirs")
	    ;; when testing for an exact match, remove trailing /
	    `(if (and (eq action 'lambda)
		      (eq (aref string (1- (length string))) ?/))
		 (setq string (substring string 0 (1- (length string))))))

       ;; First, look in cache
       (setq list (p4-depot-completion-search string ,type))

       ;; If not found in cache, build list.
       (if (not list)
	   (setq list (p4-depot-completion-build string ,type)))

       (cond
	;; try completion
	((null action)
	 (try-completion string (mapcar 'list (cdr list)) predicate))
	;; all completions
	((eq action t)
	 (let ((lst
		(all-completions string (mapcar 'list (cdr list)) predicate)))
	   ,(if (string= type "dirs")
		`(setq lst (mapcar (lambda (s)
				     (if (string-match ".*/\\(.+\\)" s)
					 (match-string 1 s)
				       s))
				   lst)))
	   lst))
	;; Test for an exact match
	(t
	 (and (>= (length list) 2)
	      (member (car list) (cdr list))))))))

(defalias 'p4-branches-completion (p4-completion-builder "branches"))
(defalias 'p4-clients-completion (p4-completion-builder "clients"))
(defalias 'p4-depot-completion (p4-completion-builder "dirs"))
(defalias 'p4-jobs-completion (p4-completion-builder "jobs"))
(defalias 'p4-labels-completion (p4-completion-builder "labels"))
(defalias 'p4-users-completion (p4-completion-builder "users"))


(defun p4-read-arg-string (prompt &optional initial type)
  (let ((minibuffer-local-completion-map
	 (copy-keymap minibuffer-local-completion-map)))
    (define-key minibuffer-local-completion-map " " 'self-insert-command)
    (completing-read prompt
		     (cond ((not type)
			    'p4-arg-string-completion)
			   ((string= type "branch")
			    'p4-branch-string-completion)
			   ((string= type "client")
			    'p4-client-string-completion)
			   ((string= type "label")
			    'p4-label-string-completion)
			   ((string= type "job")
			    'p4-job-string-completion)
			   ((string= type "user")
			    'p4-user-string-completion))
		     nil nil
		     initial 'p4-arg-string-history)))

(defun p4-arg-string-completion (string predicate action)
  (let ((first-part "") completion)
    (if (string-match "^\\(.* +\\)\\(.*\\)" string)
	(progn
	  (setq first-part (match-string 1 string))
	  (setq string (match-string 2 string))))
    (cond ((string-match "-b +$" first-part)
	   (setq completion (p4-branches-completion string predicate action)))
	  ((string-match "-t +$" first-part)
	   (setq completion (p4-list-completion
			     string (list "text " "xtext " "binary "
					  "xbinary " "symlink ")
			     predicate action)))
	  ((string-match "-j +$" first-part)
	   (setq completion (p4-jobs-completion string predicate action)))
	  ((string-match "-l +$" first-part)
	   (setq completion (p4-labels-completion string predicate action)))
	  ((string-match "\\(.*status=\\)\\(.*\\)" string)
	   (setq first-part (concat first-part (match-string 1 string)))
	   (setq string (match-string 2 string))
	   (setq completion (p4-list-completion
			     string (list "open " "closed " "suspended ")
			     predicate action)))
	  ((or (string-match "\\(.*@.+,\\)\\(.*\\)" string)
	       (string-match "\\(.*@\\)\\(.*\\)" string))
	   (setq first-part (concat first-part (match-string 1 string)))
	   (setq string (match-string 2 string))
	   (setq completion (p4-labels-completion string predicate action)))
	  ((string-match "\\(.*#\\)\\(.*\\)" string)
	   (setq first-part (concat first-part (match-string 1 string)))
	   (setq string (match-string 2 string))
	   (setq completion (p4-list-completion
			     string (list "none" "head" "have")
			     predicate action)))
	  ((string-match "^//" string)
	   (setq completion (p4-depot-completion string predicate action)))
	  ((string-match "\\(^-\\)\\(.*\\)" string)
	   (setq first-part (concat first-part (match-string 1 string)))
	   (setq string (match-string 2 string))
	   (setq completion (p4-list-completion
			     string (list "a " "af " "am " "as " "at " "ay "
					  "b " "c " "d " "dc " "dn "
					  "ds " "du " "e " "f " "i " "j "
					  "l " "m " "n " "q " "r " "s " "sa "
					  "sd " "se " "sr " "t " "v ")
			     predicate action)))
	  (t
	   (setq completion (p4-file-name-completion string
						     predicate action))))
    (cond ((null action) ;; try-completion
	   (if (stringp completion)
	       (concat first-part completion)
	     completion))
	  ((eq action t) ;; all-completions
	   completion)
	  (t             ;; exact match
	   completion))))

(defun p4-list-completion (string lst predicate action)
  (let ((collection (mapcar 'list lst)))
    (cond ((not action)
	   (try-completion string collection predicate))
	  ((eq action t)
	   (all-completions string collection predicate))
	  (t
	   (eq (try-completion string collection predicate) t)))))

(defun p4-file-name-completion (string predicate action)
  (if (string-match "//\\(.*\\)" string)
      (setq string (concat "/" (match-string 1 string))))
  (setq string (substitute-in-file-name string))
  (setq string (p4-follow-link-name (expand-file-name string)))
  (let ((dir-path "") completion)
    (if (string-match "^\\(.*[/\\]\\)\\(.*\\)" string)
	(progn
	  (setq dir-path (match-string 1 string))
	  (setq string (match-string 2 string))))
    (cond ((not action)
	   (setq completion (file-name-completion string dir-path))
	   (if (stringp completion)
	       (concat dir-path completion)
	     completion))
	  ((eq action t)
	   (file-name-all-completions string dir-path))
	  (t
	   (eq (file-name-completion string dir-path) t)))))

(defun p4-string-completion-builder (completion-function)
  `(lambda (string predicate action)
     (let ((first-part "") completion)
       (if (string-match "^\\(.* +\\)\\(.*\\)" string)
	   (progn
	     (setq first-part (match-string 1 string))
	     (setq string (match-string 2 string))))
       (cond ((string-match "^-" string)
	      (setq completion nil))
	     (t
	      (setq completion
		    (,completion-function string predicate action))))
       (cond ((null action);; try-completion
	      (if (stringp completion)
		  (concat first-part completion)
		completion))
	     ((eq action t);; all-completions
	      completion)
	     (t;; exact match
	      completion)))))

(defalias 'p4-branch-string-completion (p4-string-completion-builder
					'p4-branches-completion))

(defalias 'p4-client-string-completion (p4-string-completion-builder
					'p4-clients-completion))

(defalias 'p4-job-string-completion (p4-string-completion-builder
				     'p4-jobs-completion))

(defalias 'p4-label-string-completion (p4-string-completion-builder
				       'p4-labels-completion))

(defalias 'p4-user-string-completion (p4-string-completion-builder
				      'p4-users-completion))

(defun p4-depot-find-file (file)
  (interactive (list (completing-read "Enter filespec: "
				      'p4-depot-completion
				      nil nil
				      p4-default-depot-completion-prefix
				      'p4-depot-filespec-history)))
  (let ((lfile (cdar (p4-map-depot-files (list file)))))
    (if lfile
	(find-file lfile)
      (if (get-file-buffer file)
	  (switch-to-buffer-other-window file)
	(get-buffer-create file)
	(set-buffer file)
	(p4-noinput-buffer-action "print" nil t (list file))
	(p4-activate-print-buffer file t)))))


;; A function to get the current P4 client name
(defun p4-get-client-name ()
  "To get the current value of the environment variable P4CLIENT,
type \\[p4-get-client-name].

This will be the current client that is in use for access through
Emacs P4."
  (interactive)
  (let ((client (p4-current-client)))
    (message "P4CLIENT [local: %s], [global: %s]" client (getenv "P4CLIENT"))
    client))

(defun p4-get-config-info (file-name token)
  (let ((output-buffer (generate-new-buffer p4-output-buffer-name))
	(data (getenv token)))
    (save-excursion
      (set-buffer output-buffer)
      (goto-char (point-min))
      (insert-file-contents file-name)
      (goto-char (point-min))
      (if (re-search-forward (concat "^" (regexp-quote token) "=\\(.*\\)")
			     nil t)
	  (setq data (match-string 1))))
    (kill-buffer output-buffer)
    data))

(defun p4-current-client ()
  "Get the current local client, or the global client, if that."
  (let ((p4-config-file (p4-find-p4-config-file))
	cur-client pmin)
    (if (not p4-config-file)
	(setq cur-client (getenv "P4CLIENT"))
      (setq cur-client (p4-get-config-info p4-config-file "P4CLIENT")))
    (if (not cur-client)
	(save-excursion
	  (get-buffer-create p4-output-buffer-name)
	  (set-buffer p4-output-buffer-name)
	  (goto-char (point-max))
	  (setq pmin (point))
	  (if (zerop (p4-call-p4-here "info"))
	      (progn
		(goto-char pmin)
		(if (re-search-forward "^Client name:[ \t]+\\(.*\\)$" nil t)
		    (setq cur-client (match-string 1)))
		(delete-region pmin (point-max))))))
    cur-client))

(defun p4-current-server-port ()
  "Get the current local server:port address, or the global server:port, if
that."
  (let ((p4-config-file (p4-find-p4-config-file)))
    (if (not p4-config-file)
	(getenv "P4PORT")
      (p4-get-config-info p4-config-file "P4PORT"))))

(defun p4-save-opened-files ()
  (get-buffer-create p4-output-buffer-name);; We do these two lines
  (kill-buffer p4-output-buffer-name)      ;; to ensure no duplicates
  (let ((output-buffer (p4-depot-output "opened"))
	opened)
    (save-excursion
      (set-buffer output-buffer)
      (goto-char (point-min))
      (while (re-search-forward "^\\(.*\\)#[0-9]+ - " nil t)
	(setq opened (cons (match-string 1) opened))))
    (kill-buffer output-buffer)
    (setq opened (mapcar 'cdr (p4-map-depot-files opened)))
    (save-window-excursion
      (map-y-or-n-p
       (function
	(lambda (buffer)
	  (and (buffer-modified-p buffer)
	       (not (buffer-base-buffer buffer))
	       (buffer-file-name buffer)
	       (member (buffer-file-name buffer) opened)
	       (format "Save file %s? "
		       (buffer-file-name buffer)))))
       (function
	(lambda (buffer)
	  (set-buffer buffer)
	  (save-buffer)))
       (buffer-list)
       '("buffer" "buffers" "save")))))

(defun p4-empty-diff-p ()
  "Return t if there exists a file opened for edit with an empty diff"
  (let ((buffer (get-buffer-create "p4-edp-buf"))
	opened empty-diff)
    (p4-exec-p4 buffer (list "opened") t)
    (save-excursion
      (set-buffer buffer)
      (goto-char (point-min))
      (while (re-search-forward "^\\(.*\\)#[0-9]* - edit.*" nil t)
	(setq opened (cons (match-string 1) opened))))
    (if opened
	(progn
	  (p4-exec-p4 buffer (list "diff") t)
	  (save-excursion
	    (set-buffer buffer)
	    (goto-char (point-max))
	    (insert "====\n")
	    (goto-char (point-min))
	    (while (re-search-forward "^==== \\([^#\n]+\\)#.*\n====" nil t)
	      (if (member (match-string 1) opened)
		  (progn
		    (setq empty-diff t)
		    (goto-char (point-max))))))))
    (kill-buffer buffer)
    empty-diff))

(provide 'p4)

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