Source

clearcase / clearcase.el

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
;;; clearcase.el --- ClearCase/Emacs integration.

;;{{{ Introduction

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This is a ClearCase/Emacs integration.
;;
;; Author: esler@rational.com
;;
;; How to use
;; ==========
;;
;;   0. Make sure you're using Gnu Emacs-20.4 or later or a recent XEmacs.
;;      In general it seems to work better in Gnu Emacs than in XEmacs,
;;      although many XEmacs users have no problems at all with it.
;;
;;   1. Make sure that you DON'T load old versions of vc-hooks.el which contain
;;      incompatible versions of the tq package (functions tq-enqueue and
;;      friends). In particular, Bill Sommerfeld's VC/CC integration has this
;;      problem.
;;
;;   2. Copy the files (or at least the clearcase.elc file) to a directory
;;      on your emacs-load-path.
;;
;;   3. Insert this in your emacs startup file:  (load "clearcase")
;;
;; When you begin editing in any view-context, a ClearCase menu will appear
;; and ClearCase Minor Mode will be activated for you.
;;
;; Summary of features
;; ===================
;;
;;   Keybindings compatible with Emacs' VC (where it makes sense)
;;   Richer interface than VC
;;   Works on NT and Unix
;;   Context sensitive menu (Emacs knows the ClearCase-status of files)
;;   Snapshot view support: update, version comparisons
;;   Can use Emacs Ediff for version comparison display
;;   Dired Mode:
;;     - en masse checkin/out etc
;;     - enhanced display
;;     - browse version tree
;;   Completion of viewnames, version strings
;;   Auto starting of views referenced as /view/TAG/.. (or \\view\TAG\...)
;;   Emacs for editing comments, config specs
;;   Standard ClearCase GUI tools launchable from Emacs menu
;;     - version tree browser
;;     - project browser
;;     - UCM deliver
;;     - UCM rebase
;;   Operations directly available from Emacs menu/keymap:
;;     create-activity
;;     set-activity
;;     mkelem,
;;     checkout
;;     checkin,
;;     unco,
;;     describe
;;     list history
;;     mkbrtype
;;     update view
;;     version comparisons using ediff, diff or applet
;;   Auto version-stamping (if enabled, e.g in this file)
;;
;; Acknowledgements
;; ================
;;
;; The help of the following is gratefully acknowledged:
;;
;;   XEmacs support and other bugfixes:
;;
;;     Rod Whitby
;;     Adrian Aichner
;;
;;   This was a result of examining earlier versions of VC and VC/ClearCase
;;   integrations and borrowing freely therefrom.  Accordingly, the following
;;   are ackowledged as contributors:
;;
;;   VC/ClearCase integration authors:
;;
;;     Bill Sommerfeld
;;     Rod Whitby
;;     Andrew Markebo
;;     Andy Eskilsson
;;     Paul Smith
;;     John Kohl
;;     Chris Felaco
;;
;;   VC authors:
;;
;;     Eric S. Raymond
;;     Andre Spiegel
;;     Sebastian Kremer
;;     Richard Stallman
;;     Per Cederqvist
;;     ttn@netcom.com
;;     Andre Spiegel
;;     Jonathan Stigelman
;;     Steve Baur
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;}}}

;;{{{ Version info

(defconst clearcase-version-stamp "ClearCase-version: </main/188>")
(defconst clearcase-version (substring clearcase-version-stamp 19))
(defconst clearcase-maintainer-address "esler@rational.com")
(defconst clearcase-xemacs-package-maintainer-address
  "Michael Diers <mdiers@xemacs.org>, xemacs-beta@xemacs.org")
(defun clearcase-submit-bug-report ()
  "Submit via mail a bug report on ClearCase Mode"
  (interactive)
  (and (y-or-n-p "Do you really want to submit a report on ClearCase Mode ? ")
       (reporter-submit-bug-report
        clearcase-xemacs-package-maintainer-address
        (concat "clearcase.el " clearcase-version)
        '(
          system-type
          system-configuration
          emacs-version
          clearcase-clearcase-version-installed
          clearcase-cleartool-path
          clearcase-lt
          clearcase-v3
          clearcase-v4
          clearcase-v5
          clearcase-servers-online
          clearcase-disable-tq
          clearcase-on-cygwin32
          clearcase-setview-root
          clearcase-suppress-vc-within-mvfs
          shell-file-name
          w32-quote-process-args
          ))))

;;}}}

;;{{{ Macros

(defmacro clearcase-when-debugging (&rest forms)
  (list 'if 'clearcase-debug (cons 'progn forms)))

(defmacro clearcase-with-tempfile (filename-var &rest forms)
  `(let ((,filename-var (clearcase-utl-tempfile-name)))
     (unwind-protect
         ,@forms

       ;; Cleanup.
       ;;
       (if (file-exists-p ,filename-var)
           (delete-file ,filename-var)))))

;;}}}

;;{{{ Portability

(defvar clearcase-xemacs-p (string-match "XEmacs" emacs-version))

(defvar clearcase-on-mswindows (memq system-type '(windows-nt ms-windows cygwin32)))

(defvar clearcase-on-cygwin32 (eq system-type 'cygwin32))

(defun clearcase-view-mode-quit (buf)
  "Exit from View mode, restoring the previous window configuration."
  (progn
    (cond ((frame-property (selected-frame) 'clearcase-view-window-config)
           (set-window-configuration
            (frame-property (selected-frame) 'clearcase-view-window-config))
           (set-frame-property  (selected-frame) 'clearcase-view-window-config nil))
          ((not (one-window-p))
           (delete-window)))
    (kill-buffer buf)))

(defun clearcase-view-mode (arg &optional camefrom)
  (if clearcase-xemacs-p
      (let* ((winconfig (current-window-configuration))
             (was-one-window (one-window-p))
             (buffer-name (buffer-name (current-buffer)))
             (clearcase-view-not-visible
              (not (and (windows-of-buffer buffer-name) ;shortcut
                        (memq (selected-frame)
                              (mapcar 'window-frame
                                      (windows-of-buffer buffer-name)))))))
        (when clearcase-view-not-visible
          (set-frame-property (selected-frame)
                              'clearcase-view-window-config winconfig))
        (view-mode camefrom 'clearcase-view-mode-quit)
        (setq buffer-read-only nil))
    (view-mode arg)))

(defun clearcase-port-view-buffer-other-window (buffer)
  (if clearcase-xemacs-p
      (switch-to-buffer-other-window buffer)
    (view-buffer-other-window buffer nil 'kill-buffer)))

(defun clearcase-dired-sort-by-date ()
  (if (fboundp 'dired-sort-by-date)
      (dired-sort-by-date)))

;; Copied from emacs-20
;;
(if (not (fboundp 'subst-char-in-string))
    (defun subst-char-in-string (fromchar tochar string &optional inplace)
      "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
Unless optional argument INPLACE is non-nil, return a new string."
      (let ((i (length string))
            (newstr (if inplace string (copy-sequence string))))
        (while (> i 0)
          (setq i (1- i))
          (if (eq (aref newstr i) fromchar)
              (aset newstr i tochar)))
        newstr)))

;;}}}

;;{{{ Require calls

;; nyi: we also use these at the moment:
;;     -view
;;     -ediff
;;     -view
;;     -dired-sort

(require 'cl)
(require 'comint)
(require 'dired)
(require 'easymenu)
(require 'reporter)
(require 'ring)
(or clearcase-xemacs-p
    (require 'timer))

;; NT Emacs - doesn't use tq.
;;
(if (not clearcase-on-mswindows)
    (require 'tq))

;;}}}

;;{{{ Debugging facilities

;; Setting this to true will enable some debug code.
;;
(defvar clearcase-debug nil)

(defun clearcase-trace (string)
  (clearcase-when-debugging
   (let ((trace-buf (get-buffer "*clearcase-trace*")))
     (if trace-buf
         (save-excursion
           (set-buffer trace-buf)
           (goto-char (point-max))
           (insert string "\n"))))))

(defun clearcase-enable-tracing ()
  (interactive)
  (setq clearcase-debug t)
  (get-buffer-create "*clearcase-trace*"))

(defun clearcase-disable-tracing ()
  (interactive)
  (setq clearcase-debug nil))

(defun clearcase-dump ()
  (interactive)
  (let ((buf (get-buffer-create "*clearcase-dump*"))
        (camefrom (current-buffer)))
    (save-excursion
      (set-buffer buf)
      (clearcase-view-mode 0 camefrom)
      (erase-buffer))
    (clearcase-fprop-dump buf)
    (clearcase-vprop-dump buf)
    (clearcase-port-view-buffer-other-window buf)
    (goto-char 0)
    (set-buffer-modified-p nil)         ; XEmacs - fsf uses `not-modified'
    (shrink-window-if-larger-than-buffer)))

(defun clearcase-flush-caches ()
  (interactive)
  (clearcase-fprop-clear-all-properties)
  (clearcase-vprop-clear-all-properties))

;;}}}

;;{{{ Customizable variables

(eval-and-compile
  (condition-case nil
      (require 'custom)
    (error nil))
  (if (and (featurep 'custom)
           (fboundp 'custom-declare-variable))
      nil;; We've got what we needed
    ;; We have the old custom-library, hack around it!
    (defmacro defgroup (&rest args)
      nil)
    (defmacro defcustom (var value doc &rest args)
      (` (defvar (, var) (, value) (, doc))))
    (defmacro defface (face value doc &rest stuff)
      `(make-face ,face))
    (defmacro custom-declare-variable (symbol value doc &rest args)
      (list 'defvar (eval symbol) value doc))))

(defgroup clearcase () "ClearCase Options" :group 'tools :prefix "clearcase")

(defcustom clearcase-make-backup-files nil
  "*If non-nil, backups of ClearCase files are made as with other files.
If nil (the default), files under ClearCase control don't get backups."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-complete-viewtags t
  "*If non-nil, completion on viewtags is enabled. For sites with thousands of view
this should be set to nil."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-minimise-menus nil
  "*If non-nil, menus will hide rather than grey-out inapplicable choices."
  :group 'clearcase
  :type 'boolean)

;; nyi: Currently unused:
;;
(defcustom clearcase-display-status t
  "*If non-nil, display version string and reservation status in modeline.
Otherwise, not displayed."
  :group 'clearcase
  :type 'boolean)

;; nyi: Currently unused:
;;
(defcustom clearcase-display-branch t
  "*If non-nil, full branch name of ClearCase working file displayed in modeline.
Otherwise, just the version number or label is displayed."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-auto-dired-mode t
  "*If non-nil, automatically enter `clearcase-dired-mode' in dired-mode buffers where
version control is set-up."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-dired-highlight t
  "If non-nil, highlight reserved files in clearcase-dired buffers."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-checkout-dir-on-mkelem 'ask
  "*If t, automatically checkout the directory (if needed) when creating an element.
If nil, don't checkout the directory and cancel the registration.
If `ask', prompt before checking out the directory.

This only applies to version control systems with versioned directories (namely
ClearCase."
  :group 'clearcase
  :type '(radio (const :tag "Never checkout dir on mkelem" nil)
                (const :tag "Automatically checkout dir on mkelem" t)
                (const :tag "Prompt to checkout dir on mkelem" ask)))

(defcustom clearcase-diff-on-checkin nil
  "Display diff on checkin to help you compose the checkin comment."
  :group 'clearcase
  :type 'boolean)

;; General customization

(defcustom clearcase-suppress-confirm nil
  "If non-nil, treat user as expert; suppress yes-no prompts on some things."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-initial-mkelem-comment nil
  "Prompt for initial comment when an element is created."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-command-messages nil
  "Display run messages from back-end commands."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-checkin-switches nil
  "Extra switches passed to the checkin program by \\[clearcase-checkin]."
  :group 'clearcase
  :type '(radio (const :tag "No extra switches" nil)
                (string :tag "Switches")))

(defcustom clearcase-checkin-on-mkelem nil
  "If t, file will be checked-in when first created as an element."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-suppress-checkout-comments nil
  "Suppress prompts for checkout comments for those version control
systems which use them."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-checkout-switches nil
  "Extra switches passed to the checkout program by \\[clearcase-commented-checkout]."
  :group 'clearcase
  :type '(radio (const :tag "No extra switches" nil)
                (string :tag "Switches")))

(defcustom clearcase-directory-exclusion-list '("lost+found")
  "Directory names ignored by functions that recursively walk file trees."
  :group 'clearcase
  :type '(repeat (string :tag "Subdirectory")))

(defcustom clearcase-use-normal-diff nil
  "If non-nil, use normal diff instead of cleardiff."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-normal-diff-program "diff"
  "*Program to use for generating the differential of the two files
when `clearcase-use-normal-diff' is t."
  :group 'clearcase
  :type 'string)

(defcustom clearcase-normal-diff-switches "-u"
  "*Switches (combined into single string) passed to `clearcase-normal-diff-program'
when `clearcase-use-normal-diff' is t.  Usage of the -u switch is
recommended to produce unified diffs, when your
`clearcase-normal-diff-program' supports it."
  :group 'clearcase
  :type 'string)

(defcustom clearcase-vxpath-glue "@@"
  "The string used to construct version-extended pathnames."
  :group 'clearcase
  :type 'string)

(defcustom clearcase-viewroot (if clearcase-on-mswindows
                                  "//view"
                                "/view")
  "The ClearCase viewroot directory."
  :group 'clearcase
  :type 'file)

(defcustom clearcase-viewroot-drive "m:"
  "The ClearCase viewroot drive letter for Windows."
  :group 'clearcase
  :type 'string)

(defcustom clearcase-suppress-vc-within-mvfs t
  "Suppresses VC activity within the MVFS."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-hide-rebase-activities t
  "Hide rebase activities from activity selection list."
  :group 'clearcase
  :type 'boolean)

(defcustom clearcase-rebase-id-regexp "^rebase\\."
  "The regexp used to detect rebase actvities."
  :group 'clearcase
  :type 'string)

;;}}}

;;{{{ Global variables

;; Initialize clearcase-pname-sep-regexp according to
;; directory-sep-char.
(defvar clearcase-pname-sep-regexp
  (format "[%s/]"
          (char-to-string directory-sep-char)))

(defvar clearcase-non-pname-sep-regexp
  (format "[^%s/]"
          (char-to-string directory-sep-char)))

;; Matches any viewtag (without the trailing "/").
;;
(defvar clearcase-viewtag-regexp
  (concat "^"
          clearcase-viewroot
          clearcase-pname-sep-regexp
          "\\("
          clearcase-non-pname-sep-regexp "*"
          "\\)"
          "$"
          ))

;; Matches ANY viewroot-relative path
;;
(defvar clearcase-vrpath-regexp
  (concat "^"
          clearcase-viewroot
          clearcase-pname-sep-regexp
          "\\("
          clearcase-non-pname-sep-regexp "*"
          "\\)"
          ))

;;}}}

;;{{{ Minor Mode: ClearCase

;; For ClearCase Minor Mode
;;
(defvar clearcase-mode nil)
(set-default 'clearcase-mode nil)
(make-variable-buffer-local 'clearcase-mode)
(put 'clearcase-mode 'permanent-local t)

;; Tell Emacs about this new kind of minor mode
;;
(if (not (assoc 'clearcase-mode minor-mode-alist))
    (setq minor-mode-alist (cons '(clearcase-mode clearcase-mode)
                                 minor-mode-alist)))

;; For now we override the bindings for VC Minor Mode with ClearCase Minor Mode
;; bindings.
;;
(defvar clearcase-mode-map (make-sparse-keymap))
(defvar clearcase-prefix-map (make-sparse-keymap))
(define-key clearcase-mode-map "\C-xv" clearcase-prefix-map)
(define-key clearcase-mode-map "\C-x\C-q" 'clearcase-toggle-read-only)

(define-key clearcase-prefix-map "b" 'clearcase-browse-vtree-current-buffer)
(define-key clearcase-prefix-map "c" 'clearcase-uncheckout-current-buffer)
(define-key clearcase-prefix-map "e" 'clearcase-edcs-edit)
(define-key clearcase-prefix-map "i" 'clearcase-mkelem-current-buffer)
(define-key clearcase-prefix-map "l" 'clearcase-list-history-current-buffer)
(define-key clearcase-prefix-map "m" 'clearcase-mkbrtype)
(define-key clearcase-prefix-map "u" 'clearcase-uncheckout-current-buffer)
(define-key clearcase-prefix-map "v" 'clearcase-next-action-current-buffer)
(define-key clearcase-prefix-map "w" 'clearcase-what-rule-current-buffer)
(define-key clearcase-prefix-map "=" 'clearcase-diff-pred-current-buffer)
(define-key clearcase-prefix-map "?" 'clearcase-describe-current-buffer)

;; To avoid confusion, we prevent VC Mode from being active at all by
;; undefining its keybindings for which ClearCase Mode doesn't yet have an
;; analogue.
;;
(define-key clearcase-prefix-map "a" 'undefined);; vc-update-change-log
(define-key clearcase-prefix-map "d" 'undefined);; vc-directory
(define-key clearcase-prefix-map "g" 'undefined);; vc-annotate
(define-key clearcase-prefix-map "h" 'undefined);; vc-insert-headers
(define-key clearcase-prefix-map "m" 'undefined);; vc-merge
(define-key clearcase-prefix-map "r" 'undefined);; vc-retrieve-snapshot
(define-key clearcase-prefix-map "s" 'undefined);; vc-create-snapshot
(define-key clearcase-prefix-map "t" 'undefined);; vc-dired-toggle-terse-mode
(define-key clearcase-prefix-map "~" 'undefined);; vc-version-other-window

;; Associate the map and the minor mode
;;
(or (not (boundp 'minor-mode-map-alist))
    (assq 'clearcase-mode (symbol-value 'minor-mode-map-alist))
    (setq minor-mode-map-alist
          (cons (cons 'clearcase-mode clearcase-mode-map)
                minor-mode-map-alist)))

(defun clearcase-mode (&optional arg)
  "ClearCase Minor Mode"

  (interactive "P")

  ;; Behave like a proper minor-mode.
  ;;
  (setq clearcase-mode
        (if (interactive-p)
            (if (null arg)
                (not clearcase-mode)

              ;; Check if the numeric arg is positive.
              ;;
              (> (prefix-numeric-value arg) 0))

          ;; else
          ;; Use the car if it's a list.
          ;;
          (if (consp arg)
              (setq arg (car arg)))
          (if (symbolp arg)
              (if (null arg)
                  (not clearcase-mode);; toggle mode switch
                (not (eq '- arg)));; True if symbol is not '-

            ;; else
            ;; assume it's a number and check that.
            ;;
            (> arg 0))))

  (if clearcase-mode
      (easy-menu-add clearcase-menu 'clearcase-mode-map))
  )

;;}}}

;;{{{ Minor Mode: ClearCase Dired

;;{{{ Reformatting the Dired buffer

;; Create a face for highlighting checked out files in clearcase-dired.
;;
(if (not (memq 'clearcase-dired-checkedout-face (face-list)))
    (progn
      (make-face 'clearcase-dired-checkedout-face)
      (set-face-foreground 'clearcase-dired-checkedout-face "red")))

(defun clearcase-dired-reformat-buffer ()
  "Reformats the current dired buffer."
  (let* ((checkout-list nil)
         (directory default-directory)
         subdir
         subdir-native
         filename
         fullpath-native)

    ;; Iterate over each line in the buffer.
    ;;
    ;; Important notes:
    ;;   1. In general, a Dired buffer can contain listings for several
    ;;        directories. We pass though from top to bottom and adjust
    ;;        subdir as we go.
    ;;   2. Since this is called from dired-after-reading-hook, it can get
    ;;      called on a single-line buffer. In this case there is no subdir,
    ;;      and no checkout-list. We need to call clearcase-fprop-checked-out
    ;;      to test for a checkout.
    ;;
    (save-excursion
      (goto-char (point-min))
      (while (not (eobp))
        (cond
           
         ;; Case 1: Look for directory markers
         ;;
         ((setq subdir (dired-get-subdir))

          (setq subdir-native (clearcase-path-canonicalise-slashes
                               (clearcase-path-native subdir)))

          ;; We're at a subdirectory line in the dired buffer.
          ;; Go and list all checkouts in this subdirectory.
          ;;
          (setq checkout-list (clearcase-dired-list-checkouts subdir))
            
          ;; If no checkouts are found, we don't need to check each file, and
          ;; it's very slow.  The checkout-list should contain something so it
          ;; doesn't attempt to do this.
          ;;
          (if (null checkout-list)
              (setq checkout-list '(nil)))
          (message "Reformatting %s..." subdir))
         
         ;; Case 2: Look for files (the safest way to get the filename).
         ;;
         ((setq filename (dired-get-filename 'no-dir t))

          ;; Expand it to get rid of . and .. entries.
          ;;
          (setq fullpath-native (concat subdir-native filename))

          ;; Only modify directory listings of the correct format.
          ;; We replace the GID field with a checkout indicator.
          ;;
          (if (looking-at
               ;;     (1)     (2) (3)    (4)
               ;; -rw-rw-rw-   1 esler    5              28 Feb  2 16:02 foo.el
               "..\\([drwxlts-]+ \\) *\\([0-9]+\\) \\([^ ]+\\) *\\([^ ]+ *\\) +[0-9]+\\( [^ 0-9]+ [0-9 ][0-9] .*\\)")
              
              (let* ((replacement-begin (match-beginning 4))
                     (replacement-end (match-end 4))
                     
                     (replacement-length (- replacement-end replacement-begin))
                     (replacement-text (format "CHECKOUT"))
                     (is-checkout (if checkout-list
                                      (member fullpath-native checkout-list)
                                    (clearcase-fprop-checked-out (expand-file-name filename)))))

                ;; Highlight the line if the file is checked-out.
                ;;
                (if is-checkout
                    ;; Replace the GID field with CHECKOUT.
                    ;;
                    (let ((buffer-read-only nil))
                      
                      ;; Pad with replacement text with trailing spaces if necessary.
                      ;;
                      (if (>= replacement-length (length replacement-text))
                          (setq replacement-text
                                (concat replacement-text
                                        (make-string (- replacement-length (length replacement-text))
                                                     32))))
                      (goto-char replacement-begin)
                      (delete-char replacement-length)
                      (insert (substring replacement-text 0 replacement-length))

                      ;; Highlight the checked out files.
                      ;;
                      (if (fboundp 'put-text-property)
                          (put-text-property replacement-begin replacement-end
                                             'face 'clearcase-dired-checkedout-face))))
                ))))
        (forward-line 1)))
  (message "Reformatting...Done")))

(defun clearcase-dired-list-checkouts (directory)
  "Returns a list of files checked-out to the current view in DIRECTORY."

  ;; Don't bother looking for checkouts in a history-mode listing
  ;; nor in view-private directories.
  ;;
  (if (and (not (clearcase-vxpath-p directory))
           (not (eq 'view-private-object (clearcase-fprop-mtype directory))))

      (let* ((ignore (message "Listing ClearCase checkouts..."))
             
             (true-directory (file-truename directory))

             ;; Form the command:
             ;;
             (cmd (list
                   "lsco" "-cview" "-fmt"
                   (if clearcase-on-mswindows
                       (if clearcase-xemacs-p
                           "%n\n"
                         "%n\\n")
                     "'%n\\n'")
                   
                   ;; Give the directory as an argument so all names will be
                   ;; fullpaths. For some reason ClearCase adds an extra slash
                   ;; if you leave the trailing slash on the directory, so we
                   ;; need to remove it.
                   ;;
                   (clearcase-path-native (directory-file-name true-directory))))

             ;; Capture the output:
             ;;
             (string (clearcase-path-canonicalise-slashes
                      (apply 'clearcase-ct-cleartool-cmd cmd)))

             ;; Split the output at the newlines:
             ;;
             (checkout-list (clearcase-utl-split-string-at-char string ?\n)))
        
        ;; Add entries for "." and ".." if they're checked-out.
        ;;
        (let* ((entry ".")
               (path (expand-file-name (concat true-directory entry))))
          (if (clearcase-fprop-checked-out path)
              (setq checkout-list (cons path checkout-list))))
        (let* ((entry "..")
               (path (expand-file-name (concat true-directory entry))))
          (if (clearcase-fprop-checked-out path)
              (setq checkout-list (cons path checkout-list))))
        
        (message "Listing ClearCase checkouts...done")
        
        ;; Return the result.
        ;;
        checkout-list)))

;; I had believed that this implementation below OUGHT to be faster, having
;; read the code in "ct+lsco". It seemed that "lsco -cview" hit the VOB and
;; listed all checkouts on all elements in the directory, and then filtered by
;; view.  I thought it would probably be quicker to run "ct ls -vob_only" and
;; keep the lines that have "[eclipsed by checkout]".  However this code
;; actually seemed to run slower.  Leave the code here for now so I can test
;; further.
;;
(defun clearcase-dired-list-checkouts-experimental (directory)
  "Returns a list of files checked-out to the current view in DIRECTORY."

  ;; Don't bother looking for checkouts in a history-mode listing
  ;; nor in view-private directories.
  ;;
  (if (and (not (clearcase-vxpath-p directory))
           (not (eq 'view-private-object (clearcase-fprop-mtype directory))))

      (let* ((ignore (message "Listing ClearCase checkouts..."))
             
             (true-directory (file-truename directory))

             ;; Move temporarily to the directory:
             ;;
             (default-directory true-directory)
             
             ;; Form the command:
             ;;
             (cmd (list "ls" "-vob_only"))

             ;; Capture the output:
             ;;
             (string (clearcase-path-canonicalise-slashes
                      (apply 'clearcase-ct-cleartool-cmd cmd)))

             ;; Split the output at the newlines:
             ;;
             (line-list (clearcase-utl-split-string-at-char string ?\n))

             (checkout-list nil))

        ;; Look for lines of the form:
        ;; FILENAME@@ [eclipsed by checkout]
        ;;
        (mapcar (function
                 (lambda (line)
                   (if (string-match "^\\([^ @]+\\)@@ +\\[eclipsed by checkout\\].*" line)
                       (setq checkout-list (cons (concat
                                                  ;; Add back directory name to get
                                                  ;; full pathname.
                                                  ;;
                                                  default-directory
                                                  (substring line
                                                             (match-beginning 1)
                                                             (match-end 1)))
                                                 checkout-list)))))
                line-list)

        ;; Add entries for "." and ".." if they're checked-out.
        ;;
        (let* ((entry ".")
               (path (expand-file-name (concat true-directory entry))))
          (if (clearcase-fprop-checked-out path)
              (setq checkout-list (cons path checkout-list))))
        (let* ((entry "..")
               (path (expand-file-name (concat true-directory entry))))
          (if (clearcase-fprop-checked-out path)
              (setq checkout-list (cons path checkout-list))))
        
        (message "Listing ClearCase checkouts...done")
        
        ;; Return the result.
        ;;
        checkout-list)))

(defun clearcase-dired-list-hijacks (directory)
  "Returns a list of files hijacked to the current view in DIRECTORY."

  ;; Don't bother looking for hijacks in;
  ;;   - a history-mode listing
  ;;   - a in view-private directory
  ;;   - a dynamic view
  ;;
  (let* ((true-directory (file-truename directory))
         (viewtag (clearcase-fprop-viewtag true-directory)))
    
    (if (and viewtag
             (not (clearcase-vxpath-p directory))
             (not (eq 'view-private-object (clearcase-fprop-mtype directory)))
             (clearcase-file-would-be-in-snapshot-p true-directory))
        
        (let* ((ignore (message "Listing ClearCase hijacks..."))
               
               (true-directory (file-truename directory))
               
               ;; Form the command:
               ;;
               (cmd (list
                     "ls"

                     ;; Give the directory as an argument so all names will be
                     ;; fullpaths. For some reason ClearCase adds an extra slash
                     ;; if you leave the trailing slash on the directory, so we
                     ;; need to remove it.
                     ;;
                     (clearcase-path-native (directory-file-name true-directory))))
               
               ;; Capture the output:
               ;;
               (string (clearcase-path-canonicalise-slashes
                        (apply 'clearcase-ct-cleartool-cmd cmd)))

             ;; Split the output at the newlines:
             ;;
             (line-list (clearcase-utl-split-string-at-char string ?\n))

             (hijack-list nil))
          
          (mapcar (function
                   (lambda (line)
                     (if (string-match "^\\([^ @]+\\)@@[^ ]+ \\[hijacked\\].*" line)
                         (setq hijack-list (cons (substring line
                                                            (match-beginning 1)
                                                            (match-end 1))
                                                 hijack-list)))))
                  line-list)
             
          (message "Listing ClearCase hijacks...done")
          
          ;; Return the result.
          ;;
          hijack-list))))

;;}}}

;; For ClearCase Dired Minor Mode
;;
(defvar clearcase-dired-mode nil)
(set-default 'clearcase-dired-mode nil)
(make-variable-buffer-local 'clearcase-dired-mode)

;; Tell Emacs about this new kind of minor mode
;;
(if (not (assoc 'clearcase-dired-mode minor-mode-alist))
    (setq minor-mode-alist (cons '(clearcase-dired-mode clearcase-dired-mode)
                                 minor-mode-alist)))

;; For now we override the bindings for VC Minor Mode with ClearCase Dired
;; Minor Mode bindings.
;;
(defvar clearcase-dired-mode-map (make-sparse-keymap))
(defvar clearcase-dired-prefix-map (make-sparse-keymap))
(define-key clearcase-dired-mode-map "\C-xv" clearcase-dired-prefix-map)

(define-key clearcase-dired-prefix-map "b" 'clearcase-browse-vtree-dired-file)
(define-key clearcase-dired-prefix-map "c" 'clearcase-uncheckout-dired-files)
(define-key clearcase-dired-prefix-map "e" 'clearcase-edcs-edit)
(define-key clearcase-dired-prefix-map "i" 'clearcase-mkelem-dired-files)
(define-key clearcase-dired-prefix-map "l" 'clearcase-list-history-dired-file)
(define-key clearcase-dired-prefix-map "m" 'clearcase-mkbrtype)
(define-key clearcase-dired-prefix-map "u" 'clearcase-uncheckout-dired-files)
(define-key clearcase-dired-prefix-map "v" 'clearcase-next-action-dired-files)
(define-key clearcase-dired-prefix-map "w" 'clearcase-what-rule-dired-file)
(define-key clearcase-dired-prefix-map "=" 'clearcase-diff-pred-dired-file)
(define-key clearcase-dired-prefix-map "~" 'clearcase-version-other-window)
(define-key clearcase-dired-prefix-map "?" 'clearcase-describe-dired-file)

;; To avoid confusion, we prevent VC Mode from being active at all by
;; undefining its keybindings for which ClearCase Mode doesn't yet have an
;; analogue.
;;
(define-key clearcase-dired-prefix-map "a" 'undefined);; vc-update-change-log
(define-key clearcase-dired-prefix-map "d" 'undefined);; vc-directory
(define-key clearcase-dired-prefix-map "g" 'undefined);; vc-annotate
(define-key clearcase-dired-prefix-map "h" 'undefined);; vc-insert-headers
(define-key clearcase-dired-prefix-map "m" 'undefined);; vc-merge
(define-key clearcase-dired-prefix-map "r" 'undefined);; vc-retrieve-snapshot
(define-key clearcase-dired-prefix-map "s" 'undefined);; vc-create-snapshot
(define-key clearcase-dired-prefix-map "t" 'undefined);; vc-dired-toggle-terse-mode

;; Associate the map and the minor mode
;;
(or (not (boundp 'minor-mode-map-alist))
    (assq 'clearcase-dired-mode (symbol-value 'minor-mode-map-alist))
    (setq minor-mode-map-alist
          (cons (cons 'clearcase-dired-mode clearcase-dired-mode-map)
                minor-mode-map-alist)))

(defun clearcase-dired-mode (&optional arg)
  "The augmented Dired minor mode used in ClearCase directory buffers.
All Dired commands operate normally.  Users with checked-out files
are listed in place of the file's owner and group. Keystrokes bound to
ClearCase Mode commands will execute as though they had been called
on a buffer attached to the file named in the current Dired buffer line."

  (interactive "P")

  ;; Behave like a proper minor-mode.
  ;;
  (setq clearcase-dired-mode
        (if (interactive-p)
            (if (null arg)
                (not clearcase-dired-mode)

              ;; Check if the numeric arg is positive.
              ;;
              (> (prefix-numeric-value arg) 0))

          ;; else
          ;; Use the car if it's a list.
          ;;
          (if (consp arg)
              (setq arg (car arg)))

          (if (symbolp arg)
              (if (null arg)
                  (not clearcase-dired-mode);; toggle mode switch
                (not (eq '- arg)));; True if symbol is not '-

            ;; else
            ;; assume it's a number and check that.
            ;;
            (> arg 0))))

  (if (not (eq major-mode 'dired-mode))
      (setq clearcase-dired-mode nil))

  (if (and clearcase-dired-mode clearcase-dired-highlight)
      (clearcase-dired-reformat-buffer))

  (if clearcase-dired-mode
      (easy-menu-add clearcase-dired-menu 'clearcase-dired-mode-map))
  )

;;}}}

;;{{{ Major Mode: for editing comments.

;; The major mode function.
;;
(defun clearcase-comment-mode ()
  "Major mode for editing comments for ClearCase.

These bindings are added to the global keymap when you enter this mode:

\\[clearcase-next-action-current-buffer]  perform next logical version-control operation on current file
\\[clearcase-mkelem-current-buffer]       mkelem the current file
\\[clearcase-toggle-read-only]            like next-action, but won't create elements
\\[clearcase-list-history-current-buffer] display change history of current file
\\[clearcase-uncheckout-current-buffer]   cancel checkout in buffer
\\[clearcase-diff-pred-current-buffer]    show diffs between file versions
\\[clearcase-version-other-window]        visit old version in another window

While you are entering a comment for a version, the following
additional bindings will be in effect.

\\[clearcase-comment-finish]           proceed with check in, ending comment

Whenever you do a checkin, your comment is added to a ring of
saved comments.  These can be recalled as follows:

\\[clearcase-comment-next]             replace region with next message in comment ring
\\[clearcase-comment-previous]         replace region with previous message in comment ring
\\[clearcase-comment-search-reverse]   search backward for regexp in the comment ring
\\[clearcase-comment-search-forward]   search backward for regexp in the comment ring

Entry to the clearcase-comment-mode calls the value of text-mode-hook, then
the value of clearcase-comment-mode-hook.

Global user options:
 clearcase-initial-mkelem-comment      If non-nil, require user to enter a change
                                   comment upon first checkin of the file.

 clearcase-suppress-confirm     Suppresses some confirmation prompts,
                            notably for reversions.

 clearcase-command-messages     If non-nil, display run messages from the
                            actual version-control utilities (this is
                            intended primarily for people hacking clearcase.el
                            itself).
"
  (interactive)

  ;; Major modes are supposed to just (kill-all-local-variables)
  ;; but we rely on clearcase-parent-buffer already having been set
  ;;
  ;;(let ((parent clearcase-parent-buffer))
  ;;  (kill-all-local-variables)
  ;;  (set (make-local-variable 'clearcase-parent-buffer) parent))

  (setq major-mode 'clearcase-comment-mode)
  (setq mode-name "ClearCase/Comment")

  (set-syntax-table text-mode-syntax-table)
  (use-local-map clearcase-comment-mode-map)
  (setq local-abbrev-table text-mode-abbrev-table)

  (make-local-variable 'clearcase-comment-operands)
  (make-local-variable 'clearcase-comment-ring-index)

  (set-buffer-modified-p nil)
  (setq buffer-file-name nil)
  (run-hooks 'text-mode-hook 'clearcase-comment-mode-hook))

;; The keymap.
;;
(defvar clearcase-comment-mode-map nil)
(if clearcase-comment-mode-map
    nil
  (setq clearcase-comment-mode-map (make-sparse-keymap))
  (define-key clearcase-comment-mode-map "\M-n" 'clearcase-comment-next)
  (define-key clearcase-comment-mode-map "\M-p" 'clearcase-comment-previous)
  (define-key clearcase-comment-mode-map "\M-r" 'clearcase-comment-search-reverse)
  (define-key clearcase-comment-mode-map "\M-s" 'clearcase-comment-search-forward)
  (define-key clearcase-comment-mode-map "\C-c\C-c" 'clearcase-comment-finish)
  (define-key clearcase-comment-mode-map "\C-x\C-s" 'clearcase-comment-save)
  (define-key clearcase-comment-mode-map "\C-x\C-q" 'clearcase-comment-num-num-error))

;; Constants.
;;
(defconst clearcase-comment-maximum-ring-size 32
  "Maximum number of saved comments in the comment ring.")

;; Variables.
;;
(defvar clearcase-comment-entry-mode nil)
(defvar clearcase-comment-operation nil)
(defvar clearcase-comment-operands)
(defvar clearcase-comment-ring nil)
(defvar clearcase-comment-ring-index nil)
(defvar clearcase-comment-last-match nil)
(defvar clearcase-comment-window-config nil)

;; In several contexts, this is a local variable that points to the buffer for
;; which it was made (either a file, or a ClearCase dired buffer).
;;
(defvar clearcase-parent-buffer nil)
(defvar clearcase-parent-buffer-name nil)

;;{{{ Commands and functions

(defun clearcase-comment-start-entry (uniquifier
                                      prompt
                                      continuation
                                      operands
                                      &optional parent-buffer comment-seed)

  "Accept a comment by popping up a clearcase-comment-mode buffer
with a name derived from UNIQUIFIER, and emitting PROMPT in the minibuffer.
Set the continuation on close to CONTINUATION, which should be apply-ed to a list
formed by appending OPERANDS and the comment-string.

Optional 5th argument specifies a PARENT-BUFFER to return to when the operation
is complete.

Optional 6th argument specifies a COMMENT-SEED to insert in the comment buffer for
the user to edit."

  (let ((comment-buffer (get-buffer-create (format "*Comment-%s*" uniquifier)))
        (old-window-config (current-window-configuration))
        (parent (or parent-buffer
                    (current-buffer))))
    (pop-to-buffer comment-buffer)

    (set (make-local-variable 'clearcase-comment-window-config) old-window-config)
    (set (make-local-variable 'clearcase-parent-buffer) parent)

    (clearcase-comment-mode)
    (setq clearcase-comment-operation continuation)
    (setq clearcase-comment-operands operands)
    (if comment-seed
        (insert comment-seed))
    (message "%s  Type C-c C-c when done." prompt)))


(defun clearcase-comment-cleanup ()
  ;; Make sure it ends with newline
  ;;
  (goto-char (point-max))
  (if (not (bolp))
      (newline))

  ;; Remove useless whitespace.
  ;;
  (goto-char (point-min))
  (while (re-search-forward "[ \t]+$" nil t)
    (replace-match ""))

  ;; Remove trailing newlines, whitespace.
  ;;
  (goto-char (point-max))
  (skip-chars-backward " \n\t")
  (delete-region (point) (point-max)))

(defun clearcase-comment-finish ()
  "Complete the operation implied by the current comment."
  (interactive)

  ;;Clean and record the comment in the ring.
  ;;
  (let ((comment-buffer (current-buffer)))
    (clearcase-comment-cleanup)

    (if (null clearcase-comment-ring)
        (setq clearcase-comment-ring (make-ring clearcase-comment-maximum-ring-size)))
    (ring-insert clearcase-comment-ring (buffer-string))

    ;; Perform the operation on the operands.
    ;;
    (if clearcase-comment-operation
        (save-excursion
          (apply clearcase-comment-operation
                 (append clearcase-comment-operands (list (buffer-string)))))
      (error "No comment operation is pending"))

    ;; Return to "parent" buffer of this operation.
    ;; Remove comment window.
    ;;
    (let ((old-window-config clearcase-comment-window-config))
      (pop-to-buffer clearcase-parent-buffer)
      (delete-windows-on comment-buffer)
      (kill-buffer comment-buffer)
      (if old-window-config (set-window-configuration old-window-config)))))

(defun clearcase-comment-save-comment-for-buffer (comment buffer)
  (save-excursion
    (set-buffer buffer)
    (let ((file (buffer-file-name)))
      (if (clearcase-fprop-checked-out file)
          (progn
            (clearcase-ct-do-cleartool-command "chevent"
                                               file
                                               comment
                                               "-replace")
            (clearcase-fprop-set-comment file comment))
        (error "Can't change comment of checked-in version with this interface")))))

(defun clearcase-comment-save ()
  "Save the currently entered comment"
  (interactive)
  (let ((comment-string (buffer-string))
        (parent-buffer clearcase-parent-buffer))
    (if (not (buffer-modified-p))
        (message "(No changes need to be saved)")
      (progn
        (save-excursion
          (set-buffer parent-buffer)
          (clearcase-comment-save-comment-for-buffer comment-string parent-buffer))

        (set-buffer-modified-p nil)))))

(defun clearcase-comment-num-num-error ()
  (interactive)
  (message "Perhaps you wanted to type C-c C-c instead?"))

;; Code for the comment ring.
;;
(defun clearcase-comment-next (arg)
  "Cycle forwards through comment history."
  (interactive "*p")
  (clearcase-comment-previous (- arg)))

(defun clearcase-comment-previous (arg)
  "Cycle backwards through comment history."
  (interactive "*p")
  (let ((len (ring-length clearcase-comment-ring)))
    (cond ((or (not len) (<= len 0))
           (message "Empty comment ring")
           (ding))
          (t
           (erase-buffer)

           ;; Initialize the index on the first use of this command so that the
           ;; first M-p gets index 0, and the first M-n gets index -1.
           ;;
           (if (null clearcase-comment-ring-index)
               (setq clearcase-comment-ring-index
                     (if (> arg 0) -1
                       (if (< arg 0) 1 0))))
           (setq clearcase-comment-ring-index
                 (mod (+ clearcase-comment-ring-index arg) len))
           (message "%d" (1+ clearcase-comment-ring-index))
           (insert (ring-ref clearcase-comment-ring clearcase-comment-ring-index))))))

(defun clearcase-comment-search-forward (str)
  "Searches forwards through comment history for substring match."
  (interactive "sComment substring: ")
  (if (string= str "")
      (setq str clearcase-comment-last-match)
    (setq clearcase-comment-last-match str))
  (if (null clearcase-comment-ring-index)
      (setq clearcase-comment-ring-index 0))
  (let ((str (regexp-quote str))
        (n clearcase-comment-ring-index))
    (while (and (>= n 0) (not (string-match str (ring-ref clearcase-comment-ring n))))
      (setq n (- n 1)))
    (cond ((>= n 0)
           (clearcase-comment-next (- n clearcase-comment-ring-index)))
          (t (error "Not found")))))

(defun clearcase-comment-search-reverse (str)
  "Searches backwards through comment history for substring match."
  (interactive "sComment substring: ")
  (if (string= str "")
      (setq str clearcase-comment-last-match)
    (setq clearcase-comment-last-match str))
  (if (null clearcase-comment-ring-index)
      (setq clearcase-comment-ring-index -1))
  (let ((str (regexp-quote str))
        (len (ring-length clearcase-comment-ring))
        (n (1+ clearcase-comment-ring-index)))
    (while (and (< n len)
                (not (string-match str (ring-ref clearcase-comment-ring n))))
      (setq n (+ n 1)))
    (cond ((< n len)
           (clearcase-comment-previous (- n clearcase-comment-ring-index)))
          (t (error "Not found")))))

;;}}}

;;}}}

;;{{{ Major Mode: for editing config-specs.

;; The major mode function.
;;
(defun clearcase-edcs-mode ()
  (interactive)
  (set-syntax-table text-mode-syntax-table)
  (use-local-map clearcase-edcs-mode-map)
  (setq major-mode 'clearcase-edcs-mode)
  (setq mode-name "ClearCase/edcs")
  (make-variable-buffer-local 'clearcase-parent-buffer)
  (set-buffer-modified-p nil)
  (setq buffer-file-name nil)
  (run-hooks 'text-mode-hook 'clearcase-edcs-mode-hook))

;; The keymap.
;;
(defvar clearcase-edcs-mode-map nil)
(if clearcase-edcs-mode-map
    nil
  (setq clearcase-edcs-mode-map (make-sparse-keymap))
  (define-key clearcase-edcs-mode-map "\C-c\C-c" 'clearcase-edcs-finish)
  (define-key clearcase-edcs-mode-map "\C-x\C-s" 'clearcase-edcs-save))

;; Variables.
;;
(defvar clearcase-edcs-tag-name nil
  "Name of view tag which is currently being edited")

(defvar clearcase-edcs-tag-history ()
  "History of view tags used in clearcase-edcs-edit")

;;{{{ Commands

(defun clearcase-edcs-edit (tag-name)
  "Edit a ClearCase configuration specification"
  (interactive
   (let ((vxname (clearcase-fprop-viewtag default-directory)))
     (list (directory-file-name
            (completing-read "View Tag: "
                             (clearcase-viewtag-all-viewtags-obarray)
                             nil
                             ;;'fascist
                             nil
                             vxname
                             'clearcase-edcs-tag-history)))))
  (let ((start (current-buffer))
        (buffer-name (format "*ClearCase-Config-%s*" tag-name)))
    (kill-buffer (get-buffer-create buffer-name))
    (pop-to-buffer (get-buffer-create buffer-name))
    (auto-save-mode auto-save-default)
    (erase-buffer)
    (insert (clearcase-ct-cleartool-cmd "catcs" "-tag" tag-name))
    (goto-char (point-min))
    (re-search-forward "^[^#\n]" nil 'end)
    (beginning-of-line)
    (clearcase-edcs-mode)
    (setq clearcase-parent-buffer start)
    (make-local-variable 'clearcase-edcs-tag-name)
    (setq clearcase-edcs-tag-name tag-name)))

(defun clearcase-edcs-save ()
  (interactive)
  (if (not (buffer-modified-p))
      (message "Configuration not changed since last saved")

    (clearcase-with-tempfile
     cspec-text
     (progn
       (message "Setting configuration for %s..." clearcase-edcs-tag-name)
       (write-region (point-min) (point-max) cspec-text nil 'dont-mention-it)
       (let ((ret (clearcase-ct-cleartool-cmd "setcs"
                                              "-tag"
                                              clearcase-edcs-tag-name
                                              (clearcase-path-native cspec-text))))
         
         ;; nyi: we could be smarter and retain viewtag info and perhaps some
         ;;      other info. For now invalidate all cached file property info.
         ;;
         (clearcase-fprop-clear-all-properties)
         
         (set-buffer-modified-p nil)
         (message "Setting configuration for %s...done"
                  clearcase-edcs-tag-name))))))

(defun clearcase-edcs-finish ()
  (interactive)
  (let ((old-buffer (current-buffer)))
    (clearcase-edcs-save)
    (bury-buffer nil)
    (kill-buffer old-buffer)))

;;}}}

;;}}}

;;{{{ View browser

;; nyi: Just an idea now.
;;      Be able to present a selection of views at various times
;;        - show me current file in other view
;;        - top-level browse operation

;;  clearcase-viewtag-started-viewtags gives us the dynamic views that are mounted.

;;  How to find local snapshots ?

;; How to find drive-letter mount points for view on NT ?
;;  - parse "subst" output

;;}}}

;;{{{ Commands

;;{{{ Find checkouts

;; NYI: Enhance this:
;;  - group by:
;;    - activity name
;;    - checkout comment
;;  - permit unco/checkin
;;
(defun clearcase-find-checkouts-in-current-view ()
  "Find the checkouts in all vobs in the current view."
  (interactive)
  (let ((viewtag (clearcase-fprop-viewtag default-directory))
        (dir default-directory)
        (camefrom (current-buffer)))
    (if viewtag
        (let* ((ignore (message "Finding checkouts..."))
               (ret (clearcase-ct-blocking-call "lsco"
                                                "-cview"
                                                "-avobs"
                                                "-short")))
          (if (zerop (length ret))
              (message "No checkouts found")
            (message "Finding checkouts...done")
            (set-buffer (get-buffer-create "*clearcase*"))
            (clearcase-view-mode 0 camefrom)
            (erase-buffer)
            (insert ret)
            (clearcase-port-view-buffer-other-window "*clearcase*")
            (goto-char 0)
            (set-buffer-modified-p nil)   ; XEmacs - fsf uses `not-modified'
            (shrink-window-if-larger-than-buffer))))))

;;}}}

;;{{{ UCM operations

;;{{{ Make activity

(defun clearcase-ucm-mkact-current-dir (headline &optional comment)
  "Make an activity with HEADLINE and optional COMMENT,
in the stream associated with the view associated with the current directory.
The activity name is generated by ClearCase."
  (interactive "sHeadline: ")
  (let* ((viewtag (clearcase-fprop-viewtag default-directory))
         (stream  (clearcase-vprop-stream viewtag))
         (pvob    (clearcase-vprop-pvob viewtag)))
    (if (not (clearcase-vprop-ucm viewtag))
        (error "View %s is not a UCM view" viewtag))
    (if (null stream)
        (error "View %s has no stream" viewtag))
    (if (null stream)
        (error "View %s has no PVOB" viewtag))

    (if (null comment)
        ;; If no comment supplied, go and get one..
        ;;
        (progn
          (clearcase-comment-start-entry (format "new-activity-%d" (random))
                                         "Enter comment for new activity."
                                         'clearcase-ucm-mkact-current-dir
                                         (list headline)))
      ;; ...else do the operation.
      ;;
      (message "Making activity...")
      (clearcase-with-tempfile
       comment-file
       (let ((qualified-stream (format "%s@%s" stream pvob))
             (quoted-headline (concat "\""
                                      (clearcase-utl-escape-double-quotes headline)
                                      "\"")))
         (write-region comment nil comment-file nil 'noprint)
         (let ((ret (clearcase-ct-blocking-call "mkact" "-cfile" (clearcase-path-native comment-file)
                                                "-headline" headline
                                                "-in" qualified-stream "-force"))))))
      ;; Flush the activities for this view so they'll get refreshed when needed.
      ;;
      (clearcase-vprop-flush-activities viewtag)
      
      (message "Making activity...done"))))

;; Not currently used as we prefer system-generated activity names for now.
;;
(defun clearcase-ucm-mkact-named-current-dir (name headline &optional comment)
  "Make an activity with NAME and HEADLINE and optional COMMENT,
in the stream associated with the view associated with the current directory"
  (interactive "sActivity name: \nsHeadline: ")
  (let* ((viewtag (clearcase-fprop-viewtag default-directory))
         (stream  (clearcase-vprop-stream viewtag))
         (pvob    (clearcase-vprop-pvob viewtag)))
    (if (not (clearcase-vprop-ucm viewtag))
        (error "View %s is not a UCM view" viewtag))
    (if (null stream)
        (error "View %s has no stream" viewtag))
    (if (null stream)
        (error "View %s has no PVOB" viewtag))

    (if (null comment)
        ;; If no comment supplied, go and get one..
        ;;
        (progn
          (clearcase-comment-start-entry name
                                         "Enter comment for new activity."
                                         'clearcase-ucm-mkact-named-current-dir
                                         (list name headline)))
      ;; ...else do the operation.
      ;;
      (message "Making activity...")
      (clearcase-with-tempfile
       comment-file
       (let ((qualified-name (format "%s@%s" name pvob))
             (qualified-stream (format "%s@%s" stream pvob))
             (quoted-headline (concat "\""
                                      (clearcase-utl-escape-double-quotes headline)
                                      "\"")))
         (write-region comment nil comment-file nil 'noprint)
         (let ((ret (clearcase-ct-blocking-call "mkact" "-cfile" (clearcase-path-native comment-file)
                                                "-headline" quoted-headline
                                                "-in"
                                                qualified-stream
                                                (if (zerop (length name))
                                                    "-force"
                                                  qualified-name)))))))
      (message "Making activity...done"))))

;;}}}

;;{{{ Set activity

(defun clearcase-ucm-filter-out-rebases (activities)
  (if (not clearcase-hide-rebase-activities)
      activities
    (clearcase-utl-list-filter
     (function
      (lambda (activity)
        (let ((id (car activity)))
          (not (string-match clearcase-rebase-id-regexp id)))))
     activities)))
        
(defun clearcase-ucm-set-activity-current-dir ()
  (interactive)
  (let* ((viewtag (clearcase-fprop-viewtag default-directory)))
    (if (not (clearcase-vprop-ucm viewtag))
        (error "View %s is not a UCM view" viewtag))
    ;; Filter out the rebases here if the user doesn't want to see them.
    ;;
    (let ((activities (clearcase-ucm-filter-out-rebases (clearcase-vprop-activities viewtag))))
      (if (null activities)
          (error "View %s has no activities" viewtag))
      (clearcase-ucm-make-selection-window (concat "*clearcase-activity-select-%s*" viewtag)
                                           (mapconcat
                                            (function
                                             (lambda (activity)
                                               (let ((id (car activity))
                                                     (title (cdr activity)))
                                                 (format "%s\t%s" id title))))
                                            activities
                                            "\n")
                                           'clearcase-ucm-activity-selection-interpreter
                                           'clearcase-ucm-set-activity
                                           (list viewtag)))))

(defun clearcase-ucm-activity-selection-interpreter ()
  "Extract the activity name from the buffer at point"
  (if (looking-at "^\\(.*\\)\t")
      (let ((activity-name (buffer-substring (match-beginning 1)
                                             (match-end 1))))
        activity-name)
    (error "No activity on this line")))

(defun clearcase-ucm-set-activity-none-current-dir ()
  (interactive)
  (let* ((viewtag (clearcase-fprop-viewtag default-directory)))
    (if (not (clearcase-vprop-ucm viewtag))
        (error "View %s is not a UCM view" viewtag))
    (clearcase-ucm-set-activity viewtag nil)))

(defun clearcase-ucm-set-activity (viewtag activity-name)
  (if activity-name
      ;; Set an activity
      ;;
      (progn
        (message "Setting activity...")
        (let* ((qualified-activity-name (if (string-match "@" activity-name)
                                            activity-name
                                          (concat activity-name "@" (clearcase-vprop-pvob viewtag))))
               (ret (clearcase-ct-blocking-call "setactivity" "-nc" "-view"
                                                viewtag
                                                (if qualified-activity-name
                                                    qualified-activity-name
                                                  "-none"))))
        ;; Update cache
        ;;
        (clearcase-vprop-set-current-activity viewtag activity-name)
        (message "Setting activity...done")))
        
    ;; Set NO activity
    ;;
    (message "Unsetting activity...")
    (let ((ret (clearcase-ct-blocking-call "setactivity" "-nc" "-view"
                                           viewtag "-none")))
      ;; Update cache
      ;;
      (clearcase-vprop-set-current-activity viewtag nil)
      (message "Unsetting activity...done"))))

;;}}}

;;{{{ Show current activity

(defun clearcase-ucm-describe-current-activity ()
  (interactive)
  (let* ((viewtag (clearcase-fprop-viewtag default-directory))
         (camefrom (current-buffer)))
    (if (not viewtag)
        (error "Not in a view"))
    (if (not (clearcase-vprop-ucm viewtag))
        (error "View %s is not a UCM view" viewtag))
    (let ((pvob (clearcase-vprop-pvob viewtag))
          (current-activity (clearcase-vprop-current-activity viewtag)))
      (if (not current-activity)
          (message "No activity set")
        (let ((ret (clearcase-ct-blocking-call "desc"
                                               (concat "activity:"
                                                       current-activity
                                                       "@"
                                                       pvob))))
          ;; nyi:factor this sort of stuff out
          ;;
          (if (not (zerop (length ret)))
              (progn
                (set-buffer (get-buffer-create "*clearcase*"))
                (clearcase-view-mode 0 camefrom)
                (erase-buffer)
                (insert ret)
                (clearcase-port-view-buffer-other-window "*clearcase*")
                (goto-char 0)
                (set-buffer-modified-p nil)   ; XEmacs - fsf uses `not-modified'
                (shrink-window-if-larger-than-buffer))))))))

;;}}}

;;}}}

;;{{{ Next-action

(defun clearcase-next-action-current-buffer ()
  "Do the next logical operation on the current file.
Operations include mkelem, checkout, checkin, uncheckout"
  (interactive)
  (clearcase-next-action buffer-file-name))

(defun clearcase-next-action-dired-files ()
  "Do the next logical operation on the marked files.
Operations include mkelem, checkout, checkin, uncheckout.
If all the files are not in an equivalent state, an error is raised."

  (interactive)
  (clearcase-next-action-seq (dired-get-marked-files)))

(defun clearcase-next-action (file)
  (let ((action (clearcase-compute-next-action file)))
    (cond

     ((eq action 'mkelem)
      (clearcase-commented-mkelem file))

     ((eq action 'checkout)
      (clearcase-commented-checkout file))

     ((eq action 'uncheckout)
      (if (yes-or-no-p "Checked-out file appears unchanged. Cancel checkout ? ")
          (clearcase-uncheckout file)))

     ((eq action 'illegal-checkin)
      (error "This file is checked out by %s" (clearcase-fprop-user file)))

     ((eq action 'checkin)
      (clearcase-commented-checkin file))

     (t
      (error "Can't compute suitable next ClearCase action for file %s" file)))))

(defun clearcase-next-action-seq (files)
  "Do the next logical operation on the sequence of FILES."

  ;; Check they're all in the same state.
  ;;
  (let ((actions (mapcar (function clearcase-compute-next-action) files)))
    (if (not (clearcase-utl-elts-are-eq actions))
        (error "Marked files are not all in the same state"))
    (let ((action (car actions)))
      (cond

       ((eq action 'mkelem)
        (clearcase-commented-mkelem-seq files))

       ((eq action 'checkout)
        (clearcase-commented-checkout-seq files))

       ((eq action 'uncheckout)
        (if (yes-or-no-p "Checked-out files appears unchanged. Cancel checkouts ? ")
            (clearcase-uncheckout-seq files)))

       ((eq action 'illegal-checkin)
        (error "These files are checked out by someone else; will no checkin"))

       ((eq action 'checkin)
        (clearcase-commented-checkin-seq files))

       (t
        (error "Can't compute suitable next ClearCase action for marked files"))))))

(defun clearcase-compute-next-action (file)
  "Compute the next logical action on FILE."

  (cond
   ;; nyi: other cases to consider later:
   ;;
   ;;   - file is unreserved
   ;;   - file is not mastered

   ;; Case 1: it is not yet an element
   ;;         ==> mkelem
   ;;
   ((clearcase-file-ok-to-mkelem file)
    'mkelem)

   ;; Case 2: file is not checked out
   ;;         ==> checkout
   ;;
   ((clearcase-file-ok-to-checkout file)
    'checkout)

   ;; Case 3: file is checked-out but not modified in buffer or disk
   ;;         ==> offer to uncheckout
   ;;
   ((and (clearcase-file-ok-to-uncheckout file)
         (not (file-directory-p file))
         (not (buffer-modified-p))
         (not (clearcase-file-appears-modified-since-checkout-p file)))
    'uncheckout)

   ;; Case 4: file is checked-out but by somebody else using this view.
   ;;         ==> refuse to checkin
   ;;
   ((and (clearcase-fprop-checked-out file)
         (not (string= (user-login-name)
                       (clearcase-fprop-user file))))
    'illegal-checkin)

   ;; Case 5: user has checked-out the file
   ;;         ==> check it in
   ;;
   ((clearcase-file-ok-to-checkin file)
    'checkin)

   (t
    nil)))

;;}}}

;;{{{ Mkelem

(defun clearcase-mkelem-current-buffer ()
  "Make the current file into a ClearCase element."
  (interactive)

  ;; Watch out for new buffers of size 0: the corresponding file
  ;; does not exist yet, even though buffer-modified-p is nil.
  ;;
  (if (and (not (buffer-modified-p))
           (zerop (buffer-size))
           (not (file-exists-p buffer-file-name)))
      (set-buffer-modified-p t))

  (clearcase-commented-mkelem buffer-file-name))

(defun clearcase-mkelem-dired-files ()
  "Make the selected files into ClearCase elements."
  (interactive)
  (clearcase-commented-mkelem-seq (dired-get-marked-files)))

;;}}}

;;{{{ Checkin

(defun clearcase-checkin-current-buffer ()
  "Checkin the file in the current buffer."
  (interactive)

  ;; Watch out for new buffers of size 0: the corresponding file
  ;; does not exist yet, even though buffer-modified-p is nil.
  ;;
  (if (and (not (buffer-modified-p))
           (zerop (buffer-size))
           (not (file-exists-p buffer-file-name)))
      (set-buffer-modified-p t))

  (clearcase-commented-checkin buffer-file-name))

(defun clearcase-checkin-dired-files ()
  "Checkin the selected files."
  (interactive)
  (clearcase-commented-checkin-seq (dired-get-marked-files)))

(defun clearcase-dired-checkin-current-dir ()
  (interactive)
  (clearcase-commented-checkin (dired-current-directory)))

;;}}}

;;{{{ Checkout

(defun clearcase-checkout-current-buffer ()
  "Checkout the file in the current buffer."
  (interactive)
  (clearcase-commented-checkout buffer-file-name))

(defun clearcase-checkout-dired-files ()
  "Checkout the selected files."
  (interactive)
  (clearcase-commented-checkout-seq (dired-get-marked-files)))

(defun clearcase-dired-checkout-current-dir ()
  (interactive)
  (clearcase-commented-checkout (dired-current-directory)))

;;}}}

;;{{{ Uncheckout

(defun clearcase-uncheckout-current-buffer ()
  "Uncheckout the file in the current buffer."
  (interactive)
  (clearcase-uncheckout buffer-file-name))

(defun clearcase-uncheckout-dired-files ()
  "Uncheckout the selected files."
  (interactive)
  (clearcase-uncheckout-seq (dired-get-marked-files)))

(defun clearcase-dired-uncheckout-current-dir ()
  (interactive)
  (clearcase-uncheckout (dired-current-directory)))

;;}}}

;;{{{ Mkbrtype

(defun clearcase-mkbrtype (typename)
  (interactive "sBranch type name: ")
  (clearcase-commented-mkbrtype typename))

;;}}}

;;{{{ Describe

(defun clearcase-describe-current-buffer ()
  "Give a ClearCase description of the file in the current buffer."
  (interactive)
  (clearcase-describe buffer-file-name))

(defun clearcase-describe-dired-file ()
  "Describe the selected files."
  (interactive)
  (clearcase-describe (dired-get-filename)))

;;}}}

;;{{{ What-rule

(defun clearcase-what-rule-current-buffer ()
  (interactive)
  (clearcase-what-rule buffer-file-name))

(defun clearcase-what-rule-dired-file ()
  (interactive)
  (clearcase-what-rule (dired-get-filename)))

;;}}}

;;{{{ List history

(defun clearcase-list-history-current-buffer ()
  "List the change history of the current buffer in a window."
  (interactive)
  (clearcase-list-history buffer-file-name))

(defun clearcase-list-history-dired-file ()
  "List the change history of the current file."
  (interactive)
  (clearcase-list-history (dired-get-filename)))

;;}}}

;;{{{ Ediff

(defun clearcase-ediff-pred-current-buffer ()
  "Use Ediff to compare a version in the current buffer against its predecessor."
  (interactive)
  (clearcase-ediff-file-with-version buffer-file-name
                                     (clearcase-fprop-predecessor-version buffer-file-name)))

(defun clearcase-ediff-pred-dired-file ()
  "Use Ediff to compare the selected version against its predecessor."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-ediff-file-with-version truename
                                       (clearcase-fprop-predecessor-version truename))))

(defun clearcase-ediff-branch-base-current-buffer()
  "Use Ediff to compare a version in the current buffer
against the base of its branch."
  (interactive)
  (clearcase-ediff-file-with-version buffer-file-name
                                     (clearcase-vxpath-version-of-branch-base buffer-file-name)))

(defun clearcase-ediff-branch-base-dired-file()
  "Use Ediff to compare the selected version against the base of its branch."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-ediff-file-with-version truename
                                       (clearcase-vxpath-version-of-branch-base truename))))

(defun clearcase-ediff-named-version-current-buffer (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  buffer-file-name)))
  (clearcase-ediff-file-with-version buffer-file-name version))

(defun clearcase-ediff-named-version-dired-file (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  (dired-get-filename))))
  (clearcase-ediff-file-with-version  (clearcase-fprop-truename (dired-get-filename))
                                      version))

(defun clearcase-ediff-file-with-version (truename other-version)
  (let ((other-vxpath (clearcase-vxpath-cons-vxpath (clearcase-vxpath-element-part truename)
                                                    other-version)))
    (if (clearcase-file-is-in-mvfs-p truename)
        (ediff-files other-vxpath truename)
      (ediff-buffers (clearcase-vxpath-get-version-in-buffer other-vxpath)
                     (find-file-noselect truename t)))))

;;}}}

;;{{{ Applet diff

(defun clearcase-applet-diff-pred-current-buffer ()
  "Use applet to compare a version in the current buffer against its predecessor."
  (interactive)
  (clearcase-applet-diff-file-with-version buffer-file-name
                                           (clearcase-fprop-predecessor-version buffer-file-name)))

(defun clearcase-applet-diff-pred-dired-file ()
  "Use applet to compare the selected version against its predecessor."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-applet-diff-file-with-version truename
                                             (clearcase-fprop-predecessor-version truename))))

(defun clearcase-applet-diff-branch-base-current-buffer()
  "Use applet to compare a version in the current buffer
against the base of its branch."
  (interactive)
  (clearcase-applet-diff-file-with-version buffer-file-name
                                           (clearcase-vxpath-version-of-branch-base buffer-file-name)))

(defun clearcase-applet-diff-branch-base-dired-file()
  "Use applet to compare the selected version against the base of its branch."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-applet-diff-file-with-version truename
                                             (clearcase-vxpath-version-of-branch-base truename))))

(defun clearcase-applet-diff-named-version-current-buffer (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  buffer-file-name)))
  (clearcase-applet-diff-file-with-version buffer-file-name version))

(defun clearcase-applet-diff-named-version-dired-file (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  (dired-get-filename))))
  (clearcase-applet-diff-file-with-version  (clearcase-fprop-truename (dired-get-filename))
                                            version))

(defun clearcase-applet-diff-file-with-version (truename other-version)
  (let* ((other-vxpath (clearcase-vxpath-cons-vxpath (clearcase-vxpath-element-part truename)
                                                     other-version))
         (other-file (if (clearcase-file-is-in-mvfs-p truename)
                         other-vxpath
                       (clearcase-vxpath-get-version-in-temp-file other-vxpath)))
         (applet-name (if clearcase-on-mswindows
                          "cleardiffmrg"
                        "xcleardiff")))
    (start-process-shell-command "Diff"
                                 nil
                                 applet-name
                                 (clearcase-path-canonicalise-slashes (clearcase-path-native other-file))
                                 (clearcase-path-canonicalise-slashes (clearcase-path-native truename)))))

;;}}}

;;{{{ Diff

(defun clearcase-diff-pred-current-buffer ()
  "Use Diff to compare a version in the current buffer against its predecessor."
  (interactive)
  (clearcase-diff-file-with-version buffer-file-name
                                    (clearcase-fprop-predecessor-version buffer-file-name)))

(defun clearcase-diff-pred-dired-file ()
  "Use Diff to compare the selected version against its predecessor."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-diff-file-with-version truename
                                      (clearcase-fprop-predecessor-version truename))))

(defun clearcase-diff-branch-base-current-buffer()
  "Use Diff to compare a version in the current buffer
against the base of its branch."
  (interactive)
  (clearcase-diff-file-with-version buffer-file-name
                                    (clearcase-vxpath-version-of-branch-base buffer-file-name)))

(defun clearcase-diff-branch-base-dired-file()
  "Use Diff to compare the selected version against the base of its branch."
  (interactive)
  (let ((truename (clearcase-fprop-truename (dired-get-filename))))
    (clearcase-diff-file-with-version truename
                                      (clearcase-vxpath-version-of-branch-base truename))))

(defun clearcase-diff-named-version-current-buffer (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  buffer-file-name)))
  (clearcase-diff-file-with-version buffer-file-name version))

(defun clearcase-diff-named-version-dired-file (version)
  ;; nyi: if we're in history-mode, probably should just use
  ;; (read-file-name)
  ;;
  (interactive (list (clearcase-read-version-name "Version for comparison: "
                                                  (dired-get-filename))))
  (clearcase-diff-file-with-version (clearcase-fprop-truename (dired-get-filename))
                                    version))

(defun clearcase-diff-file-with-version (truename other-version)
  (let ((other-vxpath (clearcase-vxpath-cons-vxpath (clearcase-vxpath-element-part truename)
                                                    other-version)))
    (if (clearcase-file-is-in-mvfs-p truename)
        (clearcase-diff-files other-vxpath truename)
      (let ((temp-file (clearcase-vxpath-get-version-in-temp-file other-vxpath)))
        (clearcase-diff-files temp-file truename)
        (delete-file temp-file)))))

;;}}}

;;{{{ Browse vtree

(defun clearcase-browse-vtree-current-buffer ()
  (interactive)
  (clearcase-browse-vtree buffer-file-name))

(defun clearcase-browse-vtree-dired-file ()
  (interactive)
  (clearcase-browse-vtree (dired-get-filename)))

;;}}}

;;{{{ Applet vtree

(defun clearcase-applet-vtree-browser-current-buffer ()
  (interactive)
  (clearcase-applet-vtree-browser buffer-file-name))

(defun clearcase-applet-vtree-browser-dired-file ()
  (interactive)
  (clearcase-applet-vtree-browser (dired-get-filename)))

(defun clearcase-applet-vtree-browser (file)
  (let ((applet-name (if clearcase-on-mswindows
                         "clearvtree"
                       "xlsvtree")))
    (start-process-shell-command "Vtree_browser"
                                 nil
                                 applet-name
                                 (clearcase-path-canonicalise-slashes
                                  (clearcase-path-native file)))))

;;}}}

;;{{{ Other applets

(defun clearcase-applet-rebase ()
  (interactive)
  (start-process-shell-command "Rebase"
                               nil
                               "clearmrgman"
                               (if clearcase-on-mswindows
                                   "/rebase"
                                 "-rebase")))

(defun clearcase-applet-deliver ()
  (interactive)
  (start-process-shell-command "Deliver"
                               nil
                               "clearmrgman"
                               (if clearcase-on-mswindows
                                   "/deliver"
                                 "-deliver")))

(defun clearcase-applet-merge-manager ()
  (interactive)
  (start-process-shell-command "Merge_manager"
                               nil
                               "clearmrgman"))

(defun clearcase-applet-project-explorer ()
  (interactive)
  (start-process-shell-command "Project_explorer"
                               nil
                               "clearprojexp"))

(defun clearcase-applet-snapshot-view-updater ()
  (interactive)
  (start-process-shell-command "View_updater"
                               nil
                               "clearviewupdate"))

;;}}}

;;{{{ Update snapshot

;; In a file buffer:
;;  - update current-file
;;  - update directory
;; In dired:
;;  - update dir
;;  - update marked files
;;  - update file

;; We allow several simultaneous updates, but only one per view.

(defun clearcase-update-view ()
  (interactive)
  (clearcase-update (clearcase-fprop-viewtag default-directory)))

(defun clearcase-update-default-directory ()
  (interactive)
  (clearcase-update (clearcase-fprop-viewtag default-directory) default-directory))

(defun clearcase-update-current-buffer ()
  (interactive)
  (clearcase-update (clearcase-fprop-viewtag default-directory) buffer-file-name))

(defun clearcase-update-dired-files ()
  (interactive)
  (apply (function clearcase-update)
         (cons (clearcase-fprop-viewtag default-directory)
               (dired-get-marked-files))))
;; Silence compiler complaints about free variable.
;;
(defvar clearcase-update-buffer-viewtag nil)

(defun clearcase-update (viewtag &rest pnames)
  "Run a cleartool+update process in VIEWTAG
if there isn't one already running in that view.
Other arguments PNAMES indicate files to update"

  ;; Check that there is no update process running in that view.
  ;;
  (if (apply (function clearcase-utl-or-func)
             (mapcar (function (lambda (proc)
                                 (if (not (eq 'exit (process-status proc)))
                                     (let ((buf (process-buffer proc)))
                                       (and buf
                                            (assq 'clearcase-update-buffer-viewtag (buffer-local-variables buf))
                                            (save-excursion
                                              (set-buffer buf)
                                              (equal viewtag clearcase-update-buffer-viewtag)))))))
                     (process-list)))
      (error "There is already an update running in view %s" viewtag))

  ;; All clear so:
  ;;  - create a process in a buffer
  ;;  - rename the buffer to be of the form *clearcase-update*<N>
  ;;  - mark it as one of ours by setting clearcase-update-buffer-viewtag
  ;;
  (pop-to-buffer (apply (function make-comint)
                        (append (list "clearcase-update-temp-name"
                                      clearcase-cleartool-path
                                      nil
                                      "update")
                                pnames))
                 t);; other window
  (rename-buffer "*clearcase-update*" t)
  (set (make-local-variable 'clearcase-update-buffer-viewtag) viewtag))

;;}}}

;;}}}

;;{{{ Functions

;;{{{ Basic ClearCase operations

;;{{{ Mkelem

(defun clearcase-file-ok-to-mkelem (file)
  "Test if FILE is okay to mkelem."
  (let ((mtype (clearcase-fprop-mtype file)))
    (and (not (file-directory-p file))
         (and (or (equal 'view-private-object mtype)
                  (equal 'derived-object mtype))
              (not (clearcase-file-covers-element-p file))))))

(defun clearcase-assert-file-ok-to-mkelem (file)
  "Raise an exception if FILE is not suitable for mkelem."
  (if (not (clearcase-file-ok-to-mkelem file))
      (error "%s cannot be made into an element" file)))

(defun clearcase-commented-mkelem (file &optional comment)
  "Create a new element from FILE. If COMMENT is non-nil, it
will be used, otherwise the user will be prompted to enter one."

  (clearcase-assert-file-ok-to-mkelem file)

  ;; We may need to checkout the directory.
  ;;
  (let ((containing-dir (file-name-directory file))
        user)
    (if (eq 'directory-version (clearcase-fprop-mtype containing-dir))
        (progn
          (setq user (clearcase-fprop-owner-of-checkout containing-dir))
          (if user
              (if (not (equal user (user-login-name)))
                  (error "Directory is checked-out by %s." user))
            (if (cond
                 ((eq clearcase-checkout-dir-on-mkelem 'ask)
                  (y-or-n-p (format "Checkout directory %s " containing-dir)))
                 (clearcase-checkout-dir-on-mkelem)
                 (t nil))
                (clearcase-commented-checkout containing-dir comment)
              (error "Can't make an element unless directory is checked-out."))))))

  (if (null comment)
      ;; If no comment supplied, go and get one...
      ;;
      (clearcase-comment-start-entry (file-name-nondirectory file)
                                     "Enter initial comment for the new element."
                                     'clearcase-commented-mkelem
                                     (list file)
                                     (find-file-noselect file)
                                     clearcase-initial-mkelem-comment)

    ;; ...otherwise perform the operation.
    ;;
    (clearcase-fprop-unstore-properties file)
    (message "Making element %s..." file)

    (save-excursion
      ;; Sync the buffer to disk.
      ;;
      (let ((buffer-on-file (find-buffer-visiting file)))
        (if buffer-on-file
            (progn
              (set-buffer buffer-on-file)
              (clearcase-sync-to-disk))))

      (if clearcase-checkin-on-mkelem
          (clearcase-ct-do-cleartool-command "mkelem" file comment "-ci")
        (clearcase-ct-do-cleartool-command "mkelem" file comment))
      (message "Making element %s...done" file)

      ;; Resync.
      ;;
      (clearcase-sync-from-disk file t))))

(defun clearcase-commented-mkelem-seq (files &optional comment)
  "Mkelem a sequence of FILES. If COMMENT is supplied it will be
used, otherwise the user will be prompted to enter one."

  (mapcar
   (function clearcase-assert-file-ok-to-mkelem)
   files)

  (if (null comment)
      ;; No comment supplied, go and get one...
      ;;
      (clearcase-comment-start-entry "mkelem"
                                     "Enter comment for elements' creation"
                                     'clearcase-commented-mkelem-seq
                                     (list files))
    ;; ...otherwise operate.
    ;;
    (mapcar
     (function
      (lambda (file)
        (clearcase-commented-mkelem file comment)))
     files)))

;;}}}

;;{{{ Checkin

(defun clearcase-file-ok-to-checkin (file)
  "Test if FILE is suitable for checkin."
  (let ((me (user-login-name)))
    (equal me (clearcase-fprop-owner-of-checkout file))))

(defun clearcase-assert-file-ok-to-checkin (file)
  "Raise an exception if FILE is not suitable for checkin."
  (if (not (clearcase-file-ok-to-checkin file))
      (error "You cannot checkin %s" file)))

(defun clearcase-commented-checkin (file &optional comment)
  "Check-in FILE with COMMENT. If the comment is omitted,
a buffer is popped up to accept one."

  (clearcase-assert-file-ok-to-checkin file)

  (if (null comment)
      ;; If no comment supplied, go and get one..
      ;;
      (progn
        (clearcase-comment-start-entry (file-name-nondirectory file)
                                       "Enter a checkin comment."
                                       'clearcase-commented-checkin
                                       (list file)
                                       (find-file-noselect file)
                                       (clearcase-fprop-comment file))

        ;; Also display a diff, if that is the custom:
        ;;
        (if (and (not (file-directory-p file))
                 clearcase-diff-on-checkin)
            (save-excursion
              (let ((tmp-buffer (current-buffer)))
                (message "Running diff...")
                (clearcase-diff-file-with-version file
                                                  (clearcase-fprop-predecessor-version file))
                (message "Running diff...done")
                (set-buffer "*clearcase*")
                (if (get-buffer "*clearcase-diff*")
                    (kill-buffer "*clearcase-diff*"))
                (rename-buffer "*clearcase-diff*")
                (pop-to-buffer tmp-buffer)))))

    ;; ...otherwise perform the operation.
    ;;
    (message "Checking in %s..." file)
    (save-excursion
      ;; Sync the buffer to disk, and get local value of clearcase-checkin-switches
      ;;
      (let ((buffer-on-file (find-buffer-visiting file)))
        (if buffer-on-file
            (progn
              (set-buffer buffer-on-file)
              (clearcase-sync-to-disk))))
      (apply 'clearcase-ct-do-cleartool-command "ci" file comment
             clearcase-checkin-switches))
    (message "Checking in %s...done" file)

    ;; Resync.
    ;;
    (clearcase-sync-from-disk file t)))

(defun clearcase-commented-checkin-seq (files &optional comment)
  "Checkin a sequence of FILES. If COMMENT is supplied it will be
used, otherwise the user will be prompted to enter one."

  ;; Check they're all in the right state to be checked-in.
  ;;
  (mapcar
   (function clearcase-assert-file-ok-to-checkin)
   files)

  (if (null comment)
      ;; No comment supplied, go and get one...
      ;;
      (clearcase-comment-start-entry "checkin"
                                     "Enter checkin comment."
                                     'clearcase-commented-checkin-seq
                                     (list files))
    ;; ...otherwise operate.
    ;;
    (mapcar
     (function
      (lambda (file)
        (clearcase-commented-checkin file comment)))
     files)))

;;}}}

;;{{{ Checkout

(defun clearcase-file-ok-to-checkout (file)
  "Test if FILE is suitable for checkout."
  (let ((mtype (clearcase-fprop-mtype file)))
    (and (or (eq 'version mtype)
             (eq 'directory-version mtype))
         (not (clearcase-fprop-checked-out file)))))

(defun clearcase-assert-file-ok-to-checkout (file)
  "Raise an exception if FILE is not suitable for checkout."
  (if (not (clearcase-file-ok-to-checkout file))
      (error "You cannot checkout %s" file)))

;; nyi: Offer to setact if appropriate

(defun clearcase-commented-checkout (file &optional comment)
  "Check-out FILE with COMMENT. If the comment is omitted,
a buffer is popped up to accept one."

  (clearcase-assert-file-ok-to-checkout file)

  (if (and (null comment)
           (not clearcase-suppress-checkout-comments))
      ;; If no comment supplied, go and get one...
      ;;
      (clearcase-comment-start-entry (file-name-nondirectory file)
                                     "Enter a checkout comment."
                                     'clearcase-commented-checkout
                                     (list file)
                                     (find-file-noselect file))

    ;; ...otherwise perform the operation.
    ;;
    (message "Checking out %s..." file)
    ;; Change buffers to get local value of clearcase-checkin-switches.
    ;;
    (save-excursion
      (set-buffer (or (find-buffer-visiting file)
                      (current-buffer)))
      (clearcase-ct-do-cleartool-command "co"
                                         file
                                         comment
                                         clearcase-checkout-switches))
    (message "Checking out %s...done" file)

    ;; Resync.
    ;;
    (clearcase-sync-from-disk file t)))


(defun clearcase-commented-checkout-seq (files &optional comment)
  "Checkout a sequence of FILES. If COMMENT is supplied it will be
used, otherwise the user will be prompted to enter one."

  (mapcar
   (function clearcase-assert-file-ok-to-checkout)
   files)

  (if (and (null comment)
           (not clearcase-suppress-checkout-comments))
      ;; No comment supplied, go and get one...
      ;;
      (clearcase-comment-start-entry "checkout"
                                     "Enter a checkout comment."
                                     'clearcase-commented-checkout-seq
                                     (list files))
    ;; ...otherwise operate.
    ;;
    (mapcar
     (function
      (lambda (file)
        (clearcase-commented-checkout file comment)))
     files)))

;;}}}

;;{{{ Uncheckout

(defun clearcase-file-ok-to-uncheckout (file)
  "Test if FILE is suitable for uncheckout."
  (equal (user-login-name)
         (clearcase-fprop-owner-of-checkout file)))

(defun clearcase-assert-file-ok-to-uncheckout (file)
  "Raise an exception if FILE is not suitable for uncheckout."
  (if (not (clearcase-file-ok-to-uncheckout file))
      (error "You cannot uncheckout %s" file)))

(defun clearcase-uncheckout (file)
  "Uncheckout FILE."

  (clearcase-assert-file-ok-to-uncheckout file)

  ;; If it has changed since checkout, insist the user confirm.
  ;;
  (if (and (not (file-directory-p file))
           (clearcase-file-appears-modified-since-checkout-p file)
           (not clearcase-suppress-confirm)
           (not (yes-or-no-p (format "Really discard changes to %s ?" file))))
      (message "Uncheckout of %s cancelled" file)

    ;; Go ahead and unco:
    ;;
    (message "Cancelling checkout of %s..." file)
    ;; nyi:
    ;;  - Prompt for -keep or -rm
    ;;  - offer to remove /0 branches
    ;;
    (clearcase-ct-do-cleartool-command "unco" file 'unused "-keep")
    (message "Cancelling checkout of %s...done" file)

    ;; Resync.
    ;;
    (clearcase-sync-from-disk file)))

(defun clearcase-uncheckout-seq (files)
  "Uncheckout a sequence of FILES."

  (mapcar
   (function clearcase-assert-file-ok-to-uncheckout)
   files)

  (mapcar
   (function clearcase-uncheckout)
   files))

;;}}}

;;{{{ Describe

(defun clearcase-describe (file)
  "Give a ClearCase description of FILE."
  (clearcase-ct-do-cleartool-command "describe" file 'unused)
  (clearcase-port-view-buffer-other-window "*clearcase*")
  (goto-char 0)
  (shrink-window-if-larger-than-buffer))

(defun clearcase-describe-seq (files)
  "Give a ClearCase description of the sequence of FILES."
  (error "Not yet implemented"))

;;}}}

;;{{{ Mkbrtype

(defun clearcase-commented-mkbrtype (typename &optional comment)
  (if (null comment)
      (clearcase-comment-start-entry (format "mkbrtype:%s" typename)
                                     "Enter a comment for the new branch type."
                                     'clearcase-commented-mkbrtype
                                     (list typename))
    (clearcase-with-tempfile
     comment-file
     (let ((qualified-typename typename))
       (write-region comment nil comment-file nil 'noprint)
       (if (not (string-match "@" typename))
           (setq qualified-typename
                 (format "%s@%s" typename default-directory)))
       
       (clearcase-ct-cleartool-cmd "mkbrtype"
                                   "-cfile"
                                   (clearcase-path-native comment-file)
                                   qualified-typename)))))
;;}}}

;;{{{ Browse vtree (using Dired Mode)

(defun clearcase-file-ok-to-browse (file)
  (and file
       (or (equal 'version (clearcase-fprop-mtype file))
           (equal 'directory-version (clearcase-fprop-mtype file)))
       (clearcase-file-is-in-mvfs-p file)))

(defun clearcase-browse-vtree (file)
  (if (not (clearcase-fprop-file-is-version-p file))
      (error "%s is not a Clearcase element" file))

  (if (not (clearcase-file-is-in-mvfs-p file))
      (error "File is not in MVFS"))

  (let* ((version-path (clearcase-vxpath-cons-vxpath
                        file
                        (or (clearcase-vxpath-version-part file)
                            (clearcase-fprop-version file))))
         ;; nyi: Can't seem to get latest first here.
         ;;
         (dired-listing-switches (concat dired-listing-switches
                                         "rt"))

         (branch-path (clearcase-vxpath-branch version-path))

         ;; Position cursor to the version we came from.
         ;; If it was checked-out, go to predecessor.
         ;;
         (version-number (clearcase-vxpath-version
                          (if (clearcase-fprop-checked-out file)
                              (clearcase-fprop-predecessor-version file)
                            version-path))))

    (if (file-exists-p version-path)
        (progn
          ;; Invoke dired on the directory of the version branch.
          ;;
          (dired branch-path)
          
          (clearcase-dired-sort-by-date)

          (if (re-search-forward (concat "[ \t]+"
                                         "\\("
                                         (regexp-quote version-number)
                                         "\\)"
                                         "$")
                                 nil
                                 t)
              (goto-char (match-beginning 1))))
      (dired (concat file clearcase-vxpath-glue))

      ;; nyi: We want ANY directory in the history tree to appear with
      ;;      newest first. Probably requires a hook to dired mode.
      ;;
      (clearcase-dired-sort-by-date))))

;;}}}

;;{{{ List history

(defun clearcase-list-history (file)
  "List the change history of FILE."

  (if (eq 'version (clearcase-fprop-mtype file))
      (progn
        (clearcase-ct-do-cleartool-command "lshistory" file 'unused)
        (pop-to-buffer (get-buffer-create "*clearcase*"))
        (setq default-directory (file-name-directory file))
        (while (looking-at "=*\n")
          (delete-char (- (match-end 0) (match-beginning 0)))
          (forward-line -1))
        (goto-char (point-min))
        (if (looking-at "[\b\t\n\v\f\r ]+")
            (delete-char (- (match-end 0) (match-beginning 0))))
        (shrink-window-if-larger-than-buffer))
    (error "%s is not a ClearCase element" file)))

;;}}}

;;{{{ Diff/cmp

(defun clearcase-files-are-identical (f1 f2)
  "Test if FILE1 and FILE2 have identical contents."

  (clearcase-when-debugging
   (if (not (file-exists-p f1))
       (error "%s  non-existent" f1))
   (if (not (file-exists-p f2))
       (error "%s  non-existent" f2)))

  (zerop (call-process "cleardiff" nil nil nil "-status_only" f1 f2)))

(defun clearcase-diff-files (file1 file2)
  "Run cleardiff on FILE1 and FILE2 and display the differences."
  ;; Fix `file1' path since it's passed as a fully-qualified argument
  ;; to the command. `file2' will be split into path and base name
  ;; parts in `clearcase-do-command' which works correctly whether the
  ;; path is native or not. If we do decide that `file2' should also
  ;; be fixed up, the rigtht place is probably within
  ;; `clearcase-do-command' as `file2' becomes the one known file
  ;; argument there.
  (let ((file1 (clearcase-path-native file1)))
    (if clearcase-use-normal-diff
        (clearcase-do-command 2 clearcase-normal-diff-program file2 clearcase-normal-diff-switches file1)
      (clearcase-do-command 2 "cleardiff" file2 "-diff_format" file1))
    (let ((diff-size (save-excursion
                       (set-buffer "*clearcase*")
                       (buffer-size))))
      (if (zerop diff-size)
          (message "No differences")
        (clearcase-port-view-buffer-other-window "*clearcase*")
        (goto-char 0)
        (shrink-window-if-larger-than-buffer)))))

;;}}}

;;{{{ What rule

(defun clearcase-what-rule (file)
  (let ((result (clearcase-ct-cleartool-cmd "ls"
                                            "-d"
                                            (clearcase-path-native file))))
    (if (string-match "Rule: \\(.*\\)\n" result)
        (message (substring result
                            ;; Be a little more verbose
                            (match-beginning 0) (match-end 1)))
      (error result))))

;;}}}

;;}}}

;;{{{ File property cache

;; ClearCase properties of files are stored in a vector in a hashtable
;; with the absolute-filename (with no trailing slashes) as the lookup key.
;;
;; Properties are:
;;
;; [0] truename            : string
;; [1] mtype               : { nil, view-private-object, version,
;;                             directory-version, file-element,
;;                             dir-element, derived-object
;;                           }
;; [2] checked-out         : boolean
;; [3] reserved            : boolean
;; [4] version             : string
;; [5] predecessor-version : string
;; [6] oid                 : string
;; [7] user                : string
;; [8] date                : string (yyyymmdd.hhmmss)
;; [9] time-last-described : (N, N, N) time when the properties were last read from ClearCase
;; [10] viewtag            : string
;; [11] comment            : string

;; nyi: other possible properties to record:
;;      mtime when last described (lets us know when the cached properties might be stale)

;;{{{ Debug code

(defun clearcase-fprop-unparse-properties (properties)
  "Return a string suitable for printing PROPERTIES."
  (concat
   (format "truename:            %s\n" (aref properties 0))
   (format "mtype:               %s\n" (aref properties 1))
   (format "checked-out:         %s\n" (aref properties 2))
   (format "reserved:            %s\n" (aref properties 3))
   (format "version:             %s\n" (aref properties 4))
   (format "predecessor-version: %s\n" (aref properties 5))
   (format "oid:                 %s\n" (aref properties 6))
   (format "user:                %s\n" (aref properties 7))
   (format "date:                %s\n" (aref properties 8))
   (format "time-last-described: %s\n" (current-time-string (aref properties 9)))
   (format "viewtag:             %s\n" (aref properties 10))
   (format "comment:             %s\n" (aref properties 11))))

(defun clearcase-fprop-display-properties (file)
  "Display the recorded ClearCase properties of FILE."
  (interactive "F")
  (let* ((abs-file (expand-file-name file))
         (properties (clearcase-fprop-lookup-properties abs-file))
         (camefrom (current-buffer)))
    (if properties
        (progn
          (set-buffer (get-buffer-create "*clearcase*"))
          (clearcase-view-mode 0 camefrom)
          (erase-buffer)
          (insert (clearcase-fprop-unparse-properties properties))
          (clearcase-port-view-buffer-other-window "*clearcase*")
          (goto-char 0)
          (set-buffer-modified-p nil)   ; XEmacs - fsf uses `not-modified'
          (shrink-window-if-larger-than-buffer))
      (error "Properties for %s not stored" file))))

(defun clearcase-fprop-dump (&optional buf)
  "Dump out the table recording ClearCase properties of files."
  (interactive)
  (let ((output-buffer (if buf
                           buf
                         (get-buffer-create "*clearcase-fprop-dump*")))
        (camefrom (current-buffer)))
    (set-buffer output-buffer)
    (or buf (clearcase-view-mode 0 camefrom))
    (or buf (erase-buffer))
    (insert (format "File describe count: %s\n" clearcase-fprop-describe-count))
    (mapatoms
     (function
      (lambda (symbol)
        (let ((properties (symbol-value symbol)))
          (insert "\n"
                  (format "key:                 %s\n" (symbol-name symbol))
		  "\n"
                  (clearcase-fprop-unparse-properties properties)))))
     clearcase-fprop-hashtable)
    (insert "\n")
    (or buf
        (progn
          (clearcase-port-view-buffer-other-window output-buffer)
          (goto-char 0)
          (set-buffer-modified-p nil)   ; XEmacs - fsf uses `not-modified'
          (shrink-window-if-larger-than-buffer)))))

;;}}}

(defvar clearcase-fprop-hashtable (make-vector 31 0)
  "Obarray for per-file ClearCase properties.")

(defun clearcase-fprop-canonicalise-path (filename)
  ;; We want DIR/y and DIR\y to map to the same cache entry on ms-windows.
  ;; We want DIR and DIR/ (and on windows DIR\) to map to the same cache entry.
  ;; 
  ;; However, on ms-windows avoid canonicalising X:/ to X: because, for some
  ;; reason, cleartool+desc fails on X:, but works on X:/
  ;;
  (setq filename (clearcase-path-canonicalise-slashes filename))
  (if (and clearcase-on-mswindows
           (string-match (concat "^" "[A-Za-z]:" clearcase-pname-sep-regexp "$")
                         filename))
      filename
    (clearcase-utl-strip-trailing-slashes filename)))

(defun clearcase-fprop-clear-all-properties ()
  "Delete all entries in the clearcase-fprop-hashtable."
  (setq clearcase-fprop-hashtable (make-vector 31 0)))

(defun clearcase-fprop-store-properties (file properties)
  "For FILE, store its ClearCase PROPERTIES in the clearcase-fprop-hashtable."
  (assert (file-name-absolute-p file))
  (set (intern (clearcase-fprop-canonicalise-path file)
               clearcase-fprop-hashtable) properties))

(defun clearcase-fprop-unstore-properties (file)
  "For FILE, delete its entry in the clearcase-fprop-hashtable."
  (assert (file-name-absolute-p file))
  (unintern (clearcase-fprop-canonicalise-path file) clearcase-fprop-hashtable))

(defun clearcase-fprop-lookup-properties (file)
  "For FILE, lookup and return its ClearCase properties from the
clearcase-fprop-hashtable."
  (assert (file-name-absolute-p file))
  (symbol-value (intern-soft (clearcase-fprop-canonicalise-path file)
                             clearcase-fprop-hashtable)))

(defun clearcase-fprop-get-properties (file)
  "For FILE, make sure its ClearCase properties are in the hashtable
and then return them."
  (or (clearcase-fprop-lookup-properties file)
      (let ((properties
	     (condition-case signal-info
		 (clearcase-fprop-read-properties file)
	       (error
                (progn
                  (clearcase-trace (format "(clearcase-fprop-read-properties %s) signalled error: %s"
                                           file
                                           (cdr signal-info)))
                  (make-vector 31 nil))))))
        (clearcase-fprop-store-properties file properties)
        properties)))

(defun clearcase-fprop-truename (file)
  "For FILE, return its \"truename\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 0))

(defun clearcase-fprop-mtype (file)
  "For FILE, return its \"mtype\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 1))

(defun clearcase-fprop-checked-out (file)
  "For FILE, return its \"checked-out\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 2))

(defun clearcase-fprop-reserved (file)
  "For FILE, return its \"reserved\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 3))

(defun clearcase-fprop-version (file)
  "For FILE, return its \"version\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 4))

(defun clearcase-fprop-predecessor-version (file)
  "For FILE, return its \"predecessor-version\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 5))

(defun clearcase-fprop-oid (file)
  "For FILE, return its \"oid\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 6))

(defun clearcase-fprop-user (file)
  "For FILE, return its \"user\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 7))

(defun clearcase-fprop-date (file)
  "For FILE, return its \"date\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 8))

(defun clearcase-fprop-time-last-described (file)
  "For FILE, return its \"time-last-described\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 9))

(defun clearcase-fprop-viewtag (file)
  "For FILE, return its \"viewtag\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 10))

(defun clearcase-fprop-comment (file)
  "For FILE, return its \"comment\" ClearCase property."
  (aref (clearcase-fprop-get-properties file) 11))

(defun clearcase-fprop-set-comment (file comment)
  "For FILE, set its \"comment\" ClearCase property to COMMENT."
  (aset (clearcase-fprop-get-properties file) 11 comment))

(defun clearcase-fprop-owner-of-checkout (file)
  "For FILE, return whether the current user has it checked-out."
  (if (clearcase-fprop-checked-out file)
      (clearcase-fprop-user file)
    nil))

(defun clearcase-fprop-file-is-version-p (object-name)
  (if object-name
      (let ((mtype (clearcase-fprop-mtype object-name)))
        (or (eq 'version mtype)
            (eq 'directory-version mtype)))))

;; Read the object's ClearCase properties using cleartool and the Lisp reader.
;;
;; nyi: for some reason the \n before the %c necessary here so avoid confusing the
;;      cleartool/tq interface.  Completely mysterious. Arrived at by
;;      trial and error.
;;
(defvar clearcase-fprop-fmt-string

  ;; Yuck.  Different forms of quotation are needed here apparently to deal with
  ;; all the various ways of spawning sub-process on the the various platforms
  ;; (XEmacs vs. GnuEmacs, Win32 vs. Unix, Cygwin-built vs. native-built).
  ;;
  (if clearcase-on-mswindows
      (if clearcase-xemacs-p
          ;; XEmacs/Windows
          ;;
	  (if clearcase-on-cygwin32
	      ;; Cygwin build
	      ;;
	      "[nil \\\"%m\\\" \\\"%f\\\" \\\"%Rf\\\" \\\"%Sn\\\" \\\"%PSn\\\" \\\"%On\\\" \\\"%u\\\" \\\"%Nd\\\" nil nil nil]\\n%c"
	    ;; Native build
	    ;;
	    ;;"\"[nil \\\"%m\\\" \\\"%f\\\" \\\"%Rf\\\" \\\"%Sn\\\" \\\"%PSn\\\" \\\"%On\\\" \\\"%u\\\" \\\"%Nd\\\" nil nil nil]\n%c\"")
            "[nil \\\"%m\\\" \\\"%f\\\" \\\"%Rf\\\" \\\"%Sn\\\" \\\"%PSn\\\" \\\"%On\\\" \\\"%u\\\" \\\"%Nd\\\" nil nil nil]\n%c")            

        ;; GnuEmacs/Windows
        ;;
        "[nil \"%m\" \"%f\" \"%Rf\" \"%Sn\" \"%PSn\" \"%On\" \"%u\" \"%Nd\" nil nil nil]\\n%c")
    ;; Unix
    ;;
    "'[nil \"%m\" \"%f\" \"%Rf\" \"%Sn\" \"%PSn\" \"%On\" \"%u\" \"%Nd\" nil nil nil]\\n%c'")
  
  "Format for cleartool+describe command when reading the
ClearCase properties of a file")

(defvar clearcase-fprop-describe-count 0
  "Count the number of times clearcase-fprop-read-properties is called")

(defun clearcase-fprop-read-properties (file)
  "Invoke the cleartool+describe command to obtain the ClearCase
properties of FILE."
  (assert (file-name-absolute-p file))
  (let* ((truename (clearcase-fprop-canonicalise-path (file-truename (expand-file-name file)))))

    ;; If the object doesn't exist, signal an error
    ;;
    (if (or (not (file-exists-p (clearcase-vxpath-element-part file)))
            (not (file-exists-p (clearcase-vxpath-element-part truename))))
        (error "File doesn't exist: %s" file)

      ;; Run cleartool+ describe and capture the output as a string:
      ;;
      (let ((desc-string (clearcase-ct-cleartool-cmd "desc"
                                                     "-fmt"
                                                     clearcase-fprop-fmt-string
                                                     (clearcase-path-native truename))))
        (setq clearcase-fprop-describe-count (1+ clearcase-fprop-describe-count))

        ;;(clearcase-trace (format "desc of %s <<<<" truename))
        ;;(clearcase-trace desc-string)
        ;;(clearcase-trace (format "desc of %s >>>>" truename))

        ;; Read all but the comment, using the Lisp reader, and then copy
        ;; what's left as the comment.  We don't try to use the Lisp reader to
        ;; fetch the comment to avoid problems with quotation.
        ;;
        ;; nyi: it would be nice if we could make cleartool use "/" as pname-sep,
        ;;      because read-from-string will barf on imbedded "\".  For now
        ;;      run clearcase-path-canonicalise-slashes over the cleartool
        ;;      output before invoking the Lisp reader.
        ;;
        (let* ((first-read (read-from-string (clearcase-path-canonicalise-slashes desc-string)))
               (result (car first-read))
               (bytes-read (cdr first-read))
               (comment (substring desc-string (1+ bytes-read))));; skip \n

          ;; Plug in the slots I left empty:
          ;;
          (aset result 0 truename)
          (aset result 9 (current-time))

          (aset result 11 comment)

          ;; Convert mtype to an enumeration:
          ;;
          (let ((mtype-string (aref result 1)))
            (cond
             ((string= mtype-string "version")
              (aset result 1 'version))

             ((string= mtype-string "directory version")
              (aset result 1 'directory-version))

             ((string= mtype-string "view private object")
              (aset result 1 'view-private-object))

             ((string= mtype-string "file element")
              (aset result 1 'file-element))

             ((string= mtype-string "directory element")
              (aset result 1 'directory-element))

             ((string= mtype-string "derived object")
              (aset result 1 'derived-object))

             ;; For now treat checked-in DOs as versions.
             ;;
             ((string= mtype-string "derived object version")
              (aset result 1 'version))

             ;; On NT, coerce the mtype of symlinks into that
             ;; of their targets.
             ;;
             ;; nyi: I think this is approximately right.
             ;;
             ((and (string= mtype-string "symbolic link")
                   clearcase-on-mswindows)
              (if (file-directory-p truename)
                  (aset result 1 'directory-version)
                (aset result 1 'version)))

             ;; We get this on paths like foo.c@@/main
             ;;
             ((string= mtype-string "branch")
              (aset result 1 'branch))

             ((string= mtype-string "**null meta type**")
              (aset result 1 nil))

             (t
              (error "Unknown mtype returned by cleartool+describe: %s"
                     mtype-string))))

          ;; nyi: possible efficiency win: only evaluate the viewtag on demand.
          ;;
          (if (aref result 1)
              (aset result 10 (clearcase-file-viewtag truename)))

          ;; Convert checked-out field to boolean:
          ;;
          (aset result 2 (not (zerop (length (aref result 2)))))

          ;; Convert reserved field to boolean:
          ;;
          (aset result 3 (string= "reserved" (aref result 3)))

          ;; Return the array of properties.
          ;;
          result)))))

;;}}}

;;{{{ View property cache

;; ClearCase properties of views are stored in a vector in a hashtable
;; with the viewtag as the lookup key.
;;
;; Properties are:
;;
;; [0] ucm                 : boolean
;; [1] stream              : string
;; [2] pvob                : string
;; [3] activities          : list of strings
;; [4] current-activity    : string

;;{{{ Debug code

(defun clearcase-vprop-dump (&optional buf)
  "Dump out the table recording ClearCase properties of views."
  (interactive)
  (let ((output-buffer (if buf
                           buf
                         (get-buffer-create "*clearcase-vprop-dump*")))
        (camefrom (current-buffer)))
    (set-buffer output-buffer)
    (or buf (clearcase-view-mode 0 camefrom))
    (or buf (erase-buffer))
    (insert (format "View describe count: %s\n" clearcase-vprop-describe-count))
    (mapatoms
     (function
      (lambda (symbol)
        (let ((properties (symbol-value symbol)))
          (insert "\n"
		  (format "viewtag:             %s\n" (symbol-name symbol))
		  "\n"
		  (clearcase-vprop-unparse-properties properties)))))
     clearcase-vprop-hashtable)
    (insert "\n")
    (or buf
        (progn
          (clearcase-port-view-buffer-other-window output-buffer)
          (goto-char 0)
          (set-buffer-modified-p nil)   ; XEmacs - fsf uses `not-modified'
          (shrink-window-if-larger-than-buffer)))))

(defun clearcase-vprop-unparse-properties (properties)
  "Return a string suitable for printing PROPERTIES."
  (concat
   (format "ucm:                 %s\n" (aref properties 0))
   (format "stream:              %s\n" (aref properties 1))
   (format "pvob:                %s\n" (aref properties 2))
   (format "activities:          %s\n" (aref properties 3))
   (format "current-activity:    %s\n" (aref properties 4))))

;;}}}

;;{{{ Asynchronously fetching view properties:

(defvar clearcase-vprop-timer nil)
(defvar clearcase-vprop-prefetch-queue nil)

(defun clearcase-vprop-schedule-fetch (viewtag)
  (or clearcase-xemacs-p
      (if (null clearcase-vprop-timer)
          (setq clearcase-vprop-timer (timer-create))))
  (setq clearcase-vprop-prefetch-queue (cons viewtag clearcase-vprop-prefetch-queue))
  (if clearcase-xemacs-p
      (setq clearcase-vprop-timer
            (run-with-idle-timer 5 t 'clearcase-vprop-timer-function))
    (timer-set-function clearcase-vprop-timer 'clearcase-vprop-timer-function)
    (timer-set-idle-time clearcase-vprop-timer 5)
    (timer-activate-when-idle clearcase-vprop-timer)))

(defun clearcase-vprop-timer-function ()
  (mapcar (function (lambda (viewtag)
                      (clearcase-vprop-get-properties viewtag)))
          clearcase-vprop-prefetch-queue)
  (setq clearcase-vprop-prefetch-queue nil))

;;}}}

(defvar clearcase-vprop-hashtable (make-vector 31 0)
  "Obarray for per-view ClearCase properties.")

(defun clearcase-vprop-clear-all-properties ()
  "Delete all entries in the clearcase-vprop-hashtable."
  (setq clearcase-vprop-hashtable (make-vector 31 0)))

(defun clearcase-vprop-store-properties (viewtag properties)
  "For VIEW, store its ClearCase PROPERTIES in the clearcase-vprop-hashtable."
  (set (intern viewtag clearcase-vprop-hashtable) properties))

(defun clearcase-vprop-unstore-properties (viewtag)
  "For VIEWTAG, delete its entry in the clearcase-vprop-hashtable."
  (unintern viewtag clearcase-vprop-hashtable))

(defun clearcase-vprop-lookup-properties (viewtag)
  "For VIEWTAG, lookup and return its ClearCase properties from the
clearcase-vprop-hashtable."
  (symbol-value (intern-soft viewtag clearcase-vprop-hashtable)))

(defun clearcase-vprop-get-properties (viewtag)
  "For VIEWTAG, make sure it's ClearCase properties are in the hashtable
and then return them."
  (or (clearcase-vprop-lookup-properties viewtag)
      (let ((properties (clearcase-vprop-read-properties viewtag)))
        (clearcase-vprop-store-properties viewtag properties)
        properties)))

(defun clearcase-vprop-ucm (viewtag)
  "For VIEWTAG, return its \"ucm\" ClearCase property."
  (aref (clearcase-vprop-get-properties viewtag) 0))

(defun clearcase-vprop-stream (viewtag)
  "For VIEWTAG, return its \"stream\" ClearCase property."
  (aref (clearcase-vprop-get-properties viewtag) 1))

(defun clearcase-vprop-pvob (viewtag)
  "For VIEWTAG, return its \"stream\" ClearCase property."
  (aref (clearcase-vprop-get-properties viewtag) 2))

(defun clearcase-vprop-activities (viewtag)
  "For VIEWTAG, return its \"activities\" ClearCase property."

  ;; If the activity set has been flushed, go and schedule a re-fetch.
  ;;
  (let ((properties (clearcase-vprop-get-properties viewtag)))
    (if (null (aref properties 3))
        (aset properties 3 (clearcase-vprop-read-activities-asynchronously viewtag))))

  ;; Now poll, waiting for the activities to be available.
  ;;
  (let ((loop-count 0))
    ;; If there is a background process still reading the activities,
    ;; wait for it to finish.
    ;;
    ;; nyi: probably want a timeout here.
    ;;
    ;; nyi: There seems to be a race on NT in accept-process-output so that
    ;;      we would wait forever.
    ;;
    (if (not clearcase-on-mswindows)
        ;; Unix synchronization with the end of the process
        ;; which is reading activities.
        ;;
        (while (bufferp (aref (clearcase-vprop-get-properties viewtag) 3))
          (save-excursion
            (set-buffer (aref (clearcase-vprop-get-properties viewtag) 3))
            (message "Reading activity list...")
            (setq loop-count (1+ loop-count))
            (accept-process-output clearcase-vprop-async-proc)))
      
      ;; NT synchronization with the end of the process which is reading
      ;; activities.
      ;;
      ;; Unfortunately on NT we can't rely on the process sentinel being called
      ;; so we have to explicitly test the process status.
      ;;
      (while (bufferp (aref (clearcase-vprop-get-properties viewtag) 3))
        (message "Reading activity list...")
        (save-excursion
          (set-buffer (aref (clearcase-vprop-get-properties viewtag) 3))
          (if (or (not (processp clearcase-vprop-async-proc))
                  (eq 'exit (process-status clearcase-vprop-async-proc)))

              ;; The process has finished or gone away and apparently
              ;; the sentinel didn't get called which would have called
              ;; clearcase-vprop-finish-reading-activities, so call it
              ;; explicitly here.
              ;;
              (clearcase-vprop-finish-reading-activities (current-buffer))

            ;; The process is apparently still running, so wait
            ;; so more.
            (setq loop-count (1+ loop-count))
            (sit-for 1)))))
      
    (if (not (zerop loop-count))
        (message "Reading activity list...done"))
    
    (aref (clearcase-vprop-get-properties viewtag) 3)))
  
(defun clearcase-vprop-current-activity (viewtag)
  "For VIEWTAG, return its \"current-activity\" ClearCase property."
  (aref (clearcase-vprop-get-properties viewtag) 4))

(defun clearcase-vprop-set-activities (viewtag activities)
  "For VIEWTAG, set its \"activities\" ClearCase property to ACTIVITIES."
  (let ((properties (clearcase-vprop-lookup-properties viewtag)))
    ;; We must only set the activities for an existing vprop entry.
    ;;
    (assert properties)
    (aset properties 3 activities)))

(defun clearcase-vprop-flush-activities (viewtag)
  "For VIEWTAG, set its \"activities\" ClearCase property to nil,
to cause a future re-fetch."
  (clearcase-vprop-set-activities viewtag nil))
  
(defun clearcase-vprop-set-current-activity (viewtag activity)
  "For VIEWTAG, set its \"current-activity\" ClearCase property to ACTIVITY."
  (aset (clearcase-vprop-get-properties viewtag) 4 activity))

;; Read the object's ClearCase properties using cleartool lsview and cleartool lsstream.

(defvar clearcase-vprop-describe-count 0
  "Count the number of times clearcase-vprop-read-properties is called")

(defvar clearcase-lsstream-fmt-string
  (if clearcase-on-mswindows
      (if clearcase-xemacs-p
          ;; XEmacs/Windows
          ;;
	  (if clearcase-on-cygwin32
	      ;; Cygwin build
	      ;;
	      "[\\\"%n\\\"  \\\"%[master]p\\\" ]"
	    ;; Native build
	    ;;
	    "[\\\"%n\\\"  \\\"%[master]p\\\" ]")
        ;; GnuEmacs/Windows
        ;;
        "[\"%n\"  \"%[master]p\" ]")
    ;; Unix
    ;;
    "'[\"%n\"  \"%[master]p\" ]'"))

(defun clearcase-vprop-read-properties (viewtag)
  "Invoke cleartool commands to obtain the ClearCase
properties of VIEWTAG."

  ;; We used to use "ct+lsview -properties -full TAG", but this seemed to take
  ;; a long time in some circumstances. It appears to be because the
  ;; ADM_VIEW_GET_INFO RPC can take up to 60 seconds in certain circumstances
  ;; (typically on my laptop with self-contained ClearCase region).

  ;; Accordingly, since we don't really need to store snapshotness, the minimum we
  ;; really need to discover about a view is whether it is UCM-attached. For
  ;; this the much faster ct+lsstream suffices.
  ;;
  (let* ((result (make-vector 5 nil)))
    (if (not clearcase-v3)
        (let ((ucm nil)
              (stream nil)
              (pvob nil)
              (activity-names nil)
              (activity-titles nil)
              (activities nil)
              (current-activity nil)
              (desc-string
               (progn
                 (message "Reading view properties...")
                 (clearcase-ct-blocking-call "lsstream" "-fmt"
                                             clearcase-lsstream-fmt-string
                                             "-view" viewtag))))
          
          (setq clearcase-vprop-describe-count (1+ clearcase-vprop-describe-count))

          (if (setq ucm (not (zerop (length desc-string))))

              ;; It's apparently a UCM view
              ;;
              (let* ((first-read (read-from-string (clearcase-utl-escape-backslashes desc-string)))
                     (array-read (car first-read))
                     (bytes-read (cdr first-read)))

                ;; Get stream name
                ;;
                (setq stream (aref array-read 0))
                
                ;; Get PVOB tag from something like "unix@/vobs/projects"
                ;;
                (let ((s (aref array-read 1)))
                  (if (string-match "@" s)
                      (setq pvob (substring s (match-end 0)))
                    (setq pvob s)))
          
                ;; Get the activity list and store as a list of (NAME . TITLE) pairs
                ;;
                (setq activities (clearcase-vprop-read-activities-asynchronously viewtag))
                
                ;; Get the current activity
                ;;
                (let ((name-string (clearcase-ct-blocking-call "lsact" "-cact" "-fmt" "%n"
                                                               "-view" viewtag)))
                  (if (not (zerop (length name-string)))
                      (setq current-activity name-string)))

                (aset result 0 ucm)
                (aset result 1 stream)
                (aset result 2 pvob)
                (aset result 3 activities)
                (aset result 4 current-activity)))

          (message "Reading view properties...done")))
    
    result))

(defvar clearcase-vprop-async-viewtag nil)
(defvar clearcase-vprop-async-proc nil)
(defun clearcase-vprop-read-activities-asynchronously (viewtag)
  ;; Clean up old instance of the buffer we use to fetch activities:
  ;;
  (let ((buf (get-buffer (format "*clearcase-activity-listing-%s*" viewtag))))
    (if buf
        (progn
          (save-excursion
            (set-buffer buf)
            (if (and (boundp 'clearcase-vprop-async-proc)
                     clearcase-vprop-async-proc)
                (condition-case nil
                    (kill-process clearcase-vprop-async-proc)
                  (error nil))))
          (kill-buffer buf))))

  ;; Create a buffer and an associated new process to read activities
  ;; in the background. We return the buffer to be stored in the
  ;; activities field of the view-properties record. The function
  ;; clearcase-vprop-activities will recognise when the asynch fetching
  ;; is still underway and wait for it to finish.
  ;;
  ;; The process has a sentinel function which is supposed to get called when
  ;; the process finishes. This sometimes doesn't happen on Windows, so that
  ;; clearcase-vprop-activities has to do a bit more work.  (Perhaps a race exists:
  ;; the process completes before the sentinel can be set ?)
  ;;
  (let* ((buf (get-buffer-create (format "*clearcase-activity-listing-%s*" viewtag)))
         (proc (start-process (format "*clearcase-activity-listing-%s*" viewtag)
                              buf
                              clearcase-cleartool-path
                              "lsact" "-view" viewtag)))
    (process-kill-without-query proc)
    (save-excursion
      (set-buffer buf)
      ;; Create a sentinel to parse and store the activities when the
      ;; process finishes. We record the viewtag as a buffer-local
      ;; variable so the sentinel knows where to store the activities.
      ;;
      (set (make-local-variable 'clearcase-vprop-async-viewtag) viewtag)
      (set (make-local-variable 'clearcase-vprop-async-proc) proc)
      (set-process-sentinel proc 'clearcase-vprop-read-activities-sentinel))
    ;; Return the buffer.
    ;;
    buf))

(defun clearcase-vprop-read-activities-sentinel (process event-string)
  (clearcase-trace "Activity reading process sentinel called")
  (if (not (equal "finished\n" event-string))
      ;; Failure
      ;;
      (error "Reading activities failed: %s" event-string))
  (clearcase-vprop-finish-reading-activities (process-buffer process)))

(defun clearcase-vprop-finish-reading-activities (buffer)
  (let ((activity-list nil))
    (message "Parsing view activities...")
    (save-excursion
      (set-buffer buffer)
      (if (or (not (boundp 'clearcase-vprop-async-viewtag))
              (null clearcase-vprop-async-viewtag))
          (error "Internal error: clearcase-vprop-async-viewtag not set"))

      ;; Check that our buffer is the one currently expected to supply the
      ;; activities. (Avoid races.)
      ;;
      (let ((properties (clearcase-vprop-lookup-properties clearcase-vprop-async-viewtag)))
        (if (and properties
                 (eq buffer (aref properties 3)))
            (progn

              ;; Parse the buffer, slicing out the 2nd and 4th fields as name and title.
              ;;
              (goto-char (point-min))
              (while (re-search-forward "^[^ \t]+[ \t]+\\([^ \t]+\\)[ \t]+[^ \t]+[ \t]+\"+\\(.*\\)\"$" nil t)
                (let ((id (buffer-substring (match-beginning 1)
                                            (match-end 1)))
                      (title (buffer-substring (match-beginning 2)
                                               (match-end 2))))
                  (setq activity-list (cons (cons id title)
                                            activity-list))))

              ;; We've got activity-list in the reverse order that
              ;; cleartool+lsactivity generated them.  I think this is reverse
              ;; chronological order, so keep this order since it is more
              ;; convenient when setting to an activity.
              ;;
              ;;(setq activity-list (nreverse activity-list))
              
              (clearcase-vprop-set-activities clearcase-vprop-async-viewtag activity-list))
          
          (kill-buffer buffer))))
    (message "Parsing view activities...done")))

;;{{{ old synchronous activity reader

(defun clearcase-vprop-read-activities-synchronously (viewtag)
  "Return a list of (activity-name . title) pairs for VIEWTAG"
  ;; nyi: ought to use a variant of clearcase-ct-blocking-call that returns a buffer
  ;;      rather than a string

  ;; Performance: takes around 30 seconds to read 1000 activities.
  ;; Too slow to invoke willy-nilly on integration streams for example,
  ;; which typically can have 1000+ activities.

  (let ((ret (clearcase-ct-blocking-call "lsact" "-view" viewtag)))
    (let ((buf (get-buffer-create "*clearcase-activity-listing*"))
          (activity-list nil))
      (save-excursion
        (set-buffer buf)
        (erase-buffer)
        (insert ret)
        (goto-char (point-min))
        ;; Slice out the 2nd and 4th fields as name and title
        ;;
        (while (re-search-forward "^[^ \t]+[ \t]+\\([^ \t]+\\)[ \t]+[^ \t]+[ \t]+\"+\\(.*\\)\"$" nil t)
          (setq activity-list (cons (cons (buffer-substring (match-beginning 1)
                                                            (match-end 1))
                                          (buffer-substring (match-beginning 2)
                                                            (match-end 2)))
                                    activity-list)))
        (kill-buffer buf))

      ;; We've got activity-list in the reverse order that
      ;; cleartool+lsactivity generated them.  I think this is reverse
      ;; chronological order, so keep this order since it is more
      ;; convenient when setting to an activity.
      ;;
      ;;(nreverse activity-list))))
      activity-list)))

;;}}}

;;}}}

;;{{{ Determining if a checkout was modified.

;; How to tell if a file has been changed since checkout ?

;; If it's size differs from pred, it changed.
;; If we saw the first OID after checkout and it is different now, it changed
;; Otherwise use outboard cmp routine ? Perl ?
;;

;; nyi: doesn't work; get 1-second difference,
;; maybe because of clock skew between VOB and view ?
;;


(defun clearcase-file-appears-modified-since-checkout-p (file)
  "Return whether FILE appears to have been modified since checkout.
It doesn't examine the file contents."

  (cond
   ;; We consider various cases in order of increasing cost to compute.

   ;; Case 1: it's not even checked-out.
   ;;
   ((not (clearcase-fprop-checked-out file))
    nil)

   ;; Case 2: the mtime and the ctime are no longer the same.
   ;;
   ((not (equal (clearcase-utl-file-mtime file)
                (clearcase-utl-file-ctime file)))
    t)

   ;; Case 3: the size changed.
   ;;
   ((not (equal (clearcase-utl-file-size file)
                (clearcase-utl-file-size (clearcase-vxpath-cons-vxpath
                                          file (clearcase-fprop-predecessor-version file)))))
    t)

   ;; Case 4: the time of the checkout == the modification time of the file.
   ;;         (Unfortunately, non-equality doesn't necessarily mean the file
   ;;          was modified. It can sometimes be off by one second or so.)
   ;;
   ;; nyi: redundant case ?
   ;;
   ((string=
     (clearcase-fprop-date file)
     (clearcase-utl-emacs-date-to-clearcase-date
      (current-time-string (nth 5 (file-attributes file)))))
    nil)

   (t
    nil)))



;; nyi: store the date property in Emacs' format to minimise
;; format conversions ?
;;

;;}}}

;;{{{ Tests for view-residency

;;{{{ Tests for MVFS file residency

;; nyi: probably superseded by clearcase-file-would-be-in-view-p
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; nyi: this should get at least partially invalidated when
;;          VOBs are unmounted.

;; nyi: make this different for NT
;;
(defvar clearcase-always-mvfs-regexp (if (not clearcase-on-mswindows)
                                         "^/vobs/[^/]+/"

                                       ;; nyi: express this using drive variable
                                       ;;
                                       (concat "^"
                                               "[Mm]:"
                                               clearcase-pname-sep-regexp)))

;; This prevents the clearcase-file-vob-root function from pausing for long periods
;; stat-ing /net/host@@
;;
;; nyi: is there something equivalent on NT I need to avoid ?
;;

(defvar clearcase-never-mvfs-regexps (if clearcase-on-mswindows
                                         nil
                                       '(
                                         "^/net/[^/]+/"
                                         "^/tmp_mnt/net/[^/]+/"
                                         ))
  "Regexps matching those paths we can assume are never inside the MVFS.")

(defvar clearcase-known-vob-root-cache nil)

(defun clearcase-file-would-be-in-mvfs-p (filename)
  "Return whether FILE, after it is created, would reside in an MVFS filesystem."
  (let ((truename (file-truename filename)))
    (if (file-exists-p truename)
        (clearcase-file-is-in-mvfs-p truename)
      (let ((containing-dir (file-name-as-directory (file-name-directory truename))))
        (clearcase-file-is-in-mvfs-p containing-dir)))))

(defun clearcase-file-is-in-mvfs-p (filename)
  "Return whether existing FILE, resides in an MVFS filesystem."
  (let ((truename (file-truename filename)))

    (or
     ;; case 1: its prefix matches an "always VOB" prefix like /vobs/...
     ;;
     ;; nyi: problem here: we return true for "/vobs/nonexistent/"
     ;;
     (numberp (string-match clearcase-always-mvfs-regexp truename))

     ;; case 2: it has a prefix which is a known VOB-root
     ;;
     (clearcase-file-matches-vob-root truename clearcase-known-vob-root-cache)

     ;; case 3: it has an ancestor dir which is a newly met VOB-root
     ;;
     (clearcase-file-vob-root truename))))

(defun clearcase-wd-is-in-mvfs ()
  "Return whether the current directory resides in an MVFS filesystem."
  (clearcase-file-is-in-mvfs-p (file-truename ".")))

(defun clearcase-file-matches-vob-root (truename vob-root-list)
  "Return whether TRUENAME has a prefix in VOB-ROOT-LIST."
  (if (null vob-root-list)
      nil
    (or (numberp (string-match (regexp-quote (car vob-root-list))
                               truename))
        (clearcase-file-matches-vob-root truename (cdr vob-root-list)))))

(defun clearcase-file-vob-root (truename)
  "File the highest versioned directory in TRUENAME."

  ;; Use known non-MVFS patterns to rule some paths out.
  ;;
  (if (apply (function clearcase-utl-or-func)
             (mapcar (function (lambda (regexp)
                                 (string-match regexp truename)))
                     clearcase-never-mvfs-regexps))
      nil
    (let ((previous-dir nil)
          (dir  (file-name-as-directory (file-name-directory truename)))
          (highest-versioned-directory nil))

      (while (not (string-equal dir previous-dir))
        (if (clearcase-file-covers-element-p dir)
            (setq highest-versioned-directory dir))
        (setq previous-dir dir)
        (setq dir (file-name-directory (directory-file-name dir))))

      (if highest-versioned-directory
          (add-to-list 'clearcase-known-vob-root-cache highest-versioned-directory))

      highest-versioned-directory)))

;; Note: you should probably be using clearcase-fprop-mtype instead of this
;;       unless you really know what you're doing (nyi: check usages of this.)
;;
(defun clearcase-file-covers-element-p (path)
  "Determine quickly if PATH refers to a Clearcase element,
without caching the result."

  ;; nyi: Even faster: consult the fprop cache first ?

  (let ((element-dir (concat (clearcase-vxpath-element-part path) clearcase-vxpath-glue)))
    (and (file-exists-p path)
         (file-directory-p element-dir))))

;;}}}

;;{{{ Tests for snapshot view residency

;; nyi: probably superseded by clearcase-file-would-be-in-view-p
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defvar clearcase-known-snapshot-root-cache nil)

(defun clearcase-file-would-be-in-snapshot-p (filename)
  "Return whether FILE, after it is created, would reside in a snapshot view.
If so, return the viewtag."
  (let ((truename (file-truename filename)))
    (if (file-exists-p truename)
        (clearcase-file-is-in-snapshot-p truename)
      (let ((containing-dir (file-name-as-directory (file-name-directory truename))))
        (clearcase-file-is-in-snapshot-p containing-dir)))))

(defun clearcase-file-is-in-snapshot-p (truename)
  "Return whether existing FILE, resides in a snapshot view.
If so, return the viewtag."

  (or
   ;; case 1: it has a prefix which is a known snapshot-root
   ;;
   (clearcase-file-matches-snapshot-root truename clearcase-known-snapshot-root-cache)

   ;; case 2: it has an ancestor dir which is a newly met VOB-root
   ;;
   (clearcase-file-snapshot-root truename)))

(defun clearcase-wd-is-in-snapshot ()
  "Return whether the current directory resides in a snapshot view."
  (clearcase-file-is-in-snapshot-p (file-truename ".")))

(defun clearcase-file-matches-snapshot-root (truename snapshot-root-list)
  "Return whether TRUENAME has a prefix in SNAPSHOT-ROOT-LIST."
  (if (null snapshot-root-list)
      nil
    (or (numberp (string-match (regexp-quote (car snapshot-root-list))
                               truename))
        (clearcase-file-matches-snapshot-root truename (cdr snapshot-root-list)))))

;; This prevents the clearcase-file-snapshot-root function from pausing for long periods
;; stat-ing /net/host@@
;;
;; nyi: is there something equivalent on NT I need to avoid ?
;;

(defvar clearcase-never-snapshot-regexps (if clearcase-on-mswindows
                                             nil
                                           '(
                                             "^/net/[^/]+/"
                                             "^/tmp_mnt/net/[^/]+/"
                                             ))
  "Regexps matching those paths we can assume are never inside a snapshot view.")

(defun clearcase-file-snapshot-root (truename)
  "File the the snapshot view root containing TRUENAME."

  ;; Use known non-snapshot patterns to rule some paths out.
  ;;
  (if (apply (function clearcase-utl-or-func)
             (mapcar (function (lambda (regexp)
                                 (string-match regexp truename)))
                     clearcase-never-snapshot-regexps))
      nil
    (let ((previous-dir nil)
          (dir (file-name-as-directory (file-name-directory truename)))
          (viewtag nil)
          (viewroot nil))


      (while (and (not (string-equal dir previous-dir))
                  (null viewtag))

        ;; See if .view.dat exists and contains a valid view uuid
        ;;
        (let ((view-dat-name (concat dir (if clearcase-on-mswindows
					     "view.dat" ".view.dat"))))
          (if (file-readable-p view-dat-name)
              (let ((uuid (clearcase-viewdat-to-uuid view-dat-name)))
                (if uuid
                    (progn
                      (setq viewtag (clearcase-view-uuid-to-tag uuid))
                      (if viewtag
                          (setq viewroot dir)))))))

        (setq previous-dir dir)
        (setq dir (file-name-directory (directory-file-name dir))))

      (if viewroot
          (add-to-list 'clearcase-known-snapshot-root-cache viewroot))

      ;; nyi: update a viewtag==>viewroot map ?

      viewtag)))

(defun clearcase-viewdat-to-uuid (file)
  "Extract the view-uuid from a .view.dat file."
  ;; nyi
  )

(defun clearcase-view-uuid-to-tag (uuid)
  "Look up the view-uuid in the register to discover its tag."
  ;; nyi
  )

;;}}}

;; This is simple-minded but seems to work because cleartool+describe
;; groks snapshot views.
;;
;; nyi: Might be wise to cache view-roots to speed this up because the
;;      filename-handlers call this.
;;
;; nyi: Some possible shortcuts
;;      1. viewroot-relative path [syntax]
;;      2. under m:/ on NT        [syntax]
;;      3. setviewed on Unix      [find a containing VOB-root]
;;      4. subst-ed view on NT (calling net use seems very slow though)
;;                                [find a containing VOB-root]
;;      5. snapshot view
;;
(defun clearcase-file-would-be-in-view-p (filename)
  "Return whether FILE, after it is created, would reside in a ClearCase view."
  (let  ((truename (file-truename (expand-file-name filename))))

    ;; We use clearcase-path-file-really-exists-p here to make sure we are dealing
    ;; with a real file and not something faked by Emacs' file name handlers
    ;; like Ange-FTP.
    ;;
    (if (clearcase-path-file-really-exists-p truename)
        (clearcase-file-is-in-view-p truename)
      (let ((containing-dir (file-name-as-directory (file-name-directory truename))))
        (and (clearcase-path-file-really-exists-p containing-dir)
             (clearcase-file-is-in-view-p containing-dir))))))

(defun clearcase-file-is-in-view-p (filename)
  (let  ((truename (file-truename (expand-file-name filename))))
    ;; Shortcut if the file is a version-extended path.
    ;;
    (or (clearcase-vxpath-p truename)
        (clearcase-fprop-mtype truename))))

(defun clearcase-file-viewtag (filename)
  "Find the viewtag associated with existing FILENAME."

  (clearcase-when-debugging
   (assert (file-exists-p filename)))

  (let ((truename (file-truename (expand-file-name filename))))
    (cond

     ;; Case 1: viewroot-relative path
     ;;         ==> syntax
     ;;
     ((clearcase-vrpath-p truename)
      (clearcase-vrpath-viewtag truename))

     ;; Case 2: under m:/ on NT
     ;;         ==> syntax
     ;;
     ((and clearcase-on-mswindows
           (string-match (concat clearcase-viewroot-drive
                                 clearcase-pname-sep-regexp
                                 "\\("
                                 clearcase-non-pname-sep-regexp "*"
                                 "\\)"
                                 )
                         truename))
      (substring truename (match-beginning 1) (match-end 1)))

     ;; Case 3: setviewed on Unix
     ;;         ==> read EV, but need to check it's beneath a VOB-root
     ;;
     ((and clearcase-setview-viewtag
           (clearcase-file-would-be-in-mvfs-p truename))
      clearcase-setview-viewtag)

     ;; Case 4: subst-ed view on NT
     ;;         ==> use ct+pwv -wdview
     ;; Case 5: snapshot view
     ;;         ==> use ct+pwv -wdview
     (t
      (clearcase-file-wdview truename)))))

(defun clearcase-file-wdview (truename)
  "Return the working-directory view associated with TRUENAME,
or nil if none"
  (let ((default-directory (if (file-directory-p truename)
                               truename
                             (file-name-directory truename))))
    (clearcase-ct-cd default-directory)
    (let ((ret (clearcase-ct-blocking-call "pwv" "-wdview" "-short")))
      (if (not (string-match " NONE " ret))
          (clearcase-utl-1st-line-of-string ret)))))

;;}}}

;;{{{ The cleartool sub-process

;; We use pipes rather than pty's for two reasons:
;;
;;   1. NT only has pipes
;;   2. On Solaris there appeared to be a problem in the pty handling part
;;      of Emacs, which resulted in Emacs/tq seeing too many cleartool prompt
;;      strings. This would occasionally occur and prevent the tq-managed
;;      interactions with the cleartool sub-process from working correctly.
;;
;; Now we use pipes. Cleartool detects the "non-tty" nature of the output
;; device and doesn't send a prompt. We manufacture an end-of-transaction
;; marker by sending a "pwd -h" after each cleartool sub-command and then use
;; the expected output of "Usage: pwd\n" as our end-of-txn pattern for tq.
;;
;; Even using pipes, the semi-permanent outboard-process using tq doesn't work
;; well on NT. There appear to be bugs in accept-process-output such that:
;;   0. there apparently were hairy race conditions, which a sprinkling
;;      of (accept-process-output nil 1) seemed to avoid somewhat.
;;   1. it never seems to timeout if you name a process as arg1.
;;   2. it always seems to wait for TIMEOUT, even if there is output ready.
;; The result seemed to be less responsive tha just calling a fresh cleartool
;; process for each invocation of clearcase-ct-blocking-call
;;
;; It still seems worthwhile to make it work on NT, as clearcase-ct-blocking-call
;; typically takes about 0.5 secs on NT versus 0.05 sec on Solaris,
;; an order of magnitude difference.
;;

(defconst clearcase-ct-eotxn-cmd "pwd -h\n")
(defconst clearcase-ct-eotxn-response "Usage: pwd\n")
(defconst clearcase-ct-eotxn-response-length (length clearcase-ct-eotxn-response))

(defconst clearcase-ct-subproc-timeout 30
  "Timeout on calls to subprocess")

(defvar clearcase-ct-tq nil
  "Transaction queue to talk to ClearTool in a subprocess")

(defvar clearcase-ct-return nil
  "Return value when we're involved in a blocking call")

(defvar clearcase-ct-view ""
  "Current view of cleartool subprocess, or the empty string if none")

(defvar clearcase-ct-wdir ""
  "Current working directory of cleartool subprocess,
or the empty string if none")

(defvar clearcase-ct-running nil)

(defun clearcase-ct-accept-process-output (proc timeout)
  (accept-process-output proc timeout))

(defun clearcase-ct-start-cleartool ()
  (clearcase-trace "clearcase-ct-start-cleartool()")
  (let ((process-environment (append '("ATRIA_NO_BOLD=1"
                                       "ATRIA_FORCE_GUI=1")
                                     ;;; emacs is a GUI, right? :-)
                                     process-environment)))
    (clearcase-trace (format "Starting cleartool in %s" default-directory))
    (let* (;; Force the use of a pipe
           ;;
           (process-connection-type nil)
           (cleartool-process
            (start-process "cleartool" ;; Absolute path won't work here
                           "*cleartool*"
                           clearcase-cleartool-path)))
      (process-kill-without-query cleartool-process)
      (setq clearcase-ct-view "")
      (setq clearcase-ct-tq (tq-create cleartool-process))
      (tq-enqueue clearcase-ct-tq
                  clearcase-ct-eotxn-cmd;; question
                  clearcase-ct-eotxn-response;; regexp
                  'clearcase-ct-running;; closure
                  'set);; function
      (while (not clearcase-ct-running)
        (message "waiting for cleartool to start...")
        (clearcase-ct-accept-process-output (tq-process clearcase-ct-tq)
                                            clearcase-ct-subproc-timeout))
      (clearcase-trace "clearcase-ct-start-cleartool() done")
      (message "waiting for cleartool to start...done"))))

(defun clearcase-ct-kill-cleartool ()
  "Kill off cleartool subprocess.  If another one is needed,
it will be restarted.  This may be useful if you're debugging clearcase."
  (interactive)
  (clearcase-ct-kill-tq))

(defun clearcase-ct-callback (arg val)
  (clearcase-trace (format "clearcase-ct-callback:<\n"))
  (clearcase-trace val)
  (clearcase-trace (format "clearcase-ct-callback:>\n"))
  ;; This can only get called when the last thing received from
  ;; the cleartool sub-process was clearcase-ct-eotxn-response,
  ;; so it is safe to just remove it here.
  ;;
  (setq clearcase-ct-return (substring val 0 (- clearcase-ct-eotxn-response-length))))

(defun clearcase-ct-do-cleartool-command (command file comment &rest flags)
  "Execute a cleartool command, notifying user and checking for
errors. Output from COMMAND goes to buffer *clearcase*.  The last argument of the
command is the name of FILE; this is appended to an optional list of
FLAGS."
  (if file
      (setq file (expand-file-name file)))
  (if (listp command)
      ;;      (progn
      ;;      (setq flags (append (cdr command) flags))
      ;;      (setq command (car command)))
      (error "command must not be a list"))
  (if clearcase-command-messages
      (if file
          (message "Running %s on %s..." command file)
        (message "Running %s..." command)))
  (let ((camefrom (current-buffer))
        (squeezed nil)
        status)
    (set-buffer (get-buffer-create "*clearcase*"))
    (setq buffer-read-only nil)
    (erase-buffer)
    (set (make-local-variable 'clearcase-parent-buffer) camefrom)
    (set (make-local-variable 'clearcase-parent-buffer-name)
         (concat " from " (buffer-name camefrom)))

    ;; This is so that command arguments typed in the *clearcase* buffer will
    ;; have reasonable defaults.
    ;;
    (if file
        (setq default-directory (file-name-directory file)))

    (mapcar
     (function (lambda (s)
                 (and s
                      (setq squeezed
                            (append squeezed (list s))))))
     flags)

    (clearcase-with-tempfile
     comment-file
     (progn
       (if (not (eq comment 'unused))
           (if comment
               (progn
                 (write-region comment nil comment-file nil 'noprint)
                 (setq squeezed (append squeezed (list "-cfile" (clearcase-path-native comment-file)))))
             (setq squeezed (append squeezed (list "-nc")))))
       (if file
           (setq squeezed (append squeezed (list (clearcase-path-native file)))))
       (let ((default-directory (file-name-directory
                                 (or file default-directory))))
         (clearcase-ct-cd default-directory)
         (if clearcase-command-messages
             (message "Running %s..." command))
         (insert
          (apply 'clearcase-ct-cleartool-cmd (append (list command) squeezed)))
         (if clearcase-command-messages
             (message "Running %s...done" command)))))
    
    (goto-char (point-min))
    (clearcase-view-mode 0 camefrom)
    (set-buffer-modified-p nil)         ; XEmacs - fsf uses `not-modified'
    (if (re-search-forward "^cleartool: Error:.*$" nil t)
        (progn
          (setq status (buffer-substring (match-beginning 0) (match-end 0)))
          (clearcase-port-view-buffer-other-window "*clearcase*")
          (shrink-window-if-larger-than-buffer)
          (error "Running %s...FAILED (%s)" command status))
      (if clearcase-command-messages
          (message "Running %s...OK" command)))
    (set-buffer camefrom)
    status))

(defun clearcase-ct-cd (dir)
  (if (or (not dir)
          (string= dir clearcase-ct-wdir))
      clearcase-ct-wdir
    (let ((ret (clearcase-ct-blocking-call "cd" (clearcase-path-native dir))))
      (setq clearcase-ct-wdir dir))))

(defun clearcase-ct-cleartool-cmd (&rest cmd)
  (apply 'clearcase-ct-blocking-call cmd))

;; NT Emacs - needs a replacement for tq.
;;
(defun clearcase-ct-get-command-stdout (program &rest args)
  "Call PROGRAM.
Returns PROGRAM's stdout.
ARGS is the command line arguments to PROGRAM."
  (let ((buf (generate-new-buffer "cleartoolexecution")))
    (prog1
        (save-excursion
          (set-buffer buf)
	  (apply 'call-process program nil buf nil args)
          (buffer-string))
      (kill-buffer buf))))

;; The TQ interaction still doesn't work on NT.
;;
(defvar clearcase-disable-tq clearcase-on-mswindows
  "Set to T if the Emacs/cleartool interactions via tq are not working right.")

(defun clearcase-ct-blocking-call (&rest cmd)
  (clearcase-trace (format "clearcase-ct-blocking-call(%s)" cmd))
  (save-excursion
    (setq clearcase-ct-return nil)

    (if clearcase-disable-tq
        ;; Don't use tq:
        ;;
        (setq clearcase-ct-return (apply 'clearcase-ct-get-command-stdout
                                         clearcase-cleartool-path cmd))
      
      ;; Use tq:
      ;;
      (setq clearcase-ct-return nil)
      (if (not clearcase-ct-tq)
          (clearcase-ct-start-cleartool))
      (unwind-protect
          (let ((command ""))
	    (mapcar
	     (function
              (lambda (token)
                ;; If the token has imbedded spaces and is not already quoted,
                ;; add double quotes.
                ;;
                (setq command (concat command
                                      " "
                                      (clearcase-utl-quote-if-nec token)))))
	     cmd)
            (tq-enqueue clearcase-ct-tq
                        (concat command "\n"
                                clearcase-ct-eotxn-cmd);; question
                        clearcase-ct-eotxn-response;; regexp
                        nil;; closure
                        'clearcase-ct-callback);; function
            (while (not clearcase-ct-return)
              (clearcase-ct-accept-process-output (tq-process clearcase-ct-tq)
                                                  clearcase-ct-subproc-timeout)))
        ;; Error signalled:
        ;;
        (while (tq-queue clearcase-ct-tq)
          (tq-queue-pop clearcase-ct-tq)))))
  (if (string-match "cleartool: Error:" clearcase-ct-return)
      (error "cleartool process error %s: "
             (substring clearcase-ct-return (match-end 0))))
  (clearcase-trace (format "command-result(%s)" clearcase-ct-return))
  clearcase-ct-return)

(defun clearcase-ct-kill-tq ()
  (process-send-eof (tq-process clearcase-ct-tq))
  (kill-process (tq-process clearcase-ct-tq))
  (setq clearcase-ct-running nil)
  (setq clearcase-ct-tq nil))

(defun clearcase-ct-kill-buffer-hook ()

  ;; NT Emacs - doesn't use tq.
  ;;
  (if (not clearcase-on-mswindows)
      (let ((kill-buffer-hook nil))
        (if (and (boundp 'clearcase-ct-tq)
                 clearcase-ct-tq
                 (eq (current-buffer) (tq-buffer clearcase-ct-tq)))
            (error "Don't kill TQ buffer %s, use `clearcase-ct-kill-tq'" (current-buffer))))))

(add-hook 'kill-buffer-hook 'clearcase-ct-kill-buffer-hook)

;;}}}

;;{{{ Invoking a command

;; nyi Probably redundant.

(defun clearcase-do-command (okstatus command file &rest flags)
  "Execute a version-control command, notifying user and checking for errors.
The command is successful if its exit status does not exceed OKSTATUS.
Output from COMMAND goes to buffer *clearcase*.  The last argument of the command is
an optional list of FLAGS."
  (setq file (expand-file-name file))
  (if clearcase-command-messages
      (message "Running %s on %s..." command file))
  (let ((camefrom (current-buffer))
        (pwd )
        (squeezed nil)
        status)
    (set-buffer (get-buffer-create "*clearcase*"))
    (setq buffer-read-only nil)
    (erase-buffer)
    (set (make-local-variable 'clearcase-parent-buffer) camefrom)
    (set (make-local-variable 'clearcase-parent-buffer-name)
         (concat " from " (buffer-name camefrom)))
    ;; This is so that command arguments typed in the *clearcase* buffer will
    ;; have reasonable defaults.
    ;;
    (setq default-directory (file-name-directory file)
          file (file-name-nondirectory file))

    (mapcar
     (function (lambda (s)
                 (and s
                      (setq squeezed
                            (append squeezed (list s))))))
     flags)
    (setq squeezed (append squeezed (list file)))
    (setq status (apply 'call-process command nil t nil squeezed))
    (goto-char (point-min))
    (clearcase-view-mode 0 camefrom)
    (set-buffer-modified-p nil)         ; XEmacs - fsf uses `not-modified'
    (if (or (not (integerp status)) (< okstatus status))
        (progn
          (clearcase-port-view-buffer-other-window "*clearcase*")
          (shrink-window-if-larger-than-buffer)
          (error "Running %s...FAILED (%s)" command
                 (if (integerp status)
                     (format "status %d" status)
                   status)))
      (if clearcase-command-messages
          (message "Running %s...OK" command)))
    (set-buffer camefrom)
    status))

;;}}}

;;{{{ Viewtag management

;;{{{ Started views

(defun clearcase-viewtag-try-to-start-view (viewtag)
  "If VIEW is not apparently already visible under viewroot, start it."
  (if (not (member viewtag (clearcase-viewtag-started-viewtags)))
      (clearcase-viewtag-start-view viewtag)))

(defun clearcase-viewtag-started-viewtags-alist ()
  "Return an alist of views that are currently visible under the viewroot."
  (mapcar
   (function
    (lambda (tag)
      (list (concat tag "/"))))
   (clearcase-viewtag-started-viewtags)))

(defun clearcase-viewtag-started-viewtags ()
  "Return the list of viewtags already visible under the viewroot."
  (let ((raw-list  (if clearcase-on-mswindows
                       (directory-files clearcase-viewroot-drive)
                     (directory-files clearcase-viewroot))))
    (clearcase-utl-list-filter
     (function (lambda (string)
                 ;; Exclude the ones that start with ".",
                 ;; and the ones that end with "@@".
                 ;;
                 (and (not (equal ?. (aref string 0)))
                      (not (string-match "@@$" string)))))
     raw-list)))

;; nyi: Makes sense on NT ?
;;      Probably also want to run subst ?
;;      Need a better high-level interface to start-view
;;
(defun clearcase-viewtag-start-view (viewtag)
  "If VIEWTAG is in our cache of valid view names, start it."
  (if (clearcase-viewtag-exists viewtag)
      (progn
        (message "Starting view server for %s..." viewtag)
        (let ((ret (clearcase-ct-blocking-call "startview" viewtag)))
          (message "Starting view server for %s...done" viewtag)))))

;;}}}

;;{{{ All views

;;{{{ Internals

(defvar clearcase-viewtag-cache nil
  "Oblist of all known viewtags.")

(defvar clearcase-viewtag-dir-cache nil
  "Oblist of all known viewtag dirs.")

(defvar clearcase-viewtag-cache-timeout 1800
  "*Default timeout of all-viewtag cache, in seconds.")

(defun clearcase-viewtag-schedule-cache-invalidation ()
  "Schedule the next invalidation of clearcase-viewtag-cache."
  (run-at-time (format "%s sec" clearcase-viewtag-cache-timeout)
               nil
               (function (lambda (&rest ignore)
                           (setq clearcase-viewtag-cache nil)))
               nil))
;; Some primes:
;;
;;     1,
;;     2,
;;     3,
;;     7,
;;     17,
;;     31,
;;     61,
;;     127,
;;     257,
;;     509,
;;     1021,
;;     2053,

(defun clearcase-viewtag-read-all-viewtags ()
  "Invoke ct+lsview to get all viewtags, and return an obarry containing them."
  (message "Fetching view names...")
  (let* ((default-directory "/")
         (result (make-vector 1021 0))
         (raw-views-string (clearcase-ct-blocking-call "lsview" "-short"))
         (view-list (clearcase-utl-split-string-at-char raw-views-string ?\n)))
    (message "Fetching view names...done")
    (mapcar (function (lambda (string)
                        (set (intern string result) t)))
            view-list)
    result))

(defun clearcase-viewtag-populate-caches ()
  (setq clearcase-viewtag-cache (clearcase-viewtag-read-all-viewtags))
  (let ((dir-cache (make-vector 1021 0)))
    (mapatoms
     (function (lambda (sym)
                 (set (intern (concat (symbol-name sym) "/") dir-cache) t)))
     clearcase-viewtag-cache)
    (setq clearcase-viewtag-dir-cache dir-cache))
  (clearcase-viewtag-schedule-cache-invalidation))

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

;;}}}

;; Exported interfaces

;; This is for completion of viewtags.
;;
(defun clearcase-viewtag-all-viewtags-obarray ()
  "Return an obarray of all valid viewtags as of the last time we looke  d."
  (if (null clearcase-viewtag-cache)
      (clearcase-viewtag-populate-caches))
  clearcase-viewtag-cache)

;; This is for completion of viewtag dirs, like /view/my_view_name/
;; The trailing slash is required for compatibility with other instances
;; of filename completion in Emacs.
;;
(defun clearcase-viewtag-all-viewtag-dirs-obarray ()
  "Return an obarray of all valid viewtag directory names as of the last time we looked."
  (if (null clearcase-viewtag-dir-cache)
      (clearcase-viewtag-populate-caches))
  clearcase-viewtag-dir-cache)

(defun clearcase-viewtag-exists (viewtag)
  (symbol-value (intern-soft viewtag (clearcase-viewtag-all-viewtags-obarray))))

;;}}}

;;}}}

;;{{{ Pathnames

;;{{{ Pathnames: version-extended

(defun clearcase-vxpath-p (path)
  (or (string-match (concat clearcase-vxpath-glue "/") path)
      (string-match (concat clearcase-vxpath-glue "\\\\") path)))

(defun clearcase-vxpath-element-part (vxpath)
  "Return the element part of version-extended PATH."
  (if (string-match clearcase-vxpath-glue vxpath)
      (substring vxpath 0 (match-beginning 0))
    vxpath))

(defun clearcase-vxpath-version-part (vxpath)
  "Return the version part of version-extended PATH."
  (if (string-match clearcase-vxpath-glue vxpath)
      (substring vxpath (match-end 0))
    nil))

(defun clearcase-vxpath-branch (vxpath)
  "Return the branch part of a version-extended path or of a version"
  (if (clearcase-vxpath-p vxpath)
      (clearcase-vxpath-cons-vxpath
       (clearcase-vxpath-element-part vxpath)
       (file-name-directory (clearcase-vxpath-version-part vxpath)))
    (file-name-directory vxpath)))

(defun clearcase-vxpath-version (vxpath)
  "Return the numeric version part of a version-extended path or of a version"
  (if (clearcase-vxpath-p vxpath)
       (file-name-nondirectory (clearcase-vxpath-version-part vxpath))
    (file-name-nondirectory vxpath)))

(defun clearcase-vxpath-cons-vxpath (file version &optional viewtag)
  "Make a ClearCase version-extended pathname for ELEMENT's version VERSION.
If ELEMENT is actually a version-extended pathname, substitute VERSION for
the version included in ELEMENT.  If VERSION is nil, remove the version-extended
pathname.

If optional VIEWTAG is specified, make a view-relative pathname, possibly
replacing the existing view prefix."
  (let* ((element (clearcase-vxpath-element-part file))
         (glue-fmt (if (and (> (length version) 0)
                            (= (aref version 0) ?/))
                       (concat "%s" clearcase-vxpath-glue "%s")
                     (concat "%s" clearcase-vxpath-glue "/%s")))
         (relpath (clearcase-vrpath-tail element)))
    (if viewtag
        (setq element (concat clearcase-viewroot "/" viewtag (or relpath element))))
    (if version
        (format glue-fmt element version)
      element)))

;; NYI: This should cache the predecessor version as a property
;; of the file.
;;
(defun clearcase-vxpath-of-predecessor (file)
  "Compute the version-extended pathname of the predecessor version of FILE."
  (if (not (equal 'version (clearcase-fprop-mtype file)))
      (error "Not a clearcase version: %s" file))
  (let ((abs-file (expand-file-name file)))
    (let ((ver (clearcase-utl-1st-line-of-string
                (clearcase-ct-cleartool-cmd "describe"
                                            "-pred"
                                            "-short"
                                            (clearcase-path-native abs-file)))))
      (clearcase-path-canonicalise-slashes (concat
                                            (clearcase-vxpath-element-part file)
                                            clearcase-vxpath-glue
                                            ver)))))

(defun clearcase-vxpath-version-extend (file)
  "Compute the version-extended pathname of FILE."
  (if (not (equal 'version (clearcase-fprop-mtype file)))
      (error "Not a clearcase version: %s" file))
  (let ((abs-file (expand-file-name file)))
    (clearcase-path-canonicalise-slashes
     (clearcase-utl-1st-line-of-string
      (clearcase-ct-cleartool-cmd "describe"
                                  "-fmt"
				  (concat "%En"
					  clearcase-vxpath-glue
					  "%Vn")
                                  (clearcase-path-native abs-file))))))

(defun clearcase-vxpath-of-branch-base (file)
  "Compute the version-extended pathname of the version at the branch base of FILE."
  (let* ((file-version-path 
          (if  (clearcase-fprop-checked-out file)
              ;; If the file is checked-out, start with its predecessor version...
              ;;
              (clearcase-vxpath-version-extend (clearcase-vxpath-of-predecessor file))
            ;; ...otherwise start with the file's version.
            ;;
            (clearcase-vxpath-version-extend file)))
         (file-version-number (string-to-int (clearcase-vxpath-version file-version-path)))
         (branch (clearcase-vxpath-branch file-version-path)))
    (let* ((base-number 0)
           (base-version-path (format "%s%d" branch base-number)))
      (while (and (not (clearcase-file-is-in-snapshot-p base-version-path))
		  (not (file-exists-p base-version-path))
                  (< base-number file-version-number))
        (setq base-number (1+ base-number))
        (setq base-version-path (format "%s%d" branch base-number)))
      base-version-path)))

(defun clearcase-vxpath-version-of-branch-base (file)
  (clearcase-vxpath-version-part (clearcase-vxpath-of-branch-base file)))

(defun clearcase-vxpath-get-version-in-buffer (vxpath)
  "Return a buffer containing the version named by VXPATH.
Intended for use in snapshot views."
  (let* ((temp-file (clearcase-vxpath-get-version-in-temp-file vxpath))
         (buffer (find-file-noselect temp-file t)))
    ;; native Windows XEmacs change:  file cannot be removed if read-only.
    (if (not (file-writable-p temp-file))
        (set-file-modes temp-file (+ (lsh 6 6) (lsh 6 3) (lsh 6 0))))
    (delete-file temp-file)
    buffer))

(defun clearcase-vxpath-get-version-in-temp-file (vxpath)
  "Return the name of a temporary file containing the version named by VXPATH.
Intended for use in snapshot views."

  (let ((temp-file (clearcase-utl-tempfile-name vxpath)))
    (progn
      (clearcase-ct-blocking-call "get"
                                  "-to"
                                  (clearcase-path-native temp-file)
                                  (clearcase-path-native vxpath))
      temp-file)))

;;}}}

;;{{{ Pathnames: viewroot-relative

;; nyi: make all this work with viewroot-drive-relative files too

(defun clearcase-vrpath-p (path)
  "Return whether PATH is viewroot-relative."
  (string-match clearcase-vrpath-regexp path))

(defun clearcase-vrpath-head (vrpath)
  "Given viewroot-relative PATH, return the prefix including the view-tag."
  (if (string-match clearcase-vrpath-regexp vrpath)
      (substring vrpath (match-end 0))))

(defun clearcase-vrpath-tail (vrpath)
  "Given viewroot-relative PATH, return the suffix after the view-tag."
  (if (string-match clearcase-vrpath-regexp vrpath)
      (substring vrpath (match-end 0))))

(defun clearcase-vrpath-viewtag (vrpath)
  "Given viewroot-relative PATH, return the view-tag."
  (if (string-match clearcase-vrpath-regexp vrpath)
      (substring vrpath (match-beginning 1) (match-end 1))))

;; Remove useless viewtags from a pathname.
;; e.g. if we're setviewed to view "VIEWTAG"
;;    (clearcase-path-remove-useless-viewtags "/view/VIEWTAG/PATH")
;;     ==> "PATH"
;;    (clearcase-path-remove-useless-viewtags "/view/z/view/y/PATH")
;;     ==> /view/y/"PATH"
;;
(defvar clearcase-multiple-viewroot-regexp
  (concat "^"
          clearcase-viewroot
          clearcase-pname-sep-regexp
          clearcase-non-pname-sep-regexp "+"
          "\\("
          clearcase-viewroot
          clearcase-pname-sep-regexp
          "\\)"
          ))

(defun clearcase-path-remove-useless-viewtags (pathname)
  ;; Try to avoid file-name-handler recursion here:
  ;;
  (let ((setview-root clearcase-setview-root))
    (if setview-root
        ;; Append "/":
        ;;
        (setq setview-root (concat setview-root "/")))

    (cond

     ((string-match clearcase-multiple-viewroot-regexp pathname)
      (clearcase-path-remove-useless-viewtags (substring pathname (match-beginning 1))))

     ((and setview-root
           (string= setview-root "/"))
      pathname)

     ;; If pathname has setview-root as a proper prefix,
     ;; strip it off and recurse:
     ;;
     ((and setview-root
           (< (length setview-root) (length pathname))
           (string= setview-root (substring pathname 0 (length setview-root))))
      (clearcase-path-remove-useless-viewtags (substring pathname (- (length setview-root) 1))))

     (t
      pathname))))

;;}}}

;; Don't pass the "INPLACE" parameter to subst-char-in-string here since the
;; parameter is not necessarily a local variable (in some cases it is
;; buffer-file-name and replacing / with \ in it wreaks havoc).
;;
(defun clearcase-path-canonicalise-slashes (path)
  (if (not clearcase-on-mswindows)
      path
    (subst-char-in-string ?\\ ?/ path)))

(defun clearcase-path-canonical (path)
  (if (not clearcase-on-mswindows)
      path
    (if clearcase-on-cygwin32
	(substring (shell-command-to-string (concat "cygpath -u -p '" path "'")) 0 -1)
      (subst-char-in-string ?\\ ?/ path))))

(defun clearcase-path-native (path)
  (if (not clearcase-on-mswindows)
      path
    (if clearcase-on-cygwin32
	(substring (shell-command-to-string (concat "cygpath -w -p " path)) 0 -1)
      (subst-char-in-string ?/ ?\\ path))))

(defun clearcase-path-file-really-exists-p (filename)
  "Test if a file really exists, when all file-name handlers are disabled."
  (let ((inhibit-file-name-operation 'file-exists-p)
        (inhibit-file-name-handlers (mapcar
                                     (lambda (pair)
                                       (cdr pair))
                                     file-name-handler-alist)))
    (file-exists-p filename)))

;;}}}

;;{{{ Mode-line

(defun clearcase-mode-line-buffer-id (filename)
  "Compute an abbreviated version string for the mode-line.
It will be in one of three forms: /main/NNN, or .../branchname/NNN, or DO-NAME"

  (if (clearcase-fprop-checked-out filename)
      (if (clearcase-fprop-reserved filename)
          "RESERVED"
        "UNRESERVED")
    (let ((ver-string (clearcase-fprop-version filename)))
      (if (not (zerop (length ver-string)))
          (let ((i (length ver-string))
                (slash-count 0))
            ;; Search back from the end to the second-last slash
            ;;
            (while (and (> i 0)
                        (< slash-count  2))
              (if (equal ?/ (aref ver-string (1- i)))
                  (setq slash-count (1+ slash-count)))
              (setq i (1- i)))
            (if (> i 0)
                (concat "..." (substring ver-string i))
              (substring ver-string i)))))))

;;}}}

;;{{{ Minibuffer reading

;;{{{ clearcase-read-version-name

(defun clearcase-read-version-name (prompt file)
  "Display PROMPT and read a version string for FILE in the minibuffer,
with completion if possible."
  (let* ((insert-default-directory nil)
         (predecessor (clearcase-fprop-predecessor-version file))
         (default-filename (clearcase-vxpath-cons-vxpath file predecessor))

         ;; To get this to work it is necessary to make Emacs think
         ;; we're completing with respect to "ELEMENT@@/" rather
         ;; than "ELEMENT@@". Otherwise when we enter a version
         ;; like "/main/NN", it thinks we entered an absolute path.
         ;; So instead, we prompt the user to enter "main/..../NN"
         ;; and add back the leading slash before returning.
         ;;
         (completing-dir (concat file "@@/")))
    (if (and (clearcase-file-is-in-mvfs-p file) (not clearcase-on-mswindows))
        ;; Completion only works in MVFS:
        ;;
        (concat "/" (read-file-name prompt
                                    completing-dir
                                    (substring predecessor 1)
                                    ;;nil
                                    t
                                    (substring predecessor 1)))
      (concat "/" (read-string prompt
                               (substring predecessor 1)
                               nil)))))
;;}}}

;;{{{ clearcase-read-label-name

;; nyi: unused

(defun clearcase-read-label-name (prompt)
  "Read a label name."

  (let* ((string (clearcase-ct-cleartool-cmd "lstype"
                                             "-kind"
                                             "lbtype"
                                             "-short"))
         labels)
    (mapcar (function (lambda (arg)
                        (if (string-match "(locked)" arg)
                            nil
                          (setq labels (cons (list arg) labels)))))
            (clearcase-utl-split-string string "\n"))
    (completing-read prompt labels nil t)))

;;}}}

;;}}}

;;{{{ Directory-tree walking

(defun clearcase-dir-all-files (func &rest args)
  "Invoke FUNC f ARGS on each regular file f in default directory."
  (let ((dir default-directory))
    (message "Scanning directory %s..." dir)
    (mapcar (function (lambda (f)
                        (let ((dirf (expand-file-name f dir)))
                          (apply func dirf args))))
            (directory-files dir))
    (message "Scanning directory %s...done" dir)))

(defun clearcase-file-tree-walk-internal (file func args quiet)
  (if (not (file-directory-p file))
      (apply func file args)
    (or quiet
        (message "Traversing directory %s..." file))
    (let ((dir (file-name-as-directory file)))
      (mapcar
       (function
        (lambda (f) (or
                     (string-equal f ".")
                     (string-equal f "..")
                     (member f clearcase-directory-exclusion-list)
                     (let ((dirf (concat dir f)))
                       (or
                        (file-symlink-p dirf);; Avoid possible loops
                        (clearcase-file-tree-walk-internal dirf func args quiet))))))
       (directory-files dir)))))
;;
(defun clearcase-file-tree-walk (func &rest args)
  "Walk recursively through default directory.
Invoke FUNC f ARGS on each non-directory file f underneath it."
  (clearcase-file-tree-walk-internal default-directory func args nil)
  (message "Traversing directory %s...done" default-directory))

(defun clearcase-subdir-tree-walk (func &rest args)
  "Walk recursively through default directory.
Invoke FUNC f ARGS on each subdirectory underneath it."
  (clearcase-subdir-tree-walk-internal default-directory func args nil)
  (message "Traversing directory %s...done" default-directory))

(defun clearcase-subdir-tree-walk-internal (file func args quiet)
  (if (file-directory-p file)
      (let ((dir (file-name-as-directory file)))
        (apply func dir args)
        (or quiet
            (message "Traversing directory %s..." file))
        (mapcar
         (function
          (lambda (f) (or
                       (string-equal f ".")
                       (string-equal f "..")
                       (member f clearcase-directory-exclusion-list)
                       (let ((dirf (concat dir f)))
                         (or
                          (file-symlink-p dirf);; Avoid possible loops
                          (clearcase-subdir-tree-walk-internal dirf
                                                               func
                                                               args
                                                               quiet))))))
         (directory-files dir)))))

;;}}}

;;{{{ Buffer context

;; nyi: it would be nice if we could restore fold context too, for folded files.

;; Save a bit of the text around POSN in the current buffer, to help
;; us find the corresponding position again later.  This works even
;; if all markers are destroyed or corrupted.
;;
(defun clearcase-position-context (posn)
  (list posn
        (buffer-size)
        (buffer-substring posn
                          (min (point-max) (+ posn 100)))))

;; Return the position of CONTEXT in the current buffer, or nil if we
;; couldn't find it.
;;
(defun clearcase-find-position-by-context (context)
  (let ((context-string (nth 2 context)))
    (if (equal "" context-string)
        (point-max)
      (save-excursion
        (let ((diff (- (nth 1 context) (buffer-size))))
          (if (< diff 0) (setq diff (- diff)))
          (goto-char (nth 0 context))
          (if (or (search-forward context-string nil t)
                  ;; Can't use search-backward since the match may continue
                  ;; after point.
                  ;;
                  (progn (goto-char (- (point) diff (length context-string)))
                         ;; goto-char doesn't signal an error at
                         ;; beginning of buffer like backward-char would.
                         ;;
                         (search-forward context-string nil t)))
              ;; to beginning of OSTRING
              ;;
              (- (point) (length context-string))))))))

;;}}}

;;{{{ Synchronizing buffers with disk

(defun clearcase-sync-from-disk (file &optional no-confirm)

  (clearcase-fprop-unstore-properties file)
  ;; If the given file is in any buffer, revert it.
  ;;
  (let ((buffer (find-buffer-visiting file)))
    (if buffer
        (save-excursion
          (set-buffer buffer)
          (clearcase-buffer-revert no-confirm)
          (clearcase-fprop-get-properties file)

          ;; Make sure the mode-line gets updated.
          ;;
          (setq clearcase-mode
                (concat " ClearCase:"
                        (clearcase-mode-line-buffer-id file)))
          (force-mode-line-update))))

  ;; Update any Dired Mode buffers that list this file.
  ;;
  (dired-relist-file file)

  ;; If the file was a directory, update any dired-buffer for
  ;; that directory.
  ;;
  (mapcar (function (lambda (buffer)
                      (save-excursion
                        (set-buffer buffer)
                        (revert-buffer))))
          (dired-buffers-for-dir file)))

(defun clearcase-sync-to-disk (&optional not-urgent)

  ;; Make sure the current buffer and its working file are in sync
  ;; NOT-URGENT means it is ok to continue if the user says not to save.
  ;;
  (if (buffer-modified-p)
      (if (or clearcase-suppress-confirm
              (y-or-n-p (format "Buffer %s modified; save it? "
                                (buffer-name))))
          (save-buffer)
        (if not-urgent
            nil
          (error "Aborted")))))


(defun clearcase-buffer-revert (&optional no-confirm)
  ;; Should never call for Dired buffers
  ;;
  (assert (not (eq major-mode 'dired-mode)))
  
  ;; Revert buffer, try to keep point and mark where user expects them in spite
  ;; of changes because of expanded version-control key words.  This is quite
  ;; important since otherwise typeahead won't work as expected.
  ;;
  (widen)
  (let ((point-context (clearcase-position-context (point)))

        ;; Use clearcase-utl-mark-marker to avoid confusion in transient-mark-mode.
        ;; XEmacs - mark-marker t, FSF Emacs - mark-marker.
        ;;
        (mark-context (if (eq (marker-buffer (clearcase-utl-mark-marker))
                              (current-buffer))
                          (clearcase-position-context (clearcase-utl-mark-marker))))
        (camefrom (current-buffer)))

    ;; nyi: Should we run font-lock ?
    ;; Want to avoid re-doing a buffer that is already correct, such as on
    ;; check-in/check-out.
    ;; For now do-nothing.

    ;; The actual revisit.
    ;; For some reason, revert-buffer doesn't recompute whether View Minor Mode
    ;; should be on, so turn it off and then turn it on if necessary.
    ;;
    ;; nyi: Perhaps we should re-find-file ?
    ;;
    (or clearcase-xemacs-p
        (if (fboundp 'view-mode)
            (view-mode 0)))
    (revert-buffer t no-confirm t)
    (or clearcase-xemacs-p
        (if (and (boundp 'view-read-only)
                 view-read-only
                 buffer-read-only)
            (view-mode 1)))

    ;; Restore point and mark.
    ;;
    (let ((new-point (clearcase-find-position-by-context point-context)))
      (if new-point
          (goto-char new-point))
      (if mark-context
          (let ((new-mark (clearcase-find-position-by-context mark-context)))
            (if new-mark
                (set-mark new-mark))))

      ;; Restore a semblance of folded state.
      ;;
      (if (and (boundp 'folded-file)
               folded-file)
          (progn
            (folding-open-buffer)
            (folding-whole-buffer)
            (if new-point
                (folding-goto-char new-point)))))))

;;}}}

;;{{{ Utilities

;;{{{ Temporary files

(defvar clearcase-tempfiles nil)
(defun clearcase-utl-tempfile-name (&optional vxpath)
  (let ((ext ""))
    (and vxpath
         (save-match-data
           (if (string-match "\\(\\.[^.]+\\)@@" vxpath)
               (setq ext (match-string 1 vxpath)))))
    (let ((filename (concat
                     (make-temp-name (clearcase-path-canonical
                                      ;; Use TEMP e.v. if set.
                                      ;;
                                      (concat (or (getenv "TEMP") "/tmp")
                                              "/clearcase-")))
                     ext)))
      ;; Store its name for later cleanup.
      ;;
      (setq clearcase-tempfiles (cons filename clearcase-tempfiles))
      filename)))

(defun clearcase-utl-clean-tempfiles ()
  (mapcar (function
                 (lambda (tempfile)
                   (if (file-exists-p tempfile)
                       (condition-case nil
                           (delete-file tempfile)
                         (error nil)))))
         clearcase-tempfiles)
  (setq clearcase-tempfiles nil))

;;}}}

(defun clearcase-utl-emacs-date-to-clearcase-date (s)
  (concat
   (substring s 20);; yyyy
   (int-to-string (clearcase-utl-month-unparse (substring s 4 7)));; mm
   (substring s 8 10);; dd
   "."
   (substring s 11 13);; hh
   (substring s 14 16);; mm
   (substring s 17 19)));; ss

(defun clearcase-utl-month-unparse (s)
  (cond
   ((string= s "Jan") 1)
   ((string= s "Feb") 2)
   ((string= s "Mar") 3)
   ((string= s "Apr") 4)
   ((string= s "May") 5)
   ((string= s "Jun") 6)
   ((string= s "Jul") 7)
   ((string= s "Aug") 8)
   ((string= s "Sep") 9)
   ((string= s "Oct") 10)
   ((string= s "Nov") 11)
   ((string= s "Dec") 12)))

(defun clearcase-utl-strip-trailing-slashes (name)
  (let* ((len (length name)))
    (while (and (> len 1)
                (or (equal ?/ (aref name (1- len)))
                    (equal ?\\ (aref name (1- len)))))
      (setq len (1- len)))
    (substring name 0 len)))

(defun clearcase-utl-file-size (file)
  (nth 7 (file-attributes file)))
(defun clearcase-utl-file-atime (file)
  (nth 4 (file-attributes file)))
(defun clearcase-utl-file-mtime (file)
  (nth 5 (file-attributes file)))
(defun clearcase-utl-file-ctime (file)
  (nth 6 (file-attributes file)))

(defun clearcase-utl-kill-view-buffer ()
  (interactive)
  (let ((buf (current-buffer)))
    (delete-windows-on buf)
    (kill-buffer buf)))

(defun clearcase-utl-escape-double-quotes (s)
  "Escape any double quotes in string S"
  (mapconcat (function (lambda (char)
                         (if (equal ?\" char)
                             (string ?\\ char)
                           (string char))))
             s
             ""))

(defun clearcase-utl-escape-backslashes (s)
  "Double any backslashes in string S"
  (mapconcat (function (lambda (char)
                         (if (equal ?\\ char)
                             "\\\\"
                           (string char))))
             s
             ""))

(defun clearcase-utl-quote-if-nec (token)
  "If TOKEN contains whitespace and is not already quoted,
wrap it in double quotes."
  (if (and (string-match "[ \t]" token)
           (not (equal ?\" (aref token 0)))
           (not (equal ?\' (aref token 0))))
      (concat "\"" token "\"")
    token))

(defun clearcase-utl-or-func (&rest args)
  "A version of `or' that can be applied to a list."
  (let ((result nil)
        (cursor args))
    (while (and (null result)
                cursor)
      (if (car cursor)
          (setq result t))
      (setq cursor (cdr cursor)))
    result))

(defun clearcase-utl-list-filter (predicate list)
  "Map PREDICATE over each element of LIST, and return a list of the elements
that mapped to non-nil."
  (let ((result '())
        (cursor list))
    (while (not (null cursor))
      (let ((elt (car cursor)))
        (if (funcall predicate elt)
            (setq result (cons elt result)))
        (setq cursor (cdr cursor))))
    (nreverse result)))

(defun clearcase-utl-elts-are-eq (l)
  "Test if all elements of LIST are eq."
  (if (null l)
      t
    (let ((head (car l))
          (answer t))
      (mapcar (function (lambda (elt)
                          (if (not (eq elt head))
                              (setq answer nil))))
              (cdr l))
      answer)))
  
;; FSF Emacs - doesn't like parameters on mark-marker.
;;
(defun clearcase-utl-mark-marker ()
  (if clearcase-xemacs-p
      (mark-marker t)
    (mark-marker)))

(defun clearcase-utl-syslog (buf value)
  (save-excursion
    (let ((tmpbuf (get-buffer buf)))
      (if (bufferp tmpbuf)
          (progn
            (set-buffer buf)
            (goto-char (point-max))
            (insert (format "%s\n" value)))))))

;; Extract the first line of a string.
;;
(defun clearcase-utl-1st-line-of-string (s)
  (let ((newline ?\n)
        (len (length s))
        (i 0))
    (while (and (< i len)
                (not (eq newline
                         (aref s i))))
      (setq i (1+ i)))
    (substring s 0 i)))

(defun clearcase-utl-split-string (str pat &optional indir suffix)
  (let ((ret nil)
        (start 0)
        (last (length str)))
    (while (< start last)
      (if (string-match pat str start)
          (progn
            (let ((tmp (substring str start (match-beginning 0))))
              (if suffix (setq tmp (concat tmp suffix)))
              (setq ret (cons (if indir (cons tmp nil)
                                tmp)
                              ret)))
            (setq start (match-end 0)))
        (setq start last)
        (setq ret (cons (substring str start) ret))))
    (nreverse ret)))

(defun clearcase-utl-split-string-at-char (str char)
  (let ((ret nil)
        (i 0)
        (eos (length str)))
    (while (< i eos)
      ;; Collect next token
      ;;
      (let ((token-begin i))
        ;; Find the end
        ;;
        (while (and (< i eos)
                    (not (eq char (aref str i))))
          (setq i (1+ i)))

        (setq ret (cons (substring str token-begin i)
                        ret))
        (setq i (1+ i))))
    (nreverse ret)))


(defun clearcase-utl-add-env (env var)
  (catch 'return
    (let ((a env)
          (vname (substring var 0
                            (and (string-match "=" var)
                                 (match-end 0)))))
      (let ((vnl (length vname)))
        (while a
          (if (and (> (length (car a)) vnl)
                   (string= (substring (car a) 0 vnl)
                            vname))
              (throw 'return env))
          (setq a (cdr a)))
        (cons var env)))))


(defun clearcase-utl-augment-env-from-view-config-spec (old-env tag &optional add-ons)
  (let ((newenv nil)
        (cc-env (clearcase-misc-extract-evs-from-config-spe tag)))

    ;; 1. Add-on bindings at the front:
    ;;
    (while add-ons
      (setq newenv (clearcase-utl-add-env newenv (car add-ons)))
      (setq add-ons (cdr add-ons)))

    ;; 2. Then bindings defined in the config-spec:
    ;;
    (while cc-env
      (setq newenv (clearcase-utl-add-env newenv (car cc-env)))
      (setq cc-env (cdr cc-env)))

    ;; 3. Lastly bindings that were in the old environment.
    ;;
    (while old-env
      (setq newenv (clearcase-utl-add-env newenv (car old-env)))
      (setq old-env (cdr old-env)))
    newenv))

;;}}}

;;}}}

;;{{{ Menus

;; Predicate to determine if ClearCase menu items are relevant.
;; nyi" this should disappear
;;
(defun clearcase-buffer-contains-version-p ()
  "Return true if the current buffer contains a ClearCase file or directory."
  (let ((object-name (if (eq major-mode 'dired-mode)
                         default-directory
                       buffer-file-name)))
    (clearcase-fprop-file-is-version-p object-name)))

;;{{{ clearcase-mode menu

;;{{{ The contents

;; This version of the menu will hide rather than grey out inapplicable entries.
;;
(defvar clearcase-menu-contents-minimised
  (list "ClearCase"

        ["Check In" clearcase-checkin-current-buffer
         :keys nil
         :visible (clearcase-file-ok-to-checkin buffer-file-name)]

        ["Check Out" clearcase-checkout-current-buffer
         :keys nil
         :visible (clearcase-file-ok-to-checkout buffer-file-name)]

        ["Un-checkout" clearcase-uncheckout-current-buffer
         :visible (clearcase-file-ok-to-uncheckout buffer-file-name)]

        ["Find checkouts" clearcase-find-checkouts-in-current-view t]

        ["Make element" clearcase-mkelem-current-buffer
         :visible (clearcase-file-ok-to-mkelem buffer-file-name)]

        "---------------------------------"
        ["Describe version" clearcase-describe-current-buffer
         :visible (clearcase-buffer-contains-version-p)]

        ["Describe file" clearcase-describe-current-buffer
         :visible (not (clearcase-buffer-contains-version-p))]

        ["Show config-spec rule" clearcase-what-rule-current-buffer
         :visible (clearcase-buffer-contains-version-p)]

        ;; nyi: enable this also when setviewed ?
        ;;
        ["Edit config-spec" clearcase-edcs-edit t]

        "---------------------------------"
        (list "Compare (emacs)..."
              ["Compare with predecessor" clearcase-ediff-pred-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-ediff-branch-base-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-ediff-named-version-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)])
        (list "Compare (applet)..."
              ["Compare with predecessor" clearcase-applet-diff-pred-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-applet-diff-branch-base-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-applet-diff-named-version-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)])
        (list "Compare (diff)..."
              ["Compare with predecessor" clearcase-diff-pred-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-diff-branch-base-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-diff-named-version-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)])
        "---------------------------------"
        ["Browse versions (dired)" clearcase-browse-vtree-current-buffer
         :visible (clearcase-file-ok-to-browse buffer-file-name)]
        ["Vtree browser applet" clearcase-applet-vtree-browser-current-buffer
         :keys nil
         :visible (clearcase-buffer-contains-version-p)]
        "---------------------------------"
        (list "Update snapshot..."
              ["Update view" clearcase-update-view
               :keys nil
               :visible (and (clearcase-file-is-in-view-p default-directory)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update directory" clearcase-update-default-directory
               :keys nil
               :visible (and (clearcase-file-is-in-view-p default-directory)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update this file" clearcase-update-current-buffer
               :keys nil
               :visible (and (clearcase-file-ok-to-checkout buffer-file-name)
                             (not (clearcase-file-is-in-mvfs-p buffer-file-name)))]
              )
        "---------------------------------"
        (list "Element history..."
              ["Element history (full)" clearcase-list-history-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Element history (branch)" clearcase-list-history-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)]
              ["Element history (me)" clearcase-list-history-current-buffer
               :keys nil
               :visible (clearcase-buffer-contains-version-p)])
        "---------------------------------"
        ["Show current activity" clearcase-ucm-describe-current-activity
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Make activity" clearcase-ucm-mkact-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set activity..." clearcase-ucm-set-activity-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set NO activity" clearcase-ucm-set-activity-none-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Rebase this stream" clearcase-applet-rebase
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Deliver from this stream" clearcase-applet-deliver
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        "---------------------------------"
        (list "Applets"
              ["Merge manager" clearcase-applet-merge-manager
               :keys nil]
              ["Project explorer" clearcase-applet-project-explorer
               :keys nil]
              ["Snapshot view updater" clearcase-applet-snapshot-view-updater
               :keys nil])
        "---------------------------------"

        ;; nyi:
        ;; Enable this when current buffer is on VOB.
        ;;
        ["Make branch type" clearcase-mkbrtype
         :keys nil]

        "---------------------------------"
        ["Report Bug in ClearCase Mode" clearcase-submit-bug-report
         :keys nil]

        ["Dump internals" clearcase-dump
         :keys nil
         :visible (or (equal "rwhitby" (user-login-name))
                      (equal "esler" (user-login-name)))]

        ["Flush caches" clearcase-flush-caches
         :keys nil
         :visible (or (equal "rwhitby" (user-login-name))
                      (equal "esler" (user-login-name)))]

        "---------------------------------"
        ["Customize..." (customize-group 'clearcase)
         :keys nil]))

(defvar clearcase-menu-contents
  (list "ClearCase"

        ["Check In" clearcase-checkin-current-buffer
         :keys nil
         :active (clearcase-file-ok-to-checkin buffer-file-name)]

        ["Check Out" clearcase-checkout-current-buffer
         :keys nil
         :active (clearcase-file-ok-to-checkout buffer-file-name)]

        ["Un-checkout" clearcase-uncheckout-current-buffer
         :active (clearcase-file-ok-to-uncheckout buffer-file-name)]

        ["Make element" clearcase-mkelem-current-buffer
         :active (clearcase-file-ok-to-mkelem buffer-file-name)]

        "---------------------------------"
        ["Describe version" clearcase-describe-current-buffer
         :active (clearcase-buffer-contains-version-p)]

        ["Describe file" clearcase-describe-current-buffer
         :active (not (clearcase-buffer-contains-version-p))]

        ["Show config-spec rule" clearcase-what-rule-current-buffer
         :active (clearcase-buffer-contains-version-p)]

        ;; nyi: enable this also when setviewed ?
        ;;
        ["Edit config-spec" clearcase-edcs-edit t]

        "---------------------------------"
        (list "Compare (emacs)..."
              ["Compare with predecessor" clearcase-ediff-pred-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-ediff-branch-base-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-ediff-named-version-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)])
        (list "Compare (applet)..."
              ["Compare with predecessor" clearcase-applet-diff-pred-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-applet-diff-branch-base-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-applet-diff-named-version-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)])
        (list "Compare (diff)..."
              ["Compare with predecessor" clearcase-diff-pred-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with branch base" clearcase-diff-branch-base-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Compare with named version" clearcase-diff-named-version-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)])
        "---------------------------------"
        ["Browse versions (dired)" clearcase-browse-vtree-current-buffer
         :active (clearcase-file-ok-to-browse buffer-file-name)]
        ["Vtree browser applet" clearcase-applet-vtree-browser-current-buffer
         :keys nil
         :active (clearcase-buffer-contains-version-p)]
        "---------------------------------"
        (list "Update snapshot..."
              ["Update view" clearcase-update-view
               :keys nil
               :active (and (clearcase-file-is-in-view-p default-directory)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update directory" clearcase-update-default-directory
               :keys nil
               :active (and (clearcase-file-is-in-view-p default-directory)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update this file" clearcase-update-current-buffer
               :keys nil
               :active (and (clearcase-file-ok-to-checkout buffer-file-name)
                            (not (clearcase-file-is-in-mvfs-p buffer-file-name)))]
              )
        "---------------------------------"
        (list "Element history..."
              ["Element history (full)" clearcase-list-history-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Element history (branch)" clearcase-list-history-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)]
              ["Element history (me)" clearcase-list-history-current-buffer
               :keys nil
               :active (clearcase-buffer-contains-version-p)])
        "---------------------------------"
        ["Show current activity" clearcase-ucm-describe-current-activity
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Make activity" clearcase-ucm-mkact-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set activity..." clearcase-ucm-set-activity-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set NO activity" clearcase-ucm-set-activity-none-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Rebase this stream" clearcase-applet-rebase
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Deliver from this stream" clearcase-applet-deliver
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        "---------------------------------"
        (list "Applets"
              ["Merge manager" clearcase-applet-merge-manager
               :keys nil]
              ["Project explorer" clearcase-applet-project-explorer
               :keys nil]
              ["Snapshot view updater" clearcase-applet-snapshot-view-updater
               :keys nil])
        "---------------------------------"

        ;; nyi:
        ;; Enable this when current buffer is on VOB.
        ;;
        ["Make branch type" clearcase-mkbrtype
         :keys nil]

        "---------------------------------"
        ["Report Bug in ClearCase Mode" clearcase-submit-bug-report
         :keys nil]

        ["Dump internals" clearcase-dump
         :keys nil
         :active (or (equal "rwhitby" (user-login-name))
                     (equal "esler" (user-login-name)))]

        ["Flush caches" clearcase-flush-caches
         :keys nil
         :active (or (equal "rwhitby" (user-login-name))
                     (equal "esler" (user-login-name)))]

        "---------------------------------"
        ["Customize..." (customize-group 'clearcase)
         :keys nil]))

(if (and clearcase-minimise-menus
         (not clearcase-xemacs-p))
    (setq clearcase-menu-contents clearcase-menu-contents-minimised))

;;}}}

(if (>= emacs-major-version '20)
    (progn
      ;; Define the menu
      ;;
      (easy-menu-define
       clearcase-menu
       (list clearcase-mode-map)
       "ClearCase menu"
       clearcase-menu-contents)

      (or clearcase-xemacs-p
          (add-to-list 'menu-bar-final-items 'ClearCase))))

;;}}}

;;{{{ clearcase-dired-mode menu

;;{{{ Related functions

;; nyi: this probably gets run for each menu element.
;;      For better efficiency, look into using a one-pass ":filter"
;;      to construct this menu dynamically.

(defun clearcase-dired-mark-count ()
  (let ((old-point (point))
        (count 0))
    (goto-char (point-min))
    (while (re-search-forward
            (concat "^" (regexp-quote (char-to-string
                                       dired-marker-char))) nil t)
      (setq count (1+ count)))
    (goto-char old-point)
    count))

(defun clearcase-dired-current-ok-to-checkin ()
  (let ((file (dired-get-filename nil t)))
    (and file
         (clearcase-file-ok-to-checkin file))))

(defun clearcase-dired-current-ok-to-checkout ()
  (let ((file (dired-get-filename nil t)))
    (and file
         (clearcase-file-ok-to-checkout file))))

(defun clearcase-dired-current-ok-to-uncheckout ()
  (let ((file (dired-get-filename nil t)))
    (and file
         (clearcase-file-ok-to-uncheckout file))))

(defun clearcase-dired-current-ok-to-mkelem ()
  (let ((file (dired-get-filename nil t)))
    (and file
         (clearcase-file-ok-to-mkelem file))))

(defun clearcase-dired-current-ok-to-browse ()
  (let ((file (dired-get-filename nil t)))
    (clearcase-file-ok-to-browse file)))

(defvar clearcase-dired-max-marked-files-to-check 5
  "The maximum number of marked files in a Dired buffer when constructing
the ClearCase menu.")

(defun clearcase-dired-marked-ok-to-checkin ()
  (let ((files (dired-get-marked-files)))
    (or (> (length files) clearcase-dired-max-marked-files-to-check)
        (apply (function clearcase-utl-or-func)
               (mapcar
                (function clearcase-file-ok-to-checkin)
                files)))))

(defun clearcase-dired-marked-ok-to-checkout ()
  (let ((files (dired-get-marked-files)))
    (or (> (length files) clearcase-dired-max-marked-files-to-check)
        (apply (function clearcase-utl-or-func)
               (mapcar
                (function clearcase-file-ok-to-checkout)
                files)))))

(defun clearcase-dired-marked-ok-to-uncheckout ()
  (let ((files (dired-get-marked-files)))
    (or (> (length files) clearcase-dired-max-marked-files-to-check)
        (apply (function clearcase-utl-or-func)
               (mapcar
                (function clearcase-file-ok-to-uncheckout)
                files)))))

(defun clearcase-dired-marked-ok-to-mkelem ()
  (let ((files (dired-get-marked-files)))
    (or (> (length files) clearcase-dired-max-marked-files-to-check)
        (apply (function clearcase-utl-or-func)
               (mapcar
                (function clearcase-file-ok-to-mkelem)
                files)))))

(defun clearcase-dired-current-dir-ok-to-checkin ()
  (let ((dir (dired-current-directory)))
    (clearcase-file-ok-to-checkin dir)))

(defun clearcase-dired-current-dir-ok-to-checkout ()
  (let ((dir (dired-current-directory)))
    (clearcase-file-ok-to-checkout dir)))

(defun clearcase-dired-current-dir-ok-to-uncheckout ()
  (let ((dir (dired-current-directory)))
    (clearcase-file-ok-to-uncheckout dir)))

;;}}}

;;{{{ Contents

;; This version of the menu will hide rather than grey out inapplicable entries.
;;
(defvar clearcase-dired-menu-contents-minimised
  (list "ClearCase"

        ;; Current file
        ;;
        ["Check-in file" clearcase-checkin-dired-files
         :keys nil
         :visible (and (< (clearcase-dired-mark-count) 2)
                       (clearcase-dired-current-ok-to-checkin))]

        ["Check-out file" clearcase-checkout-dired-files
         :keys nil
         :visible (and (< (clearcase-dired-mark-count) 2)
                       (clearcase-dired-current-ok-to-checkout))]

        ["Un-check-out file" clearcase-uncheckout-dired-files
         :keys nil
         :visible (and (< (clearcase-dired-mark-count) 2)
                       (clearcase-dired-current-ok-to-uncheckout))]

        ["Find checkouts" clearcase-find-checkouts-in-current-view t]

        ["Make file an element" clearcase-mkelem-dired-files
         :visible (and (< (clearcase-dired-mark-count) 2)
                       (clearcase-dired-current-ok-to-mkelem))]

        ;; Marked files
        ;;
        ["Check-in marked files" clearcase-checkin-dired-files
         :keys nil
         :visible (and (>= (clearcase-dired-mark-count) 2)
                       (clearcase-dired-marked-ok-to-checkin))]

        ["Check-out marked files" clearcase-checkout-dired-files
         :keys nil
         :visible (and (>= (clearcase-dired-mark-count) 2)
                       (clearcase-dired-marked-ok-to-checkout))]

        ["Un-check-out marked files" clearcase-uncheckout-dired-files
         :keys nil
         :visible (and (>= (clearcase-dired-mark-count) 2)
                       (clearcase-dired-marked-ok-to-uncheckout))]

        ["Make marked files elements" clearcase-mkelem-dired-files
         :keys nil
         :visible (and (>= (clearcase-dired-mark-count) 2)
                       (clearcase-dired-marked-ok-to-mkelem))]


        ;; Current directory
        ;;
        ["Check-in current-dir" clearcase-dired-checkin-current-dir
         :keys nil
         :visible (clearcase-dired-current-dir-ok-to-checkin)]

        ["Check-out current dir" clearcase-dired-checkout-current-dir
         :keys nil
         :visible (clearcase-dired-current-dir-ok-to-checkout)]

        ["Un-checkout current dir" clearcase-dired-uncheckout-current-dir
         :keys nil
         :visible (clearcase-dired-current-dir-ok-to-uncheckout)]

        "---------------------------------"
        ["Describe file" clearcase-describe-dired-file
         :visible t]

        ["Show config-spec rule" clearcase-what-rule-dired-file
         :visible t]


        ["Edit config-spec" clearcase-edcs-edit t]

        "---------------------------------"
        (list "Compare (emacs)..."
              ["Compare with predecessor" clearcase-ediff-pred-dired-file
               :keys nil
               :visible t]
              ["Compare with branch base" clearcase-ediff-branch-base-dired-file
               :keys nil
               :visible t]
              ["Compare with named version" clearcase-ediff-named-version-dired-file
               :keys nil
               :visible t])
        (list "Compare (applet)..."
              ["Compare with predecessor" clearcase-applet-diff-pred-dired-file
               :keys nil
               :visible t]
              ["Compare with branch base" clearcase-applet-diff-branch-base-dired-file
               :keys nil
               :visible t]
              ["Compare with named version" clearcase-applet-diff-named-version-dired-file
               :keys nil
               :visible t])
        (list "Compare (diff)..."
              ["Compare with predecessor" clearcase-diff-pred-dired-file
               :keys nil
               :visible t]
              ["Compare with branch base" clearcase-diff-branch-base-dired-file
               :keys nil
               :visible t]
              ["Compare with named version" clearcase-diff-named-version-dired-file
               :keys nil
               :visible t])
        "---------------------------------"
        ["Browse versions (dired)" clearcase-browse-vtree-dired-file
         :visible (clearcase-dired-current-ok-to-browse)]
        ["Vtree browser applet" clearcase-applet-vtree-browser-dired-file
         :keys nil
         :visible t]
        "---------------------------------"
        (list "Update snapshot..."
              ["Update view" clearcase-update-view
               :keys nil
               :visible (and (clearcase-file-is-in-view-p default-directory)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update directory" clearcase-update-default-directory
               :keys nil
               :visible (and (clearcase-file-is-in-view-p default-directory)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update file" clearcase-update-dired-files
               :keys nil
               :visible (and (< (clearcase-dired-mark-count) 2)
                             (clearcase-dired-current-ok-to-checkout)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update marked files" clearcase-update-dired-files
               :keys nil
               :visible (and (>= (clearcase-dired-mark-count) 2)
                             (not (clearcase-file-is-in-mvfs-p default-directory)))]
              )
        "---------------------------------"
        (list "Element history..."
              ["Element history (full)" clearcase-list-history-dired-file
               :keys nil
               :visible t]
              ["Element history (branch)" clearcase-list-history-dired-file
               :keys nil
               :visible t]
              ["Element history (me)" clearcase-list-history-dired-file
               :keys nil
               :visible t])
        "---------------------------------"
        ["Show current activity" clearcase-ucm-describe-current-activity
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Make activity" clearcase-ucm-mkact-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set activity..." clearcase-ucm-set-activity-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set NO activity" clearcase-ucm-set-activity-none-current-dir
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Rebase this stream" clearcase-applet-rebase
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Deliver from this stream" clearcase-applet-deliver
         :keys nil
         :visible (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        "---------------------------------"
        (list "Applets"
              ["Merge manager" clearcase-applet-merge-manager
               :keys nil]
              ["Project explorer" clearcase-applet-project-explorer
               :keys nil]
              ["Snapshot view updater" clearcase-applet-snapshot-view-updater
               :keys nil])
        "---------------------------------"

        ["Make branch type" clearcase-mkbrtype
         :keys nil]

        "---------------------------------"
        ["Report Bug in ClearCase Mode" clearcase-submit-bug-report
         :keys nil]

        ["Dump internals" clearcase-dump
         :keys nil
         :visible (or (equal "rwhitby" (user-login-name))
                      (equal "esler" (user-login-name)))]

        ["Flush caches" clearcase-flush-caches
         :keys nil
         :visible (or (equal "rwhitby" (user-login-name))
                      (equal "esler" (user-login-name)))]

        "---------------------------------"
        ["Customize..." (customize-group 'clearcase)
         :keys nil]))

(defvar clearcase-dired-menu-contents
  (list "ClearCase"

        ;; Current file
        ;;
        ["Check-in file" clearcase-checkin-dired-files
         :keys nil
         :active (and (< (clearcase-dired-mark-count) 2)
                      (clearcase-dired-current-ok-to-checkin))]

        ["Check-out file" clearcase-checkout-dired-files
         :keys nil
         :active (and (< (clearcase-dired-mark-count) 2)
                      (clearcase-dired-current-ok-to-checkout))]

        ["Un-check-out file" clearcase-uncheckout-dired-files
         :keys nil
         :active (and (< (clearcase-dired-mark-count) 2)
                      (clearcase-dired-current-ok-to-uncheckout))]

        ["Make file an element" clearcase-mkelem-dired-files
         :active (and (< (clearcase-dired-mark-count) 2)
                      (clearcase-dired-current-ok-to-mkelem))]

        ;; Marked files
        ;;
        ["Check-in marked files" clearcase-checkin-dired-files
         :keys nil
         :active (and (>= (clearcase-dired-mark-count) 2)
                      (clearcase-dired-marked-ok-to-checkin))]

        ["Check-out marked files" clearcase-checkout-dired-files
         :keys nil
         :active (and (>= (clearcase-dired-mark-count) 2)
                      (clearcase-dired-marked-ok-to-checkout))]

        ["Un-check-out marked files" clearcase-uncheckout-dired-files
         :keys nil
         :active (and (>= (clearcase-dired-mark-count) 2)
                      (clearcase-dired-marked-ok-to-uncheckout))]

        ["Make marked files elements" clearcase-mkelem-dired-files
         :keys nil
         :active (and (>= (clearcase-dired-mark-count) 2)
                      (clearcase-dired-marked-ok-to-mkelem))]


        ;; Current directory
        ;;
        ["Check-in current-dir" clearcase-dired-checkin-current-dir
         :keys nil
         :active (clearcase-dired-current-dir-ok-to-checkin)]

        ["Check-out current dir" clearcase-dired-checkout-current-dir
         :keys nil
         :active (clearcase-dired-current-dir-ok-to-checkout)]

        ["Un-checkout current dir" clearcase-dired-uncheckout-current-dir
         :keys nil
         :active (clearcase-dired-current-dir-ok-to-uncheckout)]

        "---------------------------------"
        ["Describe file" clearcase-describe-dired-file
         :active t]

        ["Show config-spec rule" clearcase-what-rule-dired-file
         :active t]


        ["Edit config-spec" clearcase-edcs-edit t]

        "---------------------------------"
        (list "Compare (emacs)..."
              ["Compare with predecessor" clearcase-ediff-pred-dired-file
               :keys nil
               :active t]
              ["Compare with branch base" clearcase-ediff-branch-base-dired-file
               :keys nil
               :active t]
              ["Compare with named version" clearcase-ediff-named-version-dired-file
               :keys nil
               :active t])
        (list "Compare (applet)..."
              ["Compare with predecessor" clearcase-applet-diff-pred-dired-file
               :keys nil
               :active t]
              ["Compare with branch base" clearcase-applet-diff-branch-base-dired-file
               :keys nil
               :active t]
              ["Compare with named version" clearcase-applet-diff-named-version-dired-file
               :keys nil
               :active t])
        (list "Compare (diff)..."
              ["Compare with predecessor" clearcase-diff-pred-dired-file
               :keys nil
               :active t]
              ["Compare with branch base" clearcase-diff-branch-base-dired-file
               :keys nil
               :active t]
              ["Compare with named version" clearcase-diff-named-version-dired-file
               :keys nil
               :active t])
        "---------------------------------"
        ["Browse versions (dired)" clearcase-browse-vtree-dired-file
         :active (clearcase-dired-current-ok-to-browse)]
        ["Vtree browser applet" clearcase-applet-vtree-browser-dired-file
         :keys nil
         :active t]
        "---------------------------------"
        (list "Update snapshot..."
              ["Update view" clearcase-update-view
               :keys nil
               :active (and (clearcase-file-is-in-view-p default-directory)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update directory" clearcase-update-default-directory
               :keys nil
               :active (and (clearcase-file-is-in-view-p default-directory)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update file" clearcase-update-dired-files
               :keys nil
               :active (and (< (clearcase-dired-mark-count) 2)
                            (clearcase-dired-current-ok-to-checkout)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              ["Update marked files" clearcase-update-dired-files
               :keys nil
               :active (and (>= (clearcase-dired-mark-count) 2)
                            (not (clearcase-file-is-in-mvfs-p default-directory)))]
              )
        "---------------------------------"
        (list "Element history..."
              ["Element history (full)" clearcase-list-history-dired-file
               :keys nil
               :active t]
              ["Element history (branch)" clearcase-list-history-dired-file
               :keys nil
               :active t]
              ["Element history (me)" clearcase-list-history-dired-file
               :keys nil
               :active t])
        "---------------------------------"
        ["Show current activity" clearcase-ucm-describe-current-activity
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Make activity" clearcase-ucm-mkact-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set activity..." clearcase-ucm-set-activity-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Set NO activity" clearcase-ucm-set-activity-none-current-dir
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Rebase this stream" clearcase-applet-rebase
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        ["Deliver from this stream" clearcase-applet-deliver
         :keys nil
         :active (clearcase-vprop-ucm (clearcase-fprop-viewtag default-directory))]
        "---------------------------------"
        (list "Applets"
              ["Merge manager" clearcase-applet-merge-manager
               :keys nil]
              ["Project explorer" clearcase-applet-project-explorer
               :keys nil]
              ["Snapshot view updater" clearcase-applet-snapshot-view-updater
               :keys nil])
        "---------------------------------"

        ["Make branch type" clearcase-mkbrtype
         :keys nil]

        "---------------------------------"
        ["Report Bug in ClearCase Mode" clearcase-submit-bug-report
         :keys nil]

        ["Dump internals" clearcase-dump
         :keys nil
         :active (or (equal "rwhitby" (user-login-name))
                     (equal "esler" (user-login-name)))]

        ["Flush caches" clearcase-flush-caches
         :keys nil
         :active (or (equal "rwhitby" (user-login-name))
                     (equal "esler" (user-login-name)))]

        "---------------------------------"
        ["Customize..." (customize-group 'clearcase)
         :keys nil]))

(if (and clearcase-minimise-menus
         (not clearcase-xemacs-p))
    (setq clearcase-dired-menu-contents clearcase-dired-menu-contents-minimised))

;;}}}

(if (>= emacs-major-version '20)
    (progn
      (easy-menu-define
       clearcase-dired-menu
       (list clearcase-dired-mode-map)
       "ClearCase Dired menu"
       clearcase-dired-menu-contents)

      (or clearcase-xemacs-p
          (add-to-list 'menu-bar-final-items 'ClearCase))))

;;}}}

;;}}}

;;{{{ Widgets

;;{{{ Single-selection buffer widget

;; Keep the compiler quiet by declaring these
;; buffer-local variables here thus.
;;
(defvar clearcase-selection-window-config nil)
(defvar clearcase-selection-interpreter nil)
(defvar clearcase-selection-continuation nil)
(defvar clearcase-selection-operands nil)

(defun clearcase-ucm-make-selection-window (buffer-name
                                            buffer-contents
                                            selection-interpreter
                                            continuation
                                            cont-arglist)
  (let ((buf (get-buffer-create buffer-name)))
    (save-excursion

      ;; Reset the buffer
      ;;
      (set-buffer buf)
      (setq buffer-read-only nil)
      (erase-buffer)
      (setq truncate-lines t)

      ;; Paint the buffer
      ;;
      (goto-char (point-min))
      (insert buffer-contents)

      ;; Insert mouse-highlighting
      ;;
      (save-excursion
        (goto-char (point-min))
        (while (< (point) (point-max))
          (condition-case nil
              (progn
                (beginning-of-line)
                (put-text-property (point)
                                   (save-excursion
                                     (end-of-line)
                                     (point))
                                   'mouse-face 'highlight))
            (error nil))
          (forward-line 1)))

      ;; Set a keymap
      ;;
      (setq buffer-read-only t)
      (use-local-map clearcase-selection-keymap)

      ;; Set up the interpreter and continuation
      ;;
      (set (make-local-variable 'clearcase-selection-window-config)
           (current-window-configuration))
      (set (make-local-variable 'clearcase-selection-interpreter)
           selection-interpreter)
      (set (make-local-variable 'clearcase-selection-continuation)
           continuation)
      (set (make-local-variable 'clearcase-selection-operands)
           cont-arglist))

    ;; Display the buffer
    ;;
    (pop-to-buffer buf)
    (goto-char 0)
    (shrink-window-if-larger-than-buffer)
    (message "Use RETURN to select an item")))

(defun clearcase-selection-continue ()
  (interactive)
  (beginning-of-line)
  (sit-for 0)
  ;; Call the interpreter to extract the item of interest
  ;; from the buffer.
  ;;
  (let ((item (funcall clearcase-selection-interpreter)))
    ;; Call the continuation.
    ;;
    (apply clearcase-selection-continuation
           (append clearcase-selection-operands (list item))))

  ;; Restore window config
  ;;
  (let ((sel-buffer (current-buffer)))
    (if clearcase-selection-window-config
        (set-window-configuration clearcase-selection-window-config))
    (delete-windows-on sel-buffer)
    (kill-buffer sel-buffer)))

(defun clearcase-selection-mouse-continue (click)
  (interactive "@e")
  (mouse-set-point click)
  (clearcase-selection-continue))

(defvar clearcase-selection-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map [return] 'clearcase-selection-continue)
    (define-key map [mouse-2] 'clearcase-selection-mouse-continue)
    (define-key map "q" 'clearcase-utl-kill-view-buffer)
    ;; nyi: refresh list
    ;; (define-key map "g" 'clearcase-selection-get)
    map))

;;}}}

;;}}}

;;{{{ Integration with Emacs

;;{{{ Functions: examining the ClearCase installation

;; Discover ClearCase version-string
;;
(defun clearcase-get-version-string ()
  ;; Some care seems to be necessary to avoid problems caused by odd settings
  ;; of the "SHELL" environment variable.  I found that simply
  ;; (shell-command-to-string "cleartool -version") on Windows-2000 with
  ;; SHELL==cmd.exe just returned a copy of the Windows command prompt. The
  ;; result was that clearcase-integrate would not complete.
  ;;
  ;; The follow seems to work.
  ;;
  (if (and clearcase-on-mswindows (not clearcase-on-cygwin32))
      (shell-command-to-string "cmd /c cleartool -version")
    (shell-command-to-string "sh -c \"cleartool -version\"")))

;; Find where cleartool is installed.
;;
(defun clearcase-find-cleartool ()
  "Search directories listed in the PATH environment variable
looking for a cleartool executable. If found return the full pathname."
  (let ((dir-list (parse-colon-path (getenv "PATH")))
        (cleartool-name (if clearcase-on-mswindows
                            "cleartool.exe"
                          "cleartool"))
        (cleartool-path nil))
     (catch 'found
       (mapcar
        (function (lambda (dir)
                    (let ((f (expand-file-name (concat dir cleartool-name))))
                      (if (file-executable-p f)
                          (progn
                            (setq cleartool-path f)
                            (throw 'found t))))))
        dir-list)
       nil)
     cleartool-path))

(defun clearcase-non-lt-registry-server-online-p ()
  "Heuristic to determine if the local host is network-connected to
its ClearCase servers. Used for a non-LT system."

  (let ((result nil)
        (buf (get-buffer-create "*clearcase-lsregion*")))
    (save-excursion
      (set-buffer buf)
      (erase-buffer)
      (let ((process (start-process "lsregion"
                                    buf
                                    "cleartool"
                                    "lsregion"
                                    "-long"))
            (timeout-occurred nil))

        ;; Now wait a little while, if necessary, for some output.
        ;;
        (while (and (null result)
                    (not timeout-occurred)
                    (< (buffer-size) (length "Tag: ")))
          (if (null (accept-process-output process 10))
              (setq timeout-occurred t))
          (goto-char (point-min))
          (if (looking-at "Tag: ")
              (setq result t)))
        (if (memq (process-status process) '(run stop))
            (kill-process process))))
    ;; If servers are apparently not online, keep the
    ;; buffer around so we can see what lsregion reported.
    ;;
    (if result
        (kill-buffer buf))
    result))

;; We could have an LT system, which lacks ct+lsregion, but has ct+lssite.
;;
(defun clearcase-lt-registry-server-online-p ()
  "Heuristic to determine if the local host is network-connected to
its ClearCase servers. Used for LT system."

  (let ((result nil)
        (buf (get-buffer-create "*clearcase-lssite*")))
    (save-excursion
      (set-buffer buf)
      (erase-buffer)
      (let ((process (start-process "lssite"
                                    buf
                                    "cleartool"
                                    "lssite"
                                    "-inquire"))
            (timeout-occurred nil))

        ;; Now wait a little while, if necessary, for some output.
        ;;
        (while (and (null result)
                    (not timeout-occurred)
                    (< (buffer-size) (length "  view_cache_size")))
          (if (null (accept-process-output process 10))
              (setq timeout-occurred t))
          (goto-char (point-min))
          (if (re-search-forward "view_cache_size" nil t)
              (setq result t)))
        (if (memq (process-status process) '(run stop))
            (kill-process process))))

    ;; If servers are apparently not online, keep the
    ;; buffer around so we can see what lssite reported.
    ;;
    (if result
        (kill-buffer buf))
    result))

;; Find out if the ClearCase registry server is accessible.
;; We could be on a disconnected laptop.
;;
(defun clearcase-registry-server-online-p ()
  "Heuristic to determine if the local host is network-connected to
its ClearCase server(s)."

  (if clearcase-lt
      (clearcase-lt-registry-server-online-p)
    (clearcase-non-lt-registry-server-online-p)))

;;}}}
;;{{{ Functions: hooks

;;{{{ A find-file hook to turn on clearcase-mode

(defun clearcase-hook-find-file-hook ()
  (let ((filename (buffer-file-name)))
    (if filename
        (progn
          (clearcase-fprop-unstore-properties filename)
          (if (clearcase-file-would-be-in-view-p filename)
              (progn
                ;; 1. Activate minor mode
                ;;
                (clearcase-mode 1)

                ;; 2. Pre-fetch file properties
                ;;
                (if (file-exists-p filename)
                    (progn
                      (clearcase-fprop-get-properties filename)

                      ;; 3. Put branch/ver in mode-line
                      ;;
                      (setq clearcase-mode
                            (concat " ClearCase:"
                                    (clearcase-mode-line-buffer-id filename)))
                      (force-mode-line-update)

                      ;; 4. Schedule the asynchronous fetching of the view's properties
                      ;;    next time Emacs is idle enough.
                      ;;
                      (clearcase-vprop-schedule-fetch (clearcase-fprop-viewtag filename))

                      ;; 5. Set backup policy
                      ;;
                      (unless clearcase-make-backup-files
                        (make-local-variable 'backup-inhibited)
                        (setq backup-inhibited t))))
                
                (clearcase-set-auto-mode)))))))

(defun clearcase-set-auto-mode ()
  "Check again for the mode of the current buffer when using ClearCase version extended paths."

  (let* ((version (clearcase-vxpath-version-part (buffer-file-name)))
         (buffer-file-name (clearcase-vxpath-element-part (buffer-file-name))))

    ;; Need to recheck the major mode only if a version was appended.
    ;;
    (if version
        (set-auto-mode))))

;;}}}

;;{{{ A find-file hook for version-extended pathnames

(defun clearcase-hook-vxpath-find-file-hook ()
  (if (clearcase-vxpath-p default-directory)
      (let ((element (clearcase-vxpath-element-part default-directory))
            (version (clearcase-vxpath-version-part default-directory)))

        ;; 1. Set the buffer name to <filename>@@/<branch path>/<version>.
        ;;
        (let ((new-buffer-name
               (concat (file-name-nondirectory element)
                       clearcase-vxpath-glue
                       version
                       (buffer-name))))
          
          (or (string= new-buffer-name (buffer-name))
              
              ;; Uniquify the name, if necessary.
              ;;
              (let ((n 2)
                    (uniquifier-string ""))
                (while (get-buffer (concat new-buffer-name uniquifier-string))
                  (setq uniquifier-string (format "<%d>" n))
                  (setq n (1+ n)))
                (rename-buffer
                 (concat new-buffer-name uniquifier-string)))))

        ;; 2. Set the default directory to the dir containing <filename>.
        ;;
        (let ((new-dir (file-name-directory element)))
          (setq default-directory new-dir))
        
        ;; 3. Disable auto-saving.
        ;;
        ;; If we're visiting <filename>@@/<branch path>/199
        ;; we don't want Emacs trying to find a place to create a "#199#.
        ;;
        (auto-save-mode 0))))

;;}}}

;;{{{ A dired-mode-hook to turn on clearcase-dired-mode

(defun clearcase-hook-dired-mode-hook ()
  ;; Force a re-computation of whether the directory is within ClearCase.
  ;;
  (clearcase-fprop-unstore-properties default-directory)

  ;; Wrap this in an exception handler. Otherwise, diredding into
  ;; a deregistered or otherwise defective snapshot-view fails.
  ;;
  (condition-case nil
      ;; If this directory is below a ClearCase element,
      ;;   1. turn on ClearCase Dired Minor Mode.
      ;;   2. display branch/ver in mode-line
      ;;
      (if (clearcase-file-would-be-in-view-p default-directory)
          (progn
            (if clearcase-auto-dired-mode
                (progn
                  (clearcase-dired-mode 1)
                  (clearcase-fprop-get-properties default-directory)
                  (clearcase-vprop-schedule-fetch (clearcase-fprop-viewtag default-directory))))
            (setq clearcase-dired-mode
                  (concat " ClearCase:"
                          (clearcase-mode-line-buffer-id default-directory)))
            (force-mode-line-update)))
    (error (message "Error fetching ClearCase properties of %s" default-directory))))

;;}}}

;;{{{ A dired-after-readin-hook to add ClearCase information to the display

(defun clearcase-hook-dired-after-readin-hook ()

  ;; If in clearcase-dired-mode, reformat the buffer.
  ;;
  (if clearcase-dired-mode
      (clearcase-dired-reformat-buffer))
  t)

;;}}}

;;{{{ A write-file-hook to auto-insert a version-string.

;; To use this, put a line containing this in the first 8 lines of your file:
;;    ClearCase-version: </main/laptop/82>
;; and make sure that clearcase-version-stamp-active gets set to true at least
;; locally in the file.

(defvar clearcase-version-stamp-line-limit 1000)
(defvar clearcase-version-stamp-begin-regexp "ClearCase-version:[ \t]<")
(defvar clearcase-version-stamp-end-regexp ">")
(defvar clearcase-version-stamp-active nil)

(defun clearcase-increment-version (version-string)
  (let* ((branch (clearcase-vxpath-branch version-string))
         (number (clearcase-vxpath-version version-string))
         (new-number (1+ (string-to-number number))))
    (format "%s%d" branch new-number)))

(defun clearcase-version-stamp ()
  (interactive)
  (if (and clearcase-version-stamp-active
           (file-exists-p buffer-file-name)
           (equal 'version (clearcase-fprop-mtype buffer-file-name)))
      (let ((latest-version (clearcase-fprop-predecessor-version buffer-file-name)))

        ;; Note: If the buffer happens to be folded, we may not find the place
        ;; to insert the version-stamp. Folding mode really needs to supply a
        ;; 'save-folded-excursion function to solve this one.  We won't attempt
        ;; a cheaper hack here.
            
        (save-excursion
          (save-restriction
            (widen)
            (goto-char (point-min))
            (forward-line clearcase-version-stamp-line-limit)
            (let ((limit (point))
                  (v-start nil)
                  (v-end nil))
              (goto-char (point-min))
              (while (and (< (point) limit)
                          (re-search-forward clearcase-version-stamp-begin-regexp
                                             limit
                                             'move))
                (setq v-start (point))
                (end-of-line)
                (let ((line-end (point)))
                  (goto-char v-start)
                  (if (re-search-forward clearcase-version-stamp-end-regexp
                                         line-end
                                         'move)
                      (setq v-end (match-beginning 0)))))
              (if v-end
                  (let ((new-version-stamp (clearcase-increment-version latest-version)))
                    (goto-char v-start)
                    (delete-region v-start v-end)
                    (insert-and-inherit new-version-stamp)))))))))

(defun clearcase-hook-write-file-hook ()

  (clearcase-version-stamp)
  ;; Important to return nil so the files eventually gets written.
  ;;
  nil)

;;}}}

;;{{{ A kill-buffer hook

(defun clearcase-hook-kill-buffer-hook ()
  (let ((filename (buffer-file-name)))
    (if (and filename
             ;; W3 has buffers in which 'buffer-file-name is bound to
             ;; a URL.  Don't attempt to unstore their properties.
             ;;
             (boundp 'buffer-file-truename)
             buffer-file-truename)
        (clearcase-fprop-unstore-properties filename))))

;;}}}

;;{{{ A kill-emacs-hook

(defun clearcase-hook-kill-emacs-hook ()
  (clearcase-utl-clean-tempfiles))

;;}}}

;;}}}
;;{{{ Function:  to replace toggle-read-only

(defun clearcase-toggle-read-only (&optional arg)
  "Change read-only status of current buffer, perhaps via version control.
If the buffer is visiting a ClearCase version, then check the file in or out.
Otherwise, just change the read-only flag of the buffer.  If called with an
argument then just change the read-only flag even if visiting a ClearCase
version."
  (interactive "P")
  (cond (arg
	 (toggle-read-only))
	((and (clearcase-fprop-mtype buffer-file-name)
              buffer-read-only
              (file-writable-p buffer-file-name)
              (/= 0 (user-uid)))
         (toggle-read-only))

        ((clearcase-fprop-mtype buffer-file-name)
         (clearcase-next-action-current-buffer))

        (t
         (toggle-read-only))))

;;}}}
;;{{{ Functions: file-name-handlers

;;{{{ Start dynamic views automatically when paths to them are used

;; This handler starts views when viewroot-relative paths are dereferenced.
;;
;; nyi: for now really only seems useful on Unix.
;;
(defun clearcase-viewroot-relative-file-name-handler (operation &rest args)

  (clearcase-when-debugging
   (if (fboundp 'clearcase-utl-syslog)
       (clearcase-utl-syslog "*clearcase-fh-trace*"
                             (cons "clearcase-viewroot-relative-file-name-handler:"
                                   (cons operation args)))))

  ;; Inhibit the handler to avoid recursion.
  ;;
  (let ((inhibit-file-name-handlers
         (cons 'clearcase-viewroot-relative-file-name-handler
               (and (eq inhibit-file-name-operation operation)
                    inhibit-file-name-handlers)))
        (inhibit-file-name-operation operation))

    (let ((first-arg (car args)))
      ;; We don't always get called with a string.
      ;; e.g. one file operation is verify-visited-file-modtime, whose
      ;; first argument is a buffer.
      ;;
      (if (stringp first-arg)
          (progn
            ;; Now start the view if necessary
            ;;
            (save-match-data
              (let* ((path (clearcase-path-remove-useless-viewtags first-arg))
                     (viewtag (clearcase-vrpath-viewtag path))
                     (default-directory (clearcase-path-remove-useless-viewtags default-directory)))
                (if viewtag
                    (clearcase-viewtag-try-to-start-view viewtag))))))
      (apply operation args))))

;;}}}

;;{{{ Completion on viewtags

;; This handler provides completion for viewtags.
;;
(defun clearcase-viewtag-file-name-handler (operation &rest args)

  (clearcase-when-debugging
   (if (fboundp 'clearcase-utl-syslog)
       (clearcase-utl-syslog "*clearcase-fh-trace*"
                             (cons "clearcase-viewtag-file-name-handler:"
                                   (cons operation args)))))
  (cond

   ((eq operation 'file-name-completion)
    (save-match-data (apply 'clearcase-viewtag-completion args)))

   ((eq operation 'file-name-all-completions)
    (save-match-data (apply 'clearcase-viewtag-completions args)))

   (t
    (let ((inhibit-file-name-handlers
           (cons 'clearcase-viewtag-file-name-handler
                 (and (eq inhibit-file-name-operation operation)
                      inhibit-file-name-handlers)))
          (inhibit-file-name-operation operation))
      (apply operation args)))))

(defun clearcase-viewtag-completion (file dir)
  (try-completion file (clearcase-viewtag-all-viewtag-dirs-obarray)))

(defun clearcase-viewtag-completions (file dir)
  (let ((tags (all-completions file
                               (clearcase-viewtag-all-viewtags-obarray))))
    (mapcar
     (function (lambda (tag)
                 (concat tag "/")))
     tags)))

;;}}}

;;{{{ Disable VC in the MVFS

;; This handler ensures that VC doesn't attempt to operate inside the MVFS.
;; This stops it from futile searches for RCS directories and the like inside.
;; It prevents a certain amount of clutter in the MVFS' noent-cache.
;;
(defun clearcase-suppress-vc-within-mvfs-file-name-handler (operation &rest args)
  (clearcase-when-debugging
   (if (fboundp 'clearcase-utl-syslog)
       (clearcase-utl-syslog "*clearcase-fh-trace*"
                             (cons "clearcase-suppress-vc-within-mvfs-file-name-handler:"
                                   (cons operation args)))))
  ;; Inhibit recursion:
  ;;
  (let ((inhibit-file-name-handlers
         (cons 'clearcase-suppress-vc-within-mvfs-file-name-handler
               (and (eq inhibit-file-name-operation operation)
                    inhibit-file-name-handlers)))
        (inhibit-file-name-operation operation))

    (cond
     ((and (eq operation 'vc-registered)
           (clearcase-file-would-be-in-view-p (car args)))
      nil)

     (t
      (apply operation args)))))

;;}}}

;;{{{ File name handler for version extended file names 

;; For version extended pathnames there are two possible answers
;; for each of
;;   file-name-directory
;;   file-name-nondirectory
;;
;; 1. that pertaining to the element path, e.g.
;;   (file-name-directory "DIR/FILE@@/BRANCH/VERSION")
;;     ==> "DIR/"
;; 2. that pertaining to the version path, e.g.
;;   (file-name-directory "DIR/FILE@@/BRANCH/VERSION")
;;     ==> "DIR/FILE@@/BRANCH/"
;;
;; Often we'd like the former, but sometimes we'd like the latter, for example
;; inside clearcase-browse-vtree, where it calls dired.  Within dired on Gnu
;; Emacs, it calls file-name-directory on the supplied pathname and in this
;; case we want the version (i.e. branch) path to be used.
;;
;; How to get the behaviour we want ?

;; APPROACH A:
;; ==========
;;
;; Define a variable clearcase-treat-branches-as-dirs, which modifies
;; the behaviour of clearcase-vxpath-file-name-handler to give answer (1).
;;
;; Just before we invoke dired inside clearcase-browse-vtree, dynamically
;; bind clearcase-treat-branches-as-dirs to t. Also in the resulting Dired Mode
;; buffer, make clearcase-treat-branches-as-dirs buffer-local and set it.
;;
;; Unfortunately this doesn't quite give us what we want. For example I often
;; invoke grep from a dired buffer on a branch-qua-directory to scan all the
;; version on that branch for a certain string.  The grep-mode buffer has no
;; buffer-local binding for clearcase-treat-branches-as-dirs so the grep
;; command runs in "DIR/" instead of in "DIR/FILE@@/BRANCH/".
;;
;; APPROACH B:
;; ==========
;;
;; Modify the semantics of clearcase-vxpath-file-name-handler so that
;; if the filename given is a pathname to an existing branch-qua-directory
;; give answer 2, otherwise give answer 1.
;;
;; APPROACH C:
;; ==========
;;
;; Use the existence of a Dired Mode buffer on "DIR/FILE@@/BRANCH/" to
;; change the semantics of clearcase-vxpath-file-name-handler.
;;
;; (A) is unsatisfactory and I'm not entirely happy with (B) nor (C) so for now
;; I'm going to disable this filename handler until I'm more convinced it is
;; needed.

(defun clearcase-vxpath-file-name-handler (operation &rest args)
  (clearcase-when-debugging
   (if (fboundp 'clearcase-utl-syslog)
       (clearcase-utl-syslog "*clearcase-fh-trace*"
                             (cons "clearcase-vxpath-file-name-handler:"
                                   (cons operation args)))))
  ;; Inhibit recursion:
  ;;
  (let ((inhibit-file-name-handlers
         (cons 'clearcase-vxpath-file-name-handler
               (and (eq inhibit-file-name-operation operation)
                    inhibit-file-name-handlers)))
        (inhibit-file-name-operation operation))

    (cond ((eq operation 'file-name-nondirectory)
	   (file-name-nondirectory (clearcase-vxpath-element-part
				    (car args))))
          
	  ((eq operation 'file-name-directory)
	   (file-name-directory (clearcase-vxpath-element-part
				 (car args))))
          
	  (t
	   (apply operation args)))))

;;}}}

;;}}}

;;{{{ Functions: integrate and un-integrate.

(defun clearcase-integrate ()
  "Enable ClearCase integration"
  (interactive)

  ;; 0. Empty caches.
  ;;
  (clearcase-fprop-clear-all-properties)
  (clearcase-vprop-clear-all-properties)

  ;; 1. Install hooks.
  ;;
  (add-hook 'find-file-hooks 'clearcase-hook-find-file-hook)
  (add-hook 'find-file-hooks 'clearcase-hook-vxpath-find-file-hook)
  (add-hook 'dired-mode-hook 'clearcase-hook-dired-mode-hook)
  (add-hook 'dired-after-readin-hook 'clearcase-hook-dired-after-readin-hook)
  (add-hook 'kill-buffer-hook 'clearcase-hook-kill-buffer-hook)
  (add-hook 'write-file-hooks 'clearcase-hook-write-file-hook)
  (add-hook 'kill-emacs-hook 'clearcase-hook-kill-emacs-hook)

  ;; 2. Install file-name handlers.
  ;;
  ;;    2.1 Start views when //view/TAG or m:/TAG is referenced.
  ;;
  (if (not clearcase-on-mswindows)
      (add-to-list 'file-name-handler-alist
                   (cons clearcase-vrpath-regexp
                         'clearcase-viewroot-relative-file-name-handler)))

  ;;    2.2 Completion on viewtags.
  ;;
  (if clearcase-complete-viewtags
      (add-to-list 'file-name-handler-alist
                   (cons clearcase-viewtag-regexp
                         'clearcase-viewtag-file-name-handler)))

  ;;    2.3 Turn off RCS/VCS/SCCS activity inside a ClearCase dynamic view.
  ;;
  (if clearcase-suppress-vc-within-mvfs
      (add-to-list 'file-name-handler-alist
                   (cons ".*" 'clearcase-suppress-vc-within-mvfs-file-name-handler)))

;; Disabled for now. See comments above clearcase-vxpath-file-name-handler.
;;  
;;   ;;    2.4 Add file name handler for version extended path names
;;   ;;
;;   (add-to-list 'file-name-handler-alist
;;                (cons clearcase-vxpath-glue 'clearcase-vxpath-file-name-handler))
  )

(defun clearcase-unintegrate ()
  "Disable ClearCase integration"
  (interactive)

  ;; 0. Empty caches.
  ;;
  (clearcase-fprop-clear-all-properties)
  (clearcase-vprop-clear-all-properties)

  ;; 1. Remove hooks.
  ;;
  (remove-hook 'find-file-hooks 'clearcase-hook-find-file-hook)
  (remove-hook 'find-file-hooks 'clearcase-hook-vxpath-find-file-hook)
  (remove-hook 'dired-mode-hook 'clearcase-hook-dired-mode-hook)
  (remove-hook 'dired-after-readin-hook 'clearcase-hook-dired-after-readin-hook)
  (remove-hook 'kill-buffer-hook 'clearcase-hook-kill-buffer-hook)
  (remove-hook 'write-file-hooks 'clearcase-hook-write-file-hook)
  (remove-hook 'kill-emacs-hook 'clearcase-hook-kill-emacs-hook)

  ;; 2. Remove file-name handlers.
  ;;
  (setq file-name-handler-alist
        (delete-if (function
                    (lambda (entry)
                      (memq (cdr entry)
                            '(clearcase-viewroot-relative-file-name-handler
                              clearcase-viewtag-file-name-handler
                              clearcase-suppress-vc-within-mvfs-file-name-handler
                              clearcase-vxpath-file-name-handler))))
                   file-name-handler-alist)))

;;}}}

;; Here's where we really wire it all in:
;;
(defvar clearcase-cleartool-path nil)
(defvar clearcase-clearcase-version-installed nil)
(defvar clearcase-lt nil)
(defvar clearcase-v3 nil)
(defvar clearcase-v4 nil)
(defvar clearcase-v5 nil)
(defvar clearcase-servers-online nil)
(defvar clearcase-setview-root nil)
(defvar clearcase-setview-viewtag)
(defvar clearcase-setview-root nil)
(defvar clearcase-setview-viewtag nil)

(progn
  ;; Things have to be done here in a certain order.
  ;;
  ;; 1. Make sure cleartool is on the shell search PATH.
  ;;
  (if (setq clearcase-cleartool-path (clearcase-find-cleartool))
      (progn
        ;; 2. Try to discover what version of ClearCase we have:
        ;;
        (setq clearcase-clearcase-version-installed (clearcase-get-version-string))
        (setq clearcase-lt
              (not (null (string-match "^ClearCase LT"
                                       clearcase-clearcase-version-installed))))
        (setq clearcase-v3
              (not (null (string-match "^ClearCase version 3"
                                       clearcase-clearcase-version-installed))))
        (setq clearcase-v4
              (not (null (string-match "^ClearCase version 4"
                                       clearcase-clearcase-version-installed))))
        (setq clearcase-v5
              (not (null (string-match "^ClearCase \\(LT \\)?version 2002.05"
                                       clearcase-clearcase-version-installed))))
        
        ;; 3. Gather setview information:
        ;;
        (if (setq clearcase-setview-root (if (not clearcase-on-mswindows)
                                             (getenv "CLEARCASE_ROOT")))
            (setq clearcase-setview-viewtag
                  (file-name-nondirectory clearcase-setview-root)))
        
        ;; 4. Discover if the servers appear to be online.
        ;;
        (setq clearcase-servers-online (clearcase-registry-server-online-p))
        
        (if clearcase-servers-online
            
            ;; 5. Everything seems in place to ensure that ClearCase mode will
            ;;    operate correctly, so integrate now.
            ;;
            (progn
              (clearcase-integrate)
              ;; Schedule a fetching of the view properties when next idle.
              ;; This avoids awkward pauses after the user reaches for the
              ;; ClearCase menubar entry.
              ;;
              (if clearcase-setview-viewtag
                  (clearcase-vprop-schedule-fetch clearcase-setview-viewtag)))))))

(if (not clearcase-servers-online)
    (message "ClearCase apparently not online. ClearCase/Emacs integration not installed."))

;;}}}

(provide 'clearcase)

;;; clearcase.el ends here

;; Local variables:
;; folded-file: t
;; clearcase-version-stamp-active: t
;; End:

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.