Source

ecb / ecb-file-browser.el

Full commit
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
;;; ecb-file-browser.el --- the file-browser of Emacs

;; Copyright (C) 2000 - 2003 Jesper Nordenberg,
;;                           Klaus Berndl,
;;                           Free Software Foundation, Inc.

;; Author: Jesper Nordenberg <mayhem@home.se>
;;         Klaus Berndl <klaus.berndl@sdm.de>
;; Maintainer: Klaus Berndl <klaus.berndl@sdm.de>
;; Keywords: browser, code, programming, tools
;; Created: 2000

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

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

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

;; $Id$

;;; Commentary:

;; This file contains the code of the file-browser of ECB

(require 'ecb-util)
(require 'tree-buffer)
(require 'ecb-mode-line)
(require 'ecb-navigate)
(require 'ecb-face)
(require 'ecb-speedbar)
(require 'ecb-layout)
(require 'ecb-common-browser)

;; various loads
(require 'assoc)

(eval-when-compile
  ;; to avoid compiler grips
  (require 'cl))

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

(silentcomp-defun ecb-speedbar-update-contents)
(silentcomp-defvar vc-cvs-stay-local)

;;====================================================
;; Customization
;;====================================================


(defgroup ecb-directories nil
  "Settings for the directories-buffer in the Emacs code browser."
  :group 'ecb
  :prefix "ecb-")

(defgroup ecb-sources nil
  "Settings for the sources-buffers in the Emacs code browser."
  :group 'ecb
  :prefix "ecb-")

(defgroup ecb-history nil
  "Settings for the history-buffer in the Emacs code browser."
  :group 'ecb
  :prefix "ecb-")

(defgroup ecb-version-control nil
  "Settings for the version-control support in the ECB."
  :group 'ecb
  :prefix "ecb-")

(defcustom ecb-source-path nil
  "*Paths where to find code sources.
Each path can have an optional alias that is used as it's display name. If no
alias is set, the path is used as display name.

Lisp-type of this option: The value must be a list L whereas each element of L
is either
- a simple string which has to be the full path of a directory \(this string
  is displayed in the directory-browser of ECB) or
- a 2-element list whereas the first element is the full path of a directory
  \(string) and the second element is an arbitrary alias \(string) for this
  directory which is then displayed instead of the underlying directory."
  :group 'ecb-directories
  :group 'ecb-most-important
  :initialize 'custom-initialize-default
  :set (function (lambda (symbol value)
                   (set symbol value)
                   (if (and (boundp 'ecb-minor-mode)
                            ecb-minor-mode
			    (functionp 'ecb-update-directories-buffer))
		       (ecb-update-directories-buffer))))
  :type '(repeat (choice :tag "Display type"
                         :menu-tag "Display type"
			 (directory :tag "Path")
			 (list :tag "Path with alias"
			       (directory :tag "Path")
			       (string :tag "Alias")))))

(defcustom ecb-add-path-for-not-matching-files '(t . nil)
  "*Add path of a file to `ecb-source-path' if not already contained.
This is done during the auto. windows synchronization which happens if a file
is opened not via the file/directory-browser of ECB. In such a situation ECB
adds the path of the new file auto. to `ecb-source-path' at least temporally
for the current Emacs session. This option defines two things:
1. Should only the root-part \(which means for Unix-like systems always '/'
   and for windows-like systems the drive) of the new file be added as
   source-path to `ecb-source-path' or the whole directory-part? For
   remote-files \(e.g. tramp, ange-ftp- or efs-files) the root-part is the
   complete host-part + the root-dir at that host \(example:
   /berndl@ecb.sourceforge.net:/ would be the root-part of
   /berndl@ecb.sourceforge.net:/tmp/test.txt).
2. Should this path be added for future sessions too?

The value of this option is a cons-cell where the car is a boolean for 1. and
the cdr is a boolean for 2.

A value of not nil for the car \(1.) is reasonably if a user often opens files
not via the ECB-browser which are not located in any of the paths of
`ecb-source-path' because then only one path for each drive \(windows) or the
root-path \(unix) is added to the directory buffer of ECB."
  :group 'ecb-directories
  :type '(cons (boolean :tag "Add only root path")
               (boolean :tag "Ask for saving for future sessions")))


(defvar ecb-source-path-functions nil
  "List of functions to call for finding sources.
Each time the function `ecb-update-directories-buffer' is called, the
functions in this variable will be evaluated. Such a function must return
either nil or a list of strings where each string is a path.")


(defcustom ecb-display-default-dir-after-start t
  "*Automatically display current default-directory after activating ECB.
If a file-buffer is displayed in the edit-window then ECB synchronizes its
tree-buffers to this file-buffer - at least if the option `ecb-window-sync' it
not nil. So for this situation `ecb-display-default-dir-after-start' takes no
effect but this option is for the case if no file-buffer is displayed in the
edit-window after startup:

If true then ECB selects autom. the current default-directory after activation
even if no file-buffer is displayed in the edit-window. This is useful if ECB
is autom. activated after startup of Emacs and Emacs is started without a
file-argument. So the directory from which the startup has performed is auto.
selected in the ECB-directories buffer and the ECB-sources buffer displays the
contents of this directory."
  :group 'ecb-directories
  :type 'boolean)


(defcustom ecb-show-sources-in-directories-buffer '("left7" "left13"
                                                    "left14" "left15")
  "*Show source files in directories buffer.
The value is either 'always or 'never or a list of layout-names for which
layouts sources should be displayed in the directories window."
  :group 'ecb-directories
  :initialize 'custom-initialize-default
  :set (function (lambda (symbol value)
		   (set symbol value)
		   (if (and ecb-minor-mode
			    (functionp 'ecb-set-selected-directory)
                            ecb-path-selected-directory)
		       (ecb-set-selected-directory ecb-path-selected-directory t))))
  :type '(radio (const :tag "Always" :value always)
                (const :tag "Never" :value never)
                (repeat :tag "With these layouts"
                        (string :tag "Layout name"))))


(defcustom ecb-directories-update-speedbar 'auto
  "*Update an integrated speedbar after selecting a directory.
If not nil then an integrated speedbar will be updated after selecting a
directory in the ECB-directories-buffer so the speedbar displays the contents
of that directory.

Of course this option makes only sense if the integrated speedbar is displayed
in addition to the ECB-directories-buffer.

This option can have the following values:
- t: Always update speedbar.
- nil: Never update speedbar.
- auto: Update when senseful \(see scenarios below)
- <function>: A user-defined function. The function is called after a
  directory is selected, gets the selected directory as argument and has to
  return nil if the the integrated speedbar should NOT be updated.

Two example-scenarios where different values for this option can be senseful:

If `ecb-show-sources-in-directories-buffer' is not nil or you have a layout
where an ECB-sources-buffer is visible then you probably want to use the
ECB-directories-buffer \(and/or the ECB-sources-buffer) for directory- and
file-browsing. If you have in addition an integrated speedbar running then you
probably want to use speedbar instead of the ECB-methods-buffer for
source-content-browsing. In this case you probably want the speedbar not be
updated because you do not need speedbar reflecting the current-directory
contents but only the contents of the currently selected source-file and the
integrated speedbar updates itself autom. for the latter one!

If `ecb-show-sources-in-directories-buffer' is nil and there is also no
ECB-sources-buffer visible in the current layout then you probably want to use
an integrated speedbar for browsing directory-contents \(i.e. the files) and
file-contents \(instead of the ECB-methods-buffer for example). In this case
you probably want the speedbar updated because you need speedbar reflecting
the current-directory contents so you can select files.

The value 'auto \(see above) takes exactly these two scenarios into account."
  :group 'ecb-directories
  :type '(radio (const :tag "Always" :value t)
                (const :tag "Never" :value nil)
                (const :tag "Automatic" :value auto)
                (function :tag "Custom function")))


(defun ecb-show-sources-in-directories-buffer-p ()
  "Return not nil if in current layout sources are shown in the
directories-buffer."
  (cond ((equal ecb-show-sources-in-directories-buffer 'never)
         nil)
        ((equal ecb-show-sources-in-directories-buffer 'always)
         t)
        (t
         (and (listp ecb-show-sources-in-directories-buffer)
              (member ecb-layout-name
                      ecb-show-sources-in-directories-buffer)))))

(defcustom ecb-cache-directory-contents '(("^/\\([^:/]*@\\)?\\([^@:/]*\\):.*" . 0)
                                          (".*" . 50))
  "*Cache contents of certain directories.
This can be useful if `ecb-source-path' contains directories with many files
and subdirs, especially if these directories are mounted net-drives \(\"many\"
means here something > 1000, dependent of the speed of the net-connection and
the machine). Or if it contains remote-source-paths which means paths in the
sense of tramp, ange-ftp or efs. For these directories actualizing the
sources- and/or directories- buffer of ECB \(if displayed in current layout!)
can slow down dramatically so a caching increases speed a lot.

The value of this option is a list where the each element is a cons-cell and
looks like:
  \(<dir-regexp> . <filenumber threshold>)
<dir-regexp>: Regular expression a directory must match to be cached.
<filenumber threshold>: Number of directory contents must exceed this number.

A directory will only be cached if and only if the directory-name matches
one regexp of this option and its content-number exceeds the related
threshold AND the directory-name does not match and regexp of
`ecb-cache-directory-contents-not'!

The cache entry for a certain directory will be refreshed and actualized only
by using the POWER-click \(see `ecb-primary-secondary-mouse-buttons') in the
directories-buffer of ECB.

Default-value: ECB caches the contents of all remote directories regardless of
the size and all other directories if more than 50 entries are contained.

Examples:

An entry \(\"/usr/home/john_smith/bigdir*\" . 1000) means the contents of
every subdirectory of the home-directory of John Smith will be cached if the
directory contains more than 1000 entries and its name begins with \"bigdir\".

An entry \(\".*\" . 1000) caches every directory which has more than 1000
entries.

An entry \(\"^/\\\\\(\[^:/]*@\\\\)?\\\\\(\[^@:/]*\\\\):.*\" . 0) caches every
remote \(in the sense of tramp, ange-ftp or efs) directory regardless of the
number of entries.

Please note: If you want your home-dir being cached then you MUST NOT use
\"~\" because ECB tries always to match full path-names!"
  :group 'ecb-directories
  :group 'ecb-most-important
  :type `(repeat (cons (regexp :tag "Directory-regexp")
                       (integer :tag "Filenumber threshold" :value 1000))))


(defcustom ecb-cache-directory-contents-not nil
  "*Do not cache the contents of certain directories.
The value of this option is a list where the each element is a regular
expression a directory must match if it should not being cached.

If a directory-name matches at least one of the regexps of this option the
directory-contents will never being cached. See `ecb-cache-directory-contents'
to see when a directory will be cached.

This option can be useful when normally all directories with a certain amount
of content \(files and subdirs) should be cached but some special directories
not. This can be achieved by:
- setting `ecb-cache-directory-contents' to \(\".*\" . 500): Caches all
  directories with more then 500 entries
- setting `ecb-cache-directory-contents-not' to a value which matches these
  directories which should not being cached \(e.g. \(\"/usr/home/john_smith\")
  excludes the HOME-directory of John Smith from being cached).

Please note: If you want your home-dir exclude from being cached then you MUST
NOT use \"~\" because ECB tries always to match full path-names!"
  :group 'ecb-directories
  :type `(repeat (regexp :tag "Directory-regexp")))

(defcustom ecb-ping-program "ping"
  "Program to send network test packets to a host.
See also `ecb-ping-options'."
  :group 'ecb-directories
  :type  'string)

(defcustom ecb-ping-options
  (if (eq system-type 'windows-nt)
      (list "-n" "1")
    (list "-c" "1"))
  "List of options for the ping program.
These options can be used to limit how many ICMP packets are emitted. Ping is
used to test if a remote host of a remote path \(e.g. a tramp-, ange-ftp- or
efs-path) is accessible. See also `ecb-ping-program'."
  :group 'ecb-directories
  :type  '(repeat string))

(defcustom ecb-host-accessible-check-valid-time nil
  "Time in seconds a cached accessible-state of a remote host is valid.
This option is a list where each element specifies how long for a certain
remote host the cached ping-state \(i.e. if the host is accessible or not)
should be valid. During this time-intervall ECB pings such a remote host only
once, all other checks use the cached value of that real check. But it the
cached value is older than the value of this option ECB will ping again.

Per default ECB discards after 1 minute the cached ping-state of each remote
host. But if you are sure that a certain remote host is always accessible
\(i.e. means in consequence that you are always online when working with ECB
and remote-paths) then add an entry to this option with a high valid-interval.

Examples: An entry \(\".*sourceforge.*\" . 3600) ensures that all remote hosts
machting the string \"sourceforge\" will only once pinged during one hour. Or
\(\".*\" . 300) would ensure that every remote host would be pinged only once
during 5 minutes."
  :group 'ecb-directories
  :type '(repeat (cons (regexp :tag "Remote host regexp")
                       (integer :tag "Valid interval"))))

(defcustom ecb-prescan-directories-for-emptyness 'unless-remote
  "*Prescan directories for emptyness.
ECB does this so directories are displayed as empty in the directories-buffer
even without user-interaction \(i.e. in previous ECB-versions the emptyness of
a directory has been first checked when the user has clicked onto a
directory). ECB optimizes this check as best as possible but if a directory
contains a lot of subdirectories which contain in turn a lot of entries, then
expanding such a directory or selecting it would take of course more time as
without this check - at least at the first time \(all following selects of a
directory uses the cached information if its subdirectories are empty or not).
Therefore ECB performs this check stealthy \(see `ecb-stealthy-tasks-delay')
so normally there should no performance-decrease or additional waiting-time
for the user. There is one exception: For remote directories \(in the sense of
tramp, ange-ftp, or efs) this check can descrease performance even if
performed stealthy and interruptable. Therefore this option offers three
possible settings:

  t: Switch on this feature

  'unless-remote: Switch on this feature but not for remote directories. The
  term \"remote\" means here directories which are used via tramp, ange-ftp or
  efs. So mounted directories are counted not as remote directories here even
  if such a directory is maybe hosted on a remote machine. But normally only
  directories in a LAN are mounted so there should be no performance-problems
  with such mounted directories.

  nil: Switch off this feature completely.

The option `ecb-prescan-directories-exclude-regexps' offers are more fine
granularity to exclude certain directories from this prescan."
  :group 'ecb-directories
  :group 'ecb-most-important
  :type '(radio (const :tag "Switch on" :value t)
                (const :tag "Switch off for remote directories" :value unless-remote)
                (const :tag "Switch off completely" :value nil)))

(defcustom ecb-prescan-directories-exclude-regexps nil
  "*Which directories should be excluded from the empty-prescan.
If a directory matches any of the regexps of this option it will not be
prescanned for emptyness - This option takes only effect if
`ecb-prescan-directories-for-emptyness' is not nil."
  :group 'ecb-directories
  :type '(repeat (regexp :tag "Directory-regexp")))

(defsubst ecb-directory-should-prescanned-p (dir)
  "Return not nil if DIR should be prescanned for emptyness.
The check is performed according to the settings in the options
`ecb-prescan-directories-for-emptyness' and
`ecb-prescan-directories-exclude-regexps'."
  (and (or (equal t ecb-prescan-directories-for-emptyness)
           (and (equal 'unless-remote ecb-prescan-directories-for-emptyness)
                (not (ecb-remote-path dir))))
       (not (ecb-match-regexp-list dir ecb-prescan-directories-exclude-regexps))))

(defcustom ecb-after-directory-change-hook nil
  "*Hook which run directly after the selected directory has changed.
This means not onyl after a click onto a directory in the directory-window of
ECB but it means this hook runs always when the current directory changes
regardless of the trigger of this change. So for example it runs also when you
just switches from one buffer to another via `switch-to-buffer' or
`switch-to-buffer-other-window' and the directory of these filebuffers is
different but only when auto-synchronizing of the ECB-windows is on (see
`ecb-window-sync'). It runs not when switching between buffers and the
associated files reside in the same directory.

Each function added to this hook will be called with two arguments: The
directory which was current _before_ the directory-change-trigger and the
directory which was now the current \(i.e. after the trigger).

Example: If you switch from a filebuffer \"~/.emacs\" to a filebuffer
\"/tmp/test.txt\" then the functions of this hook will be called with the
two arguments \"~\" and \"/tmp\"."
  :group 'ecb-directories
  :type 'hook)

(defcustom ecb-sources-perform-read-only-check 'unless-remote
  "*Check if source-items in the tree-buffers are read-only.
If a sourcefile is read-only then it will be displayed with that face set in
the option `ecb-source-read-only-face'.

Because this check can be take some time if files are used via a mounted
net-drive ECB performs this check stealthy \(see `ecb-stealthy-tasks-delay')
so normally there should no performance-decrease or additional waiting-time
for the user. But to get sure this option offers three choices: t,
'unless-remote and nil. See `ecb-prescan-directories-for-emptyness' for an
explanation for these three choices.

The option `ecb-read-only-check-exclude-regexps' offers are more fine
granularity to exclude the sources of certain directories from the read-only
state-check."
  :group 'ecb-sources
  :group 'ecb-directories
  :group 'ecb-most-important
  :type '(radio (const :tag "Switch on" :value t)
                (const :tag "Switch off for remote directories" :value unless-remote)
                (const :tag "Switch off completely" :value nil)))

(defcustom ecb-read-only-check-exclude-regexps nil
  "*Which directories should be excluded from the sources-read-only-check.
If a directory matches any of the regexps of this option their sources will
not be checked if they are writable - This option takes only effect if
`ecb-sources-perform-read-only-check' is not nil."
  :group 'ecb-sources
  :group 'ecb-directories
  :type '(repeat (regexp :tag "Directory-regexp")))

(defsubst ecb-sources-read-only-check-p (dir)
  "Return not nil if the sources of DIR should be checked for read-only-state.
The check is performed according to the settings in the options
`ecb-sources-perform-read-only-check' and
`ecb-read-only-check-exclude-regexps'."
  (and (or (equal t ecb-sources-perform-read-only-check)
           (and (equal 'unless-remote ecb-sources-perform-read-only-check)
                (not (ecb-remote-path dir))))
       (not (ecb-match-regexp-list dir ecb-read-only-check-exclude-regexps))))

(defcustom ecb-directories-buffer-name " *ECB Directories*"
  "*Name of the ECB directory buffer.
Because it is not a normal buffer for editing you should enclose the name with
stars, e.g. \"*ECB Directories*\".

If it is necessary for you you can get emacs-lisp access to the buffer-object of
the ECB-directory-buffer by this name, e.g. by a call of `set-buffer'.

Changes for this option at runtime will take affect only after deactivating and
then activating ECB again!"
  :group 'ecb-directories
  :type 'string)


(defcustom ecb-excluded-directories-regexps '("^\\(CVS\\|\\.[^xX]*\\)$")
  "*Directories that should not be included in the directories list.
The value of this variable should be a list of regular expressions."
  :group 'ecb-directories
  :type '(repeat (regexp :tag "Directory-regexp")))

(defsubst ecb-check-dir-exclude (dir)
  (ecb-match-regexp-list dir ecb-excluded-directories-regexps))

(defcustom ecb-auto-expand-directory-tree 'best
  "*Automatically expand the directory tree to the current source file.
There are three options:
- best: Expand the best-matching source-path
- first: Expand the first matching source-path
- nil: Do not automatically expand the directory tree."
  :group 'ecb-directories
  :type '(radio (const :tag "Best matching"
                       :value best)
                (const :tag "First matching"
                       :value first)
                (const :tag "No auto. expand"
                       :value nil)))


(defcustom ecb-sources-buffer-name " *ECB Sources*"
  "*Name of the ECB sources buffer.
Because it is not a normal buffer for editing you should enclose the name with
stars, e.g. \"*ECB Sources*\".

If it is necessary for you you can get emacs-lisp access to the buffer-object of
the ECB-sources-buffer by this name, e.g. by a call of `set-buffer'.

Changes for this option at runtime will take affect only after deactivating and
then activating ECB again!"
  :group 'ecb-sources
  :type 'string)


(defcustom ecb-sources-exclude-cvsignore nil
  "*Specify if files contained in a .cvsignore should be excluded.
Value is a list of regular expressions or nil. If you want to exclude files
listed in a .cvsignore-file from being displayed in the ecb-sources-buffer
then specify a regexp for such a directory.

If you want to exclude the contents of .cvsignore-files for every directory
then you should add one regexp \".*\" which matches every directory.

If you never want to exclude the contents of .cvsignore-files then set this
option to nil. This is the default."
  :group 'ecb-sources
  :group 'ecb-directories
  :type '(repeat (regexp :tag "Directory-regexp")))

(defcustom ecb-source-file-regexps
  '((".*" . (("\\(^\\(\\.\\|#\\)\\|\\(~$\\|\\.\\(elc\\|obj\\|o\\|class\\|lib\\|dll\\|a\\|so\\|cache\\)$\\)\\)")
             ("^\\.\\(emacs\\|gnus\\)$"))))
  "*Specifies which files are shown as source files.
This is done on directory-base, which means for each directory-regexp the
files to display can be specified. If more than one directory-regexp matches
the current selected directory then always the first one \(and its related
file-exclude/include-regexps) is used! If no directory-regexp matches then all
files are displayed for the currently selected directory.

Important note: It is recommended that the *LAST* element of this list should
contain an always matching directory-regexp \(\".*\")!

So the value of this option is a list of cons-cells where the car is a
directory regexp and the cdr is a 2 element list where the first element is a
list of exclude regexps and the second element is a list of include regexps. A
file is displayed in the sources-buffer of ECB iff: The file does not match
any of the exclude regexps OR the file matches at least one of the include
regexps.

But regardless of the value of this option a file F is never displayed in the
sources-buffer if the directory matches `ecb-sources-exclude-cvsignore'
and the directory contains a file .cvsignore which contains F as an entry!

There are three predefined and useful combinations of an exclude and include
regexp:
- All files
- All, but no backup, object, lib or ini-files \(except .emacs and .gnus). This
  means all files except those starting with \".\", \"#\" or ending with
  \"~\", \".elc\", \".obj\", \".o\", \".lib\", \".dll\", \".a\", \".so\".
  (but including .emacs and .gnus)
- Common source file types (.c, .java etc.)
In addition to these predefined values a custom exclude and include
combination can be defined. Here each list must at least contain one regexp -
this can be a least the empty regexp \"\"!

Tips for the directory- and file-regexps: \"$^\" matches no files/directories,
\".*\" matches all files/directories."
  :group 'ecb-sources
  :group 'ecb-most-important
  :type '(repeat (cons :tag "Directory file-spec"
                       (regexp :tag "Directory regexp")
                       (choice :tag "Files to display"
                               :menu-tag "Files to display"
                               (const :tag "All files"
                                      :value (("") ("")))
                               (const :tag "All, but no backups, objects, etc..."
                                      :value (("\\(^\\(\\.\\|#\\)\\|\\(~$\\|\\.\\(elc\\|obj\\|o\\|class\\|lib\\|dll\\|a\\|so\\|cache\\)$\\)\\)") ("^\\.\\(x?emacs\\|gnus\\)$")))
                               (const :tag "Common source file types"
                                      :value (("") ("\\(\\(M\\|m\\)akefile\\|.*\\.\\(java\\|el\\|c\\|cc\\|h\\|hh\\|txt\\|html\\|texi\\|info\\|bnf\\)\\)$")))
                               (list :tag "Custom"
                                     (repeat (regexp :tag "Exclude regexp"
                                                     :value ""))
                                     (repeat (regexp :tag "Include regexp"
                                                     :value "")))))))


(defcustom ecb-show-source-file-extension t
  "*Show the file extension of source files."
  :group 'ecb-sources
  :type 'boolean)

(defcustom ecb-sources-sort-method 'name
  "*Defines how the source files are sorted.
- 'name: Sorting by name.
- 'extension: Sorting first by extension and then by name.
- nil: No sorting, means source files are displayed in the sequence returned by
  `directory-files' \(called without sorting).
See also `ecb-sources-sort-ignore-case'."
  :group 'ecb-sources
  :type '(radio (const :tag "By name"
                       :value name)
                (const :tag "By extension"
                       :value extension)
                (const :tag "No sorting"
                       :value nil)))

(defcustom ecb-sources-sort-ignore-case t
  "*Ignore case for sorting the source-files of the Sources-buffer.
See also `ecb-sources-sort-method'."
  :group 'ecb-sources
  :type 'boolean)

(defcustom ecb-history-buffer-name " *ECB History*"
  "*Name of the ECB history buffer.
Because it is not a normal buffer for editing you should enclose the name with
stars, e.g. \"*ECB History*\".

If it is necessary for you you can get emacs-lisp access to the buffer-object of
the ECB-history-buffer by this name, e.g. by a call of `set-buffer'.

Changes for this option at runtime will take affect only after deactivating and
then activating ECB again!"
  :group 'ecb-history
  :type 'string)

(defcustom ecb-history-exclude-file-regexps '("TAGS$" "semantic\\.cache$")
  "*List of regexps which exclude source-files from being historized. Be aware
that each always full filenames \(ie. incl. full path) are matched against
these regexps! Therefore be carefore with regexps beginning with ^!"
  :group 'ecb-history
  :type '(repeat (regexp :tag "Source-regexp")))

(defsubst ecb-check-filename-for-history-exclude (filename)
  (ecb-match-regexp-list filename ecb-history-exclude-file-regexps))

(defcustom ecb-history-sort-method 'name
  "*Defines how the entries in the history-buffer are sorted.
- 'name: Sorting by name.
- 'extension: Sorting first by extension and then by name.
- nil: No sorting, means the most recently used buffers are on the top of the
       history and the seldom used buffers at the bottom.
See also `ecb-history-sort-ignore-case'."
  :group 'ecb-history
  :type '(radio (const :tag "By name"
                       :value name)
                (const :tag "By extension"
                       :value extension)
                (const :tag "No sorting"
                       :value nil)))

(defcustom ecb-history-sort-ignore-case t
  "*Ignore case for sorting the history-entries.
See also `ecb-history-sort-method'."
  :group 'ecb-history
  :type 'boolean)

(defcustom ecb-kill-buffer-clears-history nil
  "*Define if `kill-buffer' should also clear the history.
There are three options:
- auto: Removes automatically the corresponding history-entry after the buffer
  has been killed.
- ask: Asks, if the history-entry should be removed after the kill.
- nil: `kill-buffer' does not affect the history \(this is the default)."
  :group 'ecb-history
  :type '(radio (const :tag "Remove history entry automatically"
                       :value auto)
                (const :tag "Ask if history entry should be removed"
                       :value ask)
                (const :tag "Do not clear the history"
                       :value nil)))


(defcustom ecb-history-item-name 'buffer-name
  "*The name to use for items in the history buffer."
  :group 'ecb-history
  :type '(radio (const :tag "Buffer name"
                       :value buffer-name)
                (const :tag "File name"
                       :value file-name)))

(defcustom ecb-directories-menu-user-extension
  '(("Version Control"
     (ecb-dir-popup-cvs-status "CVS Status" )
     (ecb-dir-popup-cvs-examine "CVS Examine")
     (ecb-dir-popup-cvs-update "CVS Update")))
  "*Static user extensions for the popup-menu of the directories buffer.
Value is a list of elements of the following type: Each element defines a new
menu-entry and is either:

a) Menu-command: A list containing two sub-elements, whereas the first is the
   function \(a function symbol) being called if the menu-entry is selected
   and the second is the name of the menu-entry.
b) Separator: A one-element-list and the element is the string \"---\": Then a
   non-selectable menu-separator is displayed.
c) Submenu: A list where the first element is the title of the submenu
   displayed in the main-menu and all other elements are either menu-commands
   \(see a) or separators \(see b) or another submenu \(see c). This allows
   deep nested menu-submenu-structures. Currently a level of 4 is allowed but
   in general there could be an infinite depth of nesting but it makes no
   sense - if possible at all - to define infinite nested defcustom-types. So
   there is a limit of 4 levels but tis is not a hard limit: Just increase the
   value of the `ecb-max-submenu-depth' *BEFORE* first loading ECB!

The function of a menu-command must follow the following guidelines: Such a
function must be defined with the macro `tree-buffer-defpopup-command! This
macro defines a new popup-command whereas the newly defined command gets one
argument NODE. See the docstring of `tree-buffer-defpopup-command' for further
details.

Example for the definition of such a popupmenu-command:

\(tree-buffer-defpopup-command ecb-my-special-dir-popup-function
  \"Prints the name of the directory of the node under point.\"
  \(let \(\(node-data=dir \(tree-node-get-data node)))
     \(message \"Dir under node: %s\" node-data=dir)))

Per default the static user-extensions are added at the beginning of the
built-in menu-entries of `ecb-directories-menu' but the whole menu can be
re-arranged with `ecb-directories-menu-sorter'.

These menu-extensions are static. A dynamic menu-extension can be achieved via
`ecb-directories-menu-user-extension-function'."
  :group 'ecb-directories
  :type (ecb-create-menu-user-ext-type 1 ecb-max-submenu-depth))

(defcustom ecb-directories-menu-user-extension-function nil
  "*Dynamic user extensions for the popup-menu of the directories buffer.
A function which has to return a list in the same format like the option
`ecb-directories-menu-user-extension'. This function is called when the user
opens the popup-menu for the directories buffer.

Per default the dynamic user-extensions are added in front of the static
extensions of `ecb-directories-menu-user-extension' but the whole menu can be
re-arranged with `ecb-directories-menu-sorter'."
  :group 'ecb-directories
  :type 'function)

(defcustom ecb-sources-menu-user-extension
  '(("Version control"
     (ecb-file-popup-ediff-revision "Ediff against revision")
     ("---")
     (ecb-file-popup-vc-next-action "Check In/Out")
     (ecb-file-popup-vc-log "Revision history")
     (ecb-file-popup-vc-annotate "Annotate")
     (ecb-file-popup-vc-diff "Diff against last version")
     ("---")
     (ecb-file-popup-vc-refresh-file "Recompute state for file")
     (ecb-file-popup-vc-refresh-dir "Recompute state for whole dir")))
  "*Static user extensions for the popup-menu of the sources buffer.
For further explanations see `ecb-directories-menu-user-extension'.

The node-argument of a menu-function contains as data the filename of the
source for which the popup-menu has been opened.

Per default the static user-extensions are added at the beginning of the
built-in menu-entries of `ecb-sources-menu' but the whole menu can be
re-arranged with `ecb-sources-menu-sorter'."
  :group 'ecb-sources
  :type (ecb-create-menu-user-ext-type 1 ecb-max-submenu-depth))

(defcustom ecb-sources-menu-user-extension-function nil
  "*Dynamic user extensions for the popup-menu of the sources buffer.
A function which has to return a list in the same format like the option
`ecb-sources-menu-user-extension'. This function is called when the user
opens the popup-menu for the sources buffer.

Per default the dynamic user-extensions are added in front of the static
extensions of `ecb-sources-menu-user-extension' but the whole menu can be
re-arranged with `ecb-sources-menu-sorter'."
  :group 'ecb-sources
  :type 'function)

(defcustom ecb-history-menu-user-extension
  '(("Version control"
     (ecb-file-popup-ediff-revision "Ediff against revision")
     ("---")
     (ecb-file-popup-vc-next-action "Check In/Out")
     (ecb-file-popup-vc-log "Revision history")
     (ecb-file-popup-vc-annotate "Annotate")
     (ecb-file-popup-vc-diff "Diff against last version")
     ("---")
     (ecb-file-popup-vc-refresh-file "Recompute state for file")
     (ecb-file-popup-vc-refresh-all-files "Recompute state for whole history")))
      "*Static user extensions for the popup-menu of the history buffer.
For further explanations see `ecb-directories-menu-user-extension'.

The node-argument of a menu-function contains as data the filename of the
source for which the popup-menu has been opened.

Per default the static user-extensions are added at the beginning of the
built-in menu-entries of `ecb-history-menu' but the whole menu can be
re-arranged with `ecb-history-menu-sorter'."
  :group 'ecb-history
  :type (ecb-create-menu-user-ext-type 1 ecb-max-submenu-depth))

(defcustom ecb-history-menu-user-extension-function nil
  "*Dynamic user extensions for the popup-menu of the history buffer.
A function which has to return a list in the same format like the option
`ecb-history-menu-user-extension'. This function is called when the user
opens the popup-menu for the history buffer.

Per default the dynamic user-extensions are added in front of the static
extensions of `ecb-history-menu-user-extension' but the whole menu can be
re-arranged with `ecb-history-menu-sorter'."
  :group 'ecb-history
  :type 'function)

(defcustom ecb-directories-menu-sorter nil
  "*Function which re-sorts the menu-entries of the directories buffer.
If a function then this function is called to re-arrange the menu-entries of
the combined menu-entries of the user-menu-extensions of
`ecb-directories-menu-user-extension' and the built-in-menu
`ecb-directories-menu'. If nil then no special sorting will be done and the
user-extensions are placed in front of the built-in-entries.

The function get one argument, a list of menu-entries. For the format of this
argument see `ecb-directories-menu-user-extension'. The function must return a
new list in the same format. Of course this function can not only re-arrange
the entries but also delete entries or add new entries."
  :group 'ecb-directories
  :type '(choice :tag "Menu-sorter" :menu-tag "Menu-sorter"
                 (const :tag "No special sorting" :value nil)
                 (function :tag "Sort-function" :value identity)))


(defcustom ecb-sources-menu-sorter nil
  "*Function which re-sorts the menu-entries of the directories buffer.
If a function then this function is called to sort the menu-entries of the
combined menu-entries of the user-menu-extensions of
`ecb-sources-menu-user-extension' and the built-in-menu
`ecb-sources-menu'. If nil then no special sorting will be done and the
user-extensions are placed in front of the built-in-entries.

For the guidelines for such a sorter-function see
`ecb-directories-menu-sorter'."
  :group 'ecb-sources
  :type '(choice :tag "Menu-sorter" :menu-tag "Menu-sorter"
                 (const :tag "No special sorting" :value nil)
                 (function :tag "Sort-function" :value identity)))


(defcustom ecb-history-menu-sorter nil
  "*Function which re-sorts the menu-entries of the directories buffer.
If a function then this function is called to sort the menu-entries of the
combined menu-entries of the user-menu-extensions of
`ecb-history-menu-user-extension' and the built-in-menu
`ecb-history-menu'. If nil then no special sorting will be done and the
user-extensions are placed in front of the built-in-entries.

For the guidelines for such a sorter-function see
`ecb-directories-menu-sorter'."
  :group 'ecb-history
  :type '(choice :tag "Menu-sorter" :menu-tag "Menu-sorter"
                 (const :tag "No special sorting" :value nil)
                 (function :tag "Sort-function" :value identity)))


(defcustom ecb-directories-buffer-after-create-hook nil
  "*Local hook running after the creation of the directories-buffer.
Every function of this hook is called once without arguments direct after
creating the directories-buffer of ECB and it's local key-map. So for example a
function could be added which performs calls of `local-set-key' to define new
key-bindings only for the directories-buffer of ECB.

The following keys must not be rebind in the directories-buffer:
<F2>, <F3> and <F4>"
  :group 'ecb-directories
  :type 'hook)


(defcustom ecb-sources-buffer-after-create-hook nil
  "*Local hook running after the creation of the sources-buffer.
Every function of this hook is called once without arguments direct after
creating the sources-buffer of ECB and it's local key-map. So for example a
function could be added which performs calls of `local-set-key' to define new
key-bindings only for the sources-buffer of ECB."
  :group 'ecb-sources
  :type 'hook)


(defcustom ecb-history-buffer-after-create-hook nil
  "*Local hook running after the creation of the history-buffer.
Every function of this hook is called once without arguments direct after
creating the history-buffer of ECB and it's local key-map. So for example a
function could be added which performs calls of `local-set-key' to define new
key-bindings only for the history-buffer of ECB."
  :group 'ecb-history
  :type 'hook)

(defcustom ecb-vc-enable-support 'unless-remote
  "*Enable support for version-control \(VC) systems.
If on then in the directories-buffer \(if the value of the option
`ecb-show-sources-in-directories-buffer' is on for current layout), the
sources-buffer and the history-buffer all file-items are displayed with an
appropriate icon in front of the item-name to indicate the VC-state of this
item. If off then no version-control-state checking is done.

Because this check can be take some time if files are managed by a not local
Version-control-server ECB performs this check stealthy \(see
`ecb-stealthy-tasks-delay') so normally there should no performance-decrease
or additional waiting-time for the user. But to get sure this option offers
three choices: t, 'unless-remote and nil. See the option
`ecb-prescan-directories-for-emptyness' for an explanation for these three
choices.

The option `ecb-vc-directory-exclude-regexps' offers are more fine granularity
to exclude the sources of certain directories from the VC-state-check.

See `ecb-vc-supported-backends' how to customize the VC-support itself."
  :group 'ecb-version-control
  :group 'ecb-sources
  :group 'ecb-most-important
  :type '(radio (const :tag "Switch on" :value t)
                (const :tag "Switch off for remote directories" :value unless-remote)
                (const :tag "Switch off completely" :value nil)))

(defcustom ecb-vc-directory-exclude-regexps nil
  "*Which directories should be excluded from VC-state-check.
If a directory matches any of the regexps of this option the VC-state of its
sources will not be checked - This option takes only effect if
`ecb-vc-enable-support' is not nil."
  :group 'ecb-version-control
  :group 'ecb-sources
  :type '(repeat (regexp :tag "Directory-regexp")))

(defcustom ecb-vc-xemacs-exclude-remote-cvs-repository
  (if ecb-running-xemacs t nil)
  "*Exclude directories with a remote cvs-repository from VC-check.
This option takes only effect for XEmacs and is needed cause of the outdated
VC-package of XEmacs which offers no heuristic state-checking and also no
option `vc-cvs-stay-local'. So this option takes only effect if
`vc-cvs-stay-local' is not avaiable. In this case ECB treats directories which
are managed by CVS but have a remote repository as if the directory would be
not managed by CVS \(so the files are not checked for their VC-state). This si
done to avoid blocking XEmacs when running full cvs-commands \(e.g. \"cvs
status\") over the net.

Note: When ECB can find the option `vc-cvs-stay-local' then this option will
automatically take no effect regardless which Emacs-version is used."
  :group 'ecb-version-control
  :group 'ecb-sources
  :type 'boolean)

(defsubst ecb-vc-directory-should-be-checked-p (dir)
  "Return not nil if the sources of DIR should be checked for VC-state.
The check is performed according to the settings in the options
`ecb-vc-enable-support' and `ecb-vc-directory-should-be-checked-p'."
  (and (or (equal t ecb-vc-enable-support)
           (and (equal 'unless-remote ecb-vc-enable-support)
                (not (ecb-remote-path dir))))
       (not (ecb-match-regexp-list dir ecb-vc-directory-exclude-regexps))))

(defcustom ecb-vc-state-mapping '((up-to-date       . up-to-date)
                                  (edited           . edited)
                                  (locally-modified . edited)
                                  (needs-patch      . needs-patch)
                                  (needs-checkout   . needs-patch)
                                  (needs-merge      . needs-merge)
                                  (unlocked-changes . unlocked-changes)
                                  (added            . added)
                                  (locally-added    . added)
                                  (ignored          . ignored)
                                  (unknown          . unknown))
  "*Mapping from VC-state-values of the backends to VC-state-values of ECB.
ECB understands the following state-values:

  'up-to-date        The working file is unmodified with respect to the
                     latest version on the current branch, and not locked.

  'edited            The working file has been locally edited by the user. If
                     locking is used for the file, this state means that
                     the current version is locked by the calling user.

  'needs-patch       The file has not been edited by the user, but there is
                     a more recent version on the current branch stored
                     in the master file.

  'needs-merge       The file has been edited by the user, and there is also
                     a more recent version on the current branch stored in
                     the master file. This state can only occur if locking
                     is not used for the file.

  'unlocked-changes  The current version of the working file is not locked,
                     but the working file has been changed with respect
                     to that version. This state can only occur for files
                     with locking\; it represents an erroneous condition that
                     should be resolved by the user.

  'added             The working file has already been added/registered to the
                     VC-system but not yet commited.

  'ignored           The version-control-system ignores this file \(e.g.
                     because included in a .cvsignore-file in case of CVS).

  'unknown           The state of the file can not be retrieved\; probably the
                     file is not under a version-control-system.

All state-values a check-vc-state-function of `ecb-vc-supported-backends' can
return must have a mapping to one of the ECB-state-values listed above. If for
a certain backend-VC-state no mapping can be found then per default 'edited is
assumed!

The default value of this option maps already the possible returned
state-values of `ecb-vc-state', `vc-state' and `vc-recompute-state' \(both GNU
Emacs) and `vc-cvs-status' \(Xemacs) to the ECB-VC-state-values."
  :group 'ecb-version-control
  :group 'ecb-sources
  :initialize 'custom-initialize-default  
  :set (function (lambda (sym val)
                   (set sym val)
                   (ecb-vc-cache-clear)))
  :type '(repeat (cons (choice :tag "Backend VC-state"
                               :menu-tag "Backend VC-state"
                               (const :tag "up-to-date" :value up-to-date)
                               (const :tag "edited" :value edited)
                               (const :tag "locally-modified" :value locally-modified)
                               (const :tag "needs-patch" :value needs-patch)
                               (const :tag "needs-checkout" :value needs-checkout)
                               (const :tag "needs-merge" :value needs-merge)
                               (const :tag "unlocked-changes" :value unlocked-changes)
                               (const :tag "added" :value added)
                               (const :tag "locally-added" :value locally-added)
                               (const :tag "ignored" :value ignored)
                               (const :tag "unknown" :value unknown)
                               (symbol :tag "Other..."))
                       (choice :tag "ECB VC-state"
                               :menu-tag "ECB VC-state"
                               (const :tag "up-to-date" :value up-to-date)
                               (const :tag "edited" :value edited)
                               (const :tag "needs-patch" :value needs-patch)
                               (const :tag "needs-merge" :value needs-merge)
                               (const :tag "unlocked-changes" :value unlocked-changes)
                               (const :tag "added" :value added)
                               (const :tag "ignored" :value ignored)
                               (const :tag "unknown" :value unknown)))))

(defcustom ecb-vc-supported-backends
  (delq nil (if ecb-running-xemacs
                `((ecb-vc-dir-managed-by-CVS . vc-cvs-status))
              `((ecb-vc-dir-managed-by-CVS . ecb-vc-state)
                (ecb-vc-dir-managed-by-RCS . ecb-vc-state)
                (ecb-vc-dir-managed-by-SCCS . ecb-vc-state)
                (ecb-vc-dir-managed-by-SVN . ecb-vc-state))))
  "*Define how to to identify the VC-backend and how to check the state.
The value of this option is a list containing cons-cells where the car is a
function which is called to identify the VC-backend for a DIRECTORY and the
cdr is a function which is called to check the VC-state of the FILEs contained
in DIRECTORY.

Identify-backend-function: It gets a full directory-name as argument - always
without ending slash \(rsp. backslash for native Windows-XEmacs) - and has to
return a unique symbol for the VC-backend which manages that directory \(e.g.
'CVS for the CVS-system or 'RCS for the RCS-system) or nil if the file is not
managed by a version-control-system.

Check-vc-state-function: It gets a full filename \(ie. incl. the complete
directory-part) and has to return a symbol which indicates the VC-state of
that file. The possible returned values of such a check-vc-state-function have
to be mapped with `ecb-vc-state-mapping' to the allowed ECB-VC-state values.

ECB runs for a certain DIRECTORY all identify-backend-functions in that order
they are listed in this option. For the first which returns a value unequal
nil the associated check-state-function is used to retrieve the VC-state of
all sourcefiles in that DIRECTORY.

There is no need for the identify-backend-function or the
check-vc-state-function to cache any state because ECB automatically caches
internally all necessary informations for directories and files for best
possible performance.

To prepend ECB from checking the VC-state for any file set
`ecb-vc-enable-support' to nil.

Default value for GNU Emacs: Support for CVS, RCS, SCCS and Subversion \(for
the later one the most recent version of the VC-package incl. the vc-svn
library is needed). To identify the VC-backend the functions
`ecb-vc-managed-by-CVS', `ecb-vc-managed-by-RCS' rsp. `ecb-vc-managed-by-SCCS'
rsp. `ecb-vc-managed-by-SVN' are used. For all four backends the function
`ecb-vc-state' of the VC-package is used.

Default value for XEmacs: XEmacs contains only a quite outdated VC-package,
especially there is no backend-independent check-vc-state-function available
\(like `vc-state' for GNU Emacs). Only for CVS a check-vc-state-function is
available: `vc-cvs-status'. Therefore ECB adds per default only support for
CVS and uses `ecb-vc-managed-by-CVS' rsp. `vc-cvs-status'. But read the
documentation of `ecb-vc-dir-managed-by-CVS'!

Example for GNU Emacs: If `vc-recompute-state' \(to get real state-values not
only heuristic ones) should be used to check the state for CVS-managed files
and `vc-state' for all other backends then an element
\(ecb-vc-dir-managed-by-CVS . vc-recompute-state) should be added at the
beginning of this option."
  :group 'ecb-version-control
  :group 'ecb-sources
  :initialize 'custom-initialize-default  
  :set (function (lambda (sym val)
                   (set sym val)
                   (ecb-vc-cache-clear)))
  :type '(repeat (cons (symbol :tag "Identify-backend-function")
                       (symbol :tag "Check-state-function"))))

;; Klaus Berndl <klaus.berndl@sdm.de>: For XEmacs a function like the
;; following could be used to get always fresh state-values:

;; (defun ecb-vc-recompute-state (file)
;;   ;; Return the cvs status of FILE
;;   ;; (Status field in output of "cvs status")
;;   (vc-fetch-master-properties file)
;;   (vc-file-getprop file 'vc-cvs-status))

;;====================================================
;; Internals
;;====================================================

;; constants for the node-types
(defconst ecb-directories-nodetype-directory 0)
(defconst ecb-directories-nodetype-sourcefile 1)
(defconst ecb-directories-nodetype-sourcepath 2)
(defconst ecb-sources-nodetype-sourcefile 0)
(defconst ecb-history-nodetype-sourcefile 0)


(defvar ecb-path-selected-directory nil
  "Path to currently selected directory.")

(defvar ecb-path-selected-source nil
  "Path to currently selected source.")

;; accessors for the FILES-AND-SUBDIRS-cache

(defun ecb-files-and-subdirs-cache-add (dir cached-value)
  "Add the files and subdirs of DIR to the cache."
  (ecb-multicache-put-value 'ecb-filename-cache dir 'FILES-AND-SUBDIRS
                             cached-value))

(defun ecb-files-and-subdirs-cache-get (dir)
  "Get the files and subdirs of DIR from the cache. Nil if not cached."
  (ecb-multicache-get-value 'ecb-filename-cache dir 'FILES-AND-SUBDIRS))

(defun ecb-files-and-subdirs-cache-remove (dir)
  "Remove DIR from the cache."
  (ecb-multicache-clear-value 'ecb-filename-cache dir 'FILES-AND-SUBDIRS))

(defun ecb-files-and-subdirs-cache-clear ()
  "Clear the whole FILES-AND-SUBDIRS-cache."
  (ecb-multicache-clear-subcache 'ecb-filename-cache 'FILES-AND-SUBDIRS))

(defun ecb-files-and-subdirs-cache-dump (&optional no-nil-value)
  "Dump the whole FILES-AND-SUBDIRS-cache in another window. If NO-NIL-VALUE
is not nil then these cache-entries are not dumped. This command is not
intended for end-users of ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache
                                 'FILES-AND-SUBDIRS
                                 no-nil-value))
  
;; accessors for the EMPTY-DIR-P-cache

(defun ecb-directory-empty-cache-add (dir cached-value)
  "Add information if DIR is empty or not to the cache."
  (ecb-multicache-put-value 'ecb-filename-cache dir 'EMPTY-DIR-P
                             cached-value))

(defun ecb-directory-empty-cache-get (dir)
  "get information if DIR is empty or not from the cache."
  (ecb-multicache-get-value 'ecb-filename-cache dir 'EMPTY-DIR-P))

(defun ecb-directory-empty-cache-remove (dir)
  "Remove DIR from the EMPTY-DIR-P-cache."
  (ecb-multicache-clear-value 'ecb-filename-cache dir 'EMPTY-DIR-P))

(defun ecb-directory-empty-cache-remove-all (dir)
  "Remove DIR and all its suddirs from the EMPTY-DIR-P-cache."
  (ecb-directory-empty-cache-remove dir)
  ;; now we remove the subdirs
  (save-match-data
    (ecb-multicache-mapsubcache
     'ecb-filename-cache 'EMPTY-DIR-P
     (function (lambda (key old-value)
                 (if (string-match (concat "^"
                                           (regexp-quote dir)
                                           ".+")
                                   key)
                     ;; the directory-key matches DIR so its a cache
                     ;; subdirectory of DIR so we return nil ==> in fact we
                     ;; remove this subdir from the empty-dir-p-cache
                     nil
                   ;; the directory-key doesn't match DIR so we just return
                   ;; the old-value, which means in fact that nothing changes
                   old-value))))))

(defun ecb-directory-empty-cache-clear ()
  "Clear the whole EMPTY-DIR-P-cache."
  (ecb-multicache-clear-subcache 'ecb-filename-cache 'EMPTY-DIR-P))

(defun ecb-directory-empty-cache-dump (&optional no-nil-value)
  "Dump the whole EMPTY-DIR-P-cache. If NO-NIL-VALUE is not nil then these
cache-entries are not dumped. This command is not intended for end-users of
ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache
                                 'EMPTY-DIR-P no-nil-value))


;; accessors for the SOURCES-cache

(defun ecb-sources-cache-remove (dir)
  "Remove the cache-entry for DIR from the cache."
  (ecb-multicache-clear-value 'ecb-filename-cache dir 'SOURCES))

(defun ecb-sources-cache-add-full (dir cache-elem-full)
  "Add the full sources-cache CACHE-ELEM-FULL for DIR to the cache. If there
is already a full cache-entry then replace it. CACHE-ELEM-FULL has to be a
list as returned by `ecb-sources-cache-get-full'."
  (ecb-multicache-apply-to-value
   'ecb-filename-cache dir 'SOURCES
   (function (lambda (old-cached-value)
               (if (consp old-cached-value)
                   (progn
                     (setcar old-cached-value cache-elem-full)
                     old-cached-value)
                 (cons cache-elem-full nil))))))

(defun ecb-sources-cache-add-filtered (dir cache-elem-filtered)
  "Add the filtered sources-cache CACHE-ELEM-FILTERED for DIR to the cache. If
there is already a filtered cache-entry then replace it. CACHE-ELEM-FILTERED
has to be a list as returned by `ecb-sources-cache-get-filtered'."
  (ecb-multicache-apply-to-value
   'ecb-filename-cache dir 'SOURCES
   (function (lambda (old-cached-value)
               (if (consp old-cached-value)
                   (progn
                     (setcdr old-cached-value cache-elem-filtered)
                     old-cached-value)
                 (cons nil cache-elem-filtered))))))

(defun ecb-sources-cache-get-full (dir)
  "Return the full value of a cached-directory DIR, means the 3-element-list
\(tree-buffer-root, tree-buffer-nodes, sources-buffer-string). If no
cache-entry for DIR is available then nil is returned."
  (car (ecb-multicache-get-value 'ecb-filename-cache dir 'SOURCES)))

(defun ecb-sources-cache-get-filtered (dir)
  "Return the filtered value of a cached-directory DIR, means the
4-element-list \(tree-buffer-root, tree-buffer-nodes, sources-buffer-string,
filter-regexp). If no cache-entry for DIR is available then nil is returned."
  (cdr (ecb-multicache-get-value 'ecb-filename-cache dir 'SOURCES)))

(defun ecb-sources-cache-clear ()
  "Clear the whole SOURCES-cache."
  (ecb-multicache-clear-subcache 'ecb-filename-cache 'SOURCES))

(defun ecb-sources-cache-dump (&optional no-nil-value)
  "Dump the whole SOURCES-cache. If NO-NIL-VALUE is not nil then these
cache-entries are not dumped. This command is not intended for end-users of
ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache 'SOURCES no-nil-value))

;; accessors for the VC-cache

(defun ecb-vc-cache-add-file (file state checked-buffer-names)
  (ecb-multicache-put-value 'ecb-filename-cache file 'VC
                            (list state
                                  (ecb-subseq (current-time) 0 2)
                                  checked-buffer-names))
  state)

(defun ecb-vc-cache-add-dir (dir backend)
  (ecb-multicache-put-value 'ecb-filename-cache dir 'VC backend)
  backend)

(defun ecb-vc-cache-get (file)
  (ecb-multicache-get-value 'ecb-filename-cache file 'VC))

(defun ecb-vc-cache-remove (file)
  "Remove FILE from the VC-cache."
  (ecb-multicache-clear-value 'ecb-filename-cache file 'VC))

(defun ecb-vc-cache-remove-files-of-dir (dir)
  "Remove all files contained in DIR from the VC-cache."
  (let* ((dir-sep-string (ecb-directory-sep-string dir))
         (regexp (concat "^"
                         (regexp-quote dir)
                         (regexp-quote dir-sep-string)
                         "[^"
                         dir-sep-string
                         "]+$")))
    (save-match-data
      (ecb-multicache-mapsubcache
       'ecb-filename-cache 'VC
       (function (lambda (key old-value)
                   (if (and old-value
                            (string-match regexp key))
                       ;; the filename-key has a VC-cache value and matches the
                       ;; regexp above so its a cached file of DIR so we return
                       ;; nil ==> in fact we remove this file from the VC-cache
                       nil
                     ;; the filename-key doesn't match the regexp above so we
                     ;; just return the old-value, which means in fact that
                     ;; nothing changes
                     old-value)))))))


(defun ecb-vc-cache-clear ()
  "Clear the whole VC-cache."
  (ecb-multicache-clear-subcache 'ecb-filename-cache 'VC))

(defun ecb-vc-cache-dump (&optional no-nil-value)
  "Dump the whole VC-cache. If NO-NIL-VALUE is not nil then these
cache-entries are not dumped. This command is not intended for end-users of
ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache 'VC no-nil-value))

;; accessors for the REMOTE-PATH cache

(defun ecb-remote-path-cache-add (path remote-path)
  "Add the value of REMOTE-PATH for PATH to the REMOTE-PATH-cache."
  (ecb-multicache-put-value 'ecb-filename-cache path 'REMOTE-PATH
                            remote-path))

(defun ecb-remote-path-cache-get (path)
  "Return the cached value for PATH from the REMOTE-PATH-cache."
  (ecb-multicache-get-value 'ecb-filename-cache path 'REMOTE-PATH))

(defun ecb-remote-path-cache-dump (&optional no-nil-value)
  "Dump the whole REMOTE-PATH-cache. If NO-NIL-VALUE is not nil then these
cache-entries are not dumped. This command is not intended for end-users of
ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache 'REMOTE-PATH no-nil-value))

;; accessors for the HOST-ACCESSIBLE cache

(defun ecb-host-accessible-cache-add (host accessible-p)
  "Add the value of ACCESSIBLE-P to the HOST-ACCESSIBLE-cache with key HOST."
  (ecb-multicache-put-value 'ecb-filename-cache host 'HOST-ACCESSIBLE
                            (cons (current-time) accessible-p)))

(defun ecb-host-accessible-cache-get (host valid-time)
  "Get the accessible-p value from the HOST-ACCESSIBLE-cache. If the cache
entry is older then VALID-TIME \(in seconds) then it is discarded."
  (let ((value (ecb-multicache-get-value 'ecb-filename-cache host
                                         'HOST-ACCESSIBLE)))
    (if (or (null value)
            (> (ecb-time-diff (current-time) (car value) t) valid-time))
        ;; either not yet cached or outdated
        nil
      ;; return the valid cache-value
      (cdr value))))

(defun ecb-host-accessible-cache-dump (&optional no-nil-value)
  "Dump the whole HOST-ACCESSIBLE-cache. If NO-NIL-VALUE is not nil then these
cache-entries are not dumped. This command is not intended for end-users of
ECB."
  (interactive "P")
  (ecb-multicache-print-subcache 'ecb-filename-cache 'HOST-ACCESSIBLE no-nil-value))


;; ---- end of filename-cache implementation -----------------------

(defun ecb-file-browser-initialize-caches ()
  "Initialize the caches of the file-browser of ECB."
  (ecb-reset-history-filter)
  (ecb-filename-cache-init))

(defun ecb-file-browser-initialize (&optional no-caches)
  "Initialize the file-browser of ECB. If optional arg NO-CACHES is not nil
then the caches used by the file-browser will not be initialized."
  (setq ecb-path-selected-directory nil
        ecb-path-selected-source nil)
  (unless no-caches
    (ecb-file-browser-initialize-caches)))
  
(defmacro ecb-exec-in-directories-window (&rest body)
  "Evaluates BODY in the directories-window of ECB. If that window is not
visible then return the symbol 'window-not-visible. Otherwise the return
value of BODY is returned."
  `(unwind-protect
       (if (not (ecb-window-select ecb-directories-buffer-name))
           'window-not-visible
	 ,@body)
     ))


(defmacro ecb-exec-in-sources-window (&rest body)
  "Evaluates BODY in the sources-window of ECB. If that window is not
visible then return the symbol 'window-not-visible. Otherwise the return
value of BODY is returned."
  `(unwind-protect
       (if (not (ecb-window-select ecb-sources-buffer-name))
           'window-not-visible
	 ,@body)
     ))


(defmacro ecb-exec-in-history-window (&rest body)
  "Evaluates BODY in the history-window of ECB. If that window is not
visible then return the symbol 'window-not-visible. Otherwise the return
value of BODY is returned."
  `(unwind-protect
       (if  (not (ecb-window-select ecb-history-buffer-name))
           'window-not-visible
	 ,@body)
     ))


(defun ecb-goto-window-directories ()
  "Make the ECB-directories window the current window.
If `ecb-use-speedbar-instead-native-tree-buffer' is 'dir then goto to the
speedbar-window."
  (interactive)
  (or (ecb-goto-ecb-window ecb-directories-buffer-name)
      (and (equal ecb-use-speedbar-instead-native-tree-buffer 'dir)
           (ecb-goto-window-speedbar))))

(defun ecb-goto-window-sources ()
  "Make the ECB-sources window the current window.
If `ecb-use-speedbar-instead-native-tree-buffer' is 'source then goto to the
speedbar-window."
  (interactive)
  (or (ecb-goto-ecb-window ecb-sources-buffer-name)
      (and (equal ecb-use-speedbar-instead-native-tree-buffer 'source)
           (ecb-goto-window-speedbar))))

(defun ecb-goto-window-history ()
  "Make the ECB-history window the current window."
  (interactive)
  (ecb-goto-ecb-window ecb-history-buffer-name))

(defun ecb-maximize-window-directories ()
  "Maximize the ECB-directories-window.
I.e. delete all other ECB-windows, so only one ECB-window and the
edit-window\(s) are visible \(and maybe a compile-window). Works also if the
ECB-directories-window is not visible in current layout."
  (interactive)
  (if (equal ecb-use-speedbar-instead-native-tree-buffer 'dir)
      (ecb-maximize-window-speedbar)
    (ecb-display-one-ecb-buffer ecb-directories-buffer-name)))

(defun ecb-maximize-window-sources ()
  "Maximize the ECB-sources-window.
I.e. delete all other ECB-windows, so only one ECB-window and the
edit-window\(s) are visible \(and maybe a compile-window). Works also if the
ECB-sources-window is not visible in current layout."
  (interactive)
  (if (equal ecb-use-speedbar-instead-native-tree-buffer 'source)
      (ecb-maximize-window-speedbar)
    (ecb-display-one-ecb-buffer ecb-sources-buffer-name)))

(defun ecb-maximize-window-history ()
  "Maximize the ECB-history-window.
I.e. delete all other ECB-windows, so only one ECB-window and the
edit-window\(s) are visible \(and maybe a compile-window). Works also if the
ECB-history-window is not visible in current layout."
  (interactive)
  (ecb-display-one-ecb-buffer ecb-history-buffer-name))


(defun ecb-expand-directory-tree (path node)
  "Expands the directory part so the node representing PATH is visible.
Start with the childrens of NODE. Return not nil when an expansion has been
done \(so normally the tree-buffer must be rebuild). Return nil if the
expansion-state of the tree can show without any further expansion the node
representing PATH."
  (catch 'exit
    (dolist (child (tree-node-get-children node))
      (let ((data (tree-node-get-data child)))
        (when (and (>= (length path) (length data))
                   (ecb-string= (substring path 0 (length data)) data)
                   (or (= (length path) (length data))
                       (eq (elt path (length data))
                           (ecb-directory-sep-char path))))
          (let ((was-expanded (or (not (tree-node-is-expandable child))
                                  (tree-node-is-expanded child))))
            (tree-node-set-expanded child t)
            (ecb-update-directory-node child)
            (throw 'exit
                   (or (when (> (length path) (length data))
                         (ecb-expand-directory-tree path child))
                       (not was-expanded)))))))))


(defun ecb-check-directory-for-caching (dir number-of-contents)
  "Return not nil if DIR matches not any regexp of the option
`ecb-cache-directory-contents-not' but matches at least one regexp in
`ecb-cache-directory-contents' and NUMBER-OF-CONTENTS is greater then the
related threshold."
  (and (not (catch 'exit
              (dolist (elem ecb-cache-directory-contents-not)
                (let ((case-fold-search t))
                  (save-match-data
                    (if (string-match (car elem) dir)
                        (throw 'exit (car elem))))
                  nil))))
       (catch 'exit
         (dolist (elem ecb-cache-directory-contents)
           (let ((case-fold-search t))
             (save-match-data
               (if (and (string-match (car elem) dir)
                        (> number-of-contents (cdr elem)))
                   (throw 'exit (car elem))))
             nil)))))


(defun ecb-check-directory-for-source-regexps (dir)
  "Return the related source-exclude-include-regexps of
`ecb-source-file-regexps' if DIR matches any directory-regexp in
`ecb-source-file-regexps'."
  (ecb-match-regexp-list dir ecb-source-file-regexps 'car 'cdr))


(defun ecb-files-from-cvsignore (dir)
  "Return an expanded list of filenames which are excluded by the .cvsignore
file in current directory."
  (let ((cvsignore-content (ecb-file-content-as-string
                            (ecb-expand-file-name ".cvsignore" dir)))
        (files nil))
    (when cvsignore-content
      (dolist (f (split-string cvsignore-content))
        (setq files (append (ecb-directory-files dir nil
                                                 (wildcard-to-regexp f) t)
                            files)))
      files)))


(defun ecb-check-directory-for-cvsignore-exclude (dir)
  "Return not nil if DIR matches a regexp in `ecb-sources-exclude-cvsignore'."
  (ecb-match-regexp-list dir ecb-sources-exclude-cvsignore))

(defun ecb-get-sources-sort-function (sort-method &optional ignore-case)
  "According to SORT-METHOD \(which can either be 'name, 'extension or nil)
and IGNORE-CASE return a function which can be used as argument for `sort'."
  (cond ((equal sort-method 'name)
         (function (lambda (a b)
                     (ecb-string< a b ecb-sources-sort-ignore-case))))
        ((equal sort-method 'extension)
         (function
          (lambda(a b)
            (let ((ext-a (ecb-file-name-extension a t))
                  (ext-b (ecb-file-name-extension b t)))
              (if (ecb-string= ext-a ext-b ecb-sources-sort-ignore-case)
                  (ecb-string< a b ecb-sources-sort-ignore-case)
                (ecb-string< ext-a ext-b ecb-sources-sort-ignore-case))))))
        (t (function (lambda (a b)
                       nil)))))


(defun ecb-get-files-and-subdirs (dir)
  "Return a cons cell where car is a list of all files to display in DIR and
cdr is a list of all subdirs to display in DIR. Both lists are sorted
according to `ecb-sources-sort-method'."
  (or (ecb-files-and-subdirs-cache-get dir)
      ;; dir is not cached
      (let ((files (ecb-directory-files dir nil nil t))
            (source-regexps (or (ecb-check-directory-for-source-regexps
                                 (ecb-fix-filename dir))
                                '(("") (""))))
            (cvsignore-files (if (ecb-check-directory-for-cvsignore-exclude dir)
                                 (ecb-files-from-cvsignore dir)))
            sorted-files source-files subdirs cached-value)
        ;; if necessary sort FILES
        (setq sorted-files
              (if ecb-sources-sort-method
                  (sort files (ecb-get-sources-sort-function
                               ecb-sources-sort-method))
                files))
        ;; divide real files and subdirs. For really large directories (~ >=
        ;; 2000 entries) this is the performance-bottleneck in the
        ;; file-browser of ECB.
        (dolist (file sorted-files)
          (if (ecb-file-directory-p (ecb-fix-filename dir file))
              (when (not (ecb-check-dir-exclude file))
;;                 (when (not (ecb-file-accessible-directory-p file))
;;                   (ecb-merge-face-into-text file
;;                                             ecb-directory-not-accessible-face))
                (setq subdirs (append subdirs (list file))))
            (when (and (not (member file cvsignore-files))
                       (or (ecb-match-regexp-list file (cadr source-regexps))
                           (not (ecb-match-regexp-list file (car source-regexps)))))
              (setq source-files (append source-files (list file))))))
        
        (setq cached-value (cons source-files subdirs))
        ;; check if this directory must be cached
        (if (ecb-check-directory-for-caching dir (length sorted-files))
            (ecb-files-and-subdirs-cache-add dir cached-value))
        ;; return the result
        cached-value)))


(defun ecb-update-sources-buffer (dir-before-update)
  "Updates the sources-buffer with all sources contained in
`ecb-path-selected-directory' - the contents are either newly computed or come
from the `ecb-sources-cache'. DIR-BEFORE-UPDATE is the directory which was
selected before this update."

  ;; Here we add a cache-mechanism which caches for each path the node-tree
  ;; and the whole buffer-string of the sources-buffer. A cache-elem would be
  ;; removed from the cache if a directory is POWER-clicked in the directories
  ;; buffer because this is the only way to synchronize the sources-buffer
  ;; with the disk-contents of the clicked directory. This works because the
  ;; tree of the sources-buffer contains only not expandable nodes (see the
  ;; comment in `ecb-rebuild-methods-buffer-with-tagcache'). If we would
  ;; make the nodes in the Sources-buffer "expandable" this caching would not
  ;; work!
  
  (ecb-exec-in-sources-window
   ;; if we have a filtered cache we must display it - otherwise we use the
   ;; full cache if there is any
   (let ((cache-elem (or (ecb-sources-cache-get-filtered ecb-path-selected-directory)
                         (ecb-sources-cache-get-full ecb-path-selected-directory))))
     (if cache-elem
         (progn
           (tree-buffer-set-root (nth 0 cache-elem))
           (tree-buffer-update nil (cons (nth 2 cache-elem)
                                         (nth 1 cache-elem))))
       (let ((new-tree (tree-node-new-root))
             (old-children (tree-node-get-children (tree-buffer-get-root)))
             (new-cache-elem nil))
         ;; building up the new files-tree
         (ecb-tree-node-add-files
          new-tree
          ecb-path-selected-directory
          (car (ecb-get-files-and-subdirs ecb-path-selected-directory))
          ecb-sources-nodetype-sourcefile
          ecb-show-source-file-extension old-children t)

         ;; updating the buffer itself
         (tree-buffer-set-root new-tree)
         (tree-buffer-update)

         ;; check if the sources buffer for this directory must be
         ;; cached: If yes update the cache
         (when (ecb-check-directory-for-caching
                ecb-path-selected-directory
                (length tree-buffer-nodes))
           (setq new-cache-elem (list (tree-buffer-get-root)
                                      (ecb-copy-list tree-buffer-nodes)
                                      (buffer-substring (point-min)
                                                        (point-max))))
           (ecb-sources-cache-add-full ecb-path-selected-directory
                                       new-cache-elem))))
           
     (when (not (ecb-string= dir-before-update ecb-path-selected-directory))
       (tree-buffer-scroll (point-min) (point-min))))))

(defun ecb-sources-filter-by-ext (ext-str)
  "Filter the sources by extension EXT-STR."
  (if (= (length ext-str) 0)
      (ecb-apply-filter-to-sources-buffer
       "^[^.]+$" ;; matches only filenames with no extension
       "No ext.")
    (ecb-apply-filter-to-sources-buffer
     (format "\\.%s\\'" ext-str)
     (format "*.%s" ext-str))))

(tree-buffer-defpopup-command ecb-popup-sources-filter-by-ext
  "Filter the sources by extension by popup."
  (ecb-sources-filter-by-ext
   (read-string "Insert the filter-extension without leading dot: "
                (and node
                     (ecb-file-name-extension (tree-node-get-data node))))))

(defun ecb-sources-filter-by-regexp ()
  "Filter the sources by a regexp. Ask for the regexp."
  (let ((regexp-str (read-string "Insert the filter-regexp: ")))
    (if (> (length regexp-str) 0)
        (ecb-apply-filter-to-sources-buffer regexp-str))))
  
(tree-buffer-defpopup-command ecb-popup-sources-filter-by-regexp
  "Filter the sources by regexp by popup."
  (ecb-sources-filter-by-regexp))
  
(tree-buffer-defpopup-command ecb-popup-sources-filter-none
  "Remove any filter from the sources by popup."
  (ecb-apply-filter-to-sources-buffer nil))
  

(defun ecb-sources-filter ()
  "Apply a filter to the sources-buffer to reduce the number of entries.
So you get a better overlooking. There are three choices:
- Filter by extension: Just insert the extension you want the Sources-buffer
  being filtered. Insert the extension without leading dot!
- Filter by regexp: Insert the filter as regular expression.
- No filter: This means to display an entry for every file in the current
  selected directory \(all except these filter already filtered out by
  `ecb-source-file-regexps' and `ecb-sources-exclude-cvsignore').
Such a filter is only applied to the current selected directory, i.e. each
directory has its own filtered sources-buffer."
  (interactive)
  (let ((choice (ecb-query-string "Filter sources by:"
                                  '("extension" "regexp" "nothing"))))
    (cond ((ecb-string= choice "extension")
           (ecb-sources-filter-by-ext
            (read-string "Insert the filter-extension without leading dot: ")))
          ((ecb-string= choice "regexp")
           (ecb-sources-filter-by-regexp))
          (t (ecb-apply-filter-to-sources-buffer nil)))))

(defun ecb-sources-filter-modeline-prefix (buffer-name sel-dir sel-source)
  "Compute a mode-line prefix for the Sources-buffer so the current filter
applied to the sources is displayed. This function is only for using by
the option `ecb-mode-line-prefixes'."
  (let ((filtered-cache-elem (ecb-sources-cache-get-filtered sel-dir)))
    (if (null filtered-cache-elem)
        nil ;; no prefix if no filter
      (format "[Filter: %s]" (cdr (nth 3 filtered-cache-elem))))))

(defun ecb-apply-filter-to-sources-buffer (filter-regexp &optional filter-display)
  "Apply the regular expression FILTER-REGEXP to the files of
`ecb-path-selected-directory' and display only the filtered files in the
Sources-buffer. If FILTER-REGEXP is nil then any applied filter is removed and
all files are displayed."
  (save-selected-window
    (ecb-exec-in-sources-window
     (if (null filter-regexp)
         ;; no filtering
         (progn
           ;; remove the filtered cache by setting it to nil
           (ecb-sources-cache-add-filtered ecb-path-selected-directory nil)
           ;; update the sources buffer - because the filtered cache is nil
           ;; the full sources are displayed.
           (ecb-update-sources-buffer ecb-path-selected-directory)
           (tree-buffer-highlight-node-data ecb-path-selected-source))
       ;; apply the filter-regexp
       (let ((new-tree (tree-node-new-root))
             (old-children (tree-node-get-children (tree-buffer-get-root)))
             (all-files (car (ecb-get-files-and-subdirs ecb-path-selected-directory)))
             (filtered-files nil))
         (dolist (file all-files)
           (if (string-match filter-regexp file)
               (setq filtered-files
                     (cons file filtered-files))))
         (if (null filtered-files)
             (message "ECB has not applied this filter because it would filter out all files!")
           ;; building up the new files-tree
           (ecb-tree-node-add-files
            new-tree
            ecb-path-selected-directory
            (nreverse filtered-files)
            ecb-sources-nodetype-sourcefile
            ecb-show-source-file-extension old-children t)

           ;; updating the buffer itself
           (tree-buffer-set-root new-tree)
           (tree-buffer-update)
           (tree-buffer-scroll (point-min) (point-min))
           (tree-buffer-highlight-node-data ecb-path-selected-source)

           ;; add the new filter to the cache, so the next call to
           ;; `ecb-update-sources-buffer' displays the filtered sources.
           (ecb-sources-cache-add-filtered ecb-path-selected-directory
                                           (list (tree-buffer-get-root)
                                                 (ecb-copy-list tree-buffer-nodes)
                                                 (buffer-substring (point-min)
                                                                   (point-max))
                                                 (cons filter-regexp
                                                       (or filter-display
                                                           filter-regexp)))))))))
  ;; now we update the mode-lines so the current filter (can be no filter) is
  ;; displayed in the mode-line. See `ecb-sources-filter-modeline-prefix'.
  (ecb-mode-line-format))

(defun ecb-matching-source-paths (path-to-match &optional sorted)
  "Return all source-paths of `ecb-source-path' which match PATH-TO-MATCH. If
SORTED is not nil then the paths are sorted by descending length, means the
longest path \(which is the best matching) is the first elem and the shortest
path the last elem. Otherwise the matching paths are returned in that sequence
they occur in `ecb-source-paths'."
  (let* ((p-t-m (ecb-fix-filename path-to-match))
         (normed-current-source-paths
          (mapcar (function (lambda (elem)
                              (ecb-fix-filename (if (listp elem) (car elem) elem))))
                  (append (ecb-get-source-paths-from-functions)
                          ecb-source-path)))
         (matching-paths
          (delq nil
                (mapcar (lambda (elem)
                          (save-match-data
                            (if (string-match (concat "^" (regexp-quote elem))
                                              p-t-m)
                                elem)))
                        normed-current-source-paths))))
    (if (not sorted)
        matching-paths
      (sort matching-paths
            (lambda (lhs rhs)
              (> (length lhs) (length rhs)))))))

(defun ecb-get-best-matching-source-path (path)
  "Return the best-matching source-path for PATH."
  (car (ecb-matching-source-paths path t)))

(defun ecb-set-selected-directory (path &optional force)
  "Set the contents of the ECB-directories and -sources buffer correct for the
value of PATH. If PATH is equal to the value of `ecb-path-selected-directory'
then nothing is done unless first optional argument FORCE is not nil."
  (let ((last-dir ecb-path-selected-directory))
    (save-selected-window
      (setq ecb-path-selected-directory (ecb-fix-filename path))
      ;; if ecb-path-selected-directory has not changed then there is no need
      ;; to do anything here because neither the content of directory buffer
      ;; nor the content of the sources buffer can have been changed!
      (when (or force (not (ecb-string= last-dir ecb-path-selected-directory)))
        (when (or (not (ecb-show-sources-in-directories-buffer-p))
                  ecb-auto-expand-directory-tree)
          (ecb-exec-in-directories-window
           (let (start was-expanded)
             (when ecb-auto-expand-directory-tree
               ;; Expand tree to show selected directory
               (setq start
                     (if (equal ecb-auto-expand-directory-tree 'best)
                         ;; If none of the source-paths in the buffer
                         ;; `ecb-directories-buffer-name' matches then nil
                         ;; otherwise the node of the best matching
                         ;; source-path
                         (let ((best-source-path
                                (ecb-get-best-matching-source-path
                                 ecb-path-selected-directory)))
                           (if best-source-path
                               (tree-buffer-find-node-data
                                (ecb-fix-filename best-source-path))))
                       ;; we start at the root node
                       (tree-buffer-get-root)))
               (when (and (equal ecb-auto-expand-directory-tree 'best)
                          start)
                 (setq was-expanded (or (not (tree-node-is-expandable start))
                                        (tree-node-is-expanded start)))
                 ;; expand the best-match node itself
                 (tree-node-set-expanded start t)
                 ;; This function ensures a correct expandable-state of
                 ;; start-node
                 (ecb-update-directory-node start))
               ;; start recursive expanding of either the best-matching node or
               ;; the root-node itself.
               (if (or (ecb-expand-directory-tree ecb-path-selected-directory
                                                  (or start
                                                      (tree-buffer-get-root)))
                       (not was-expanded))
                   (tree-buffer-update)
                 (tree-buffer-recenter start (selected-window))
                 ;; sometimes we do not need a full tree-buffer-update, even
                 ;; when FORCE is not nil. But we have to restart the
                 ;; directories-buffer stealthy-state.
                 (and force (ecb-stealth-tasks-after-directories-update))))
;;              (ecb-expand-directory-tree ecb-path-selected-directory
;;                                           (or start
;;                                               (tree-buffer-get-root)))
;;                (tree-buffer-update))
             (when (not (ecb-show-sources-in-directories-buffer-p))
               (tree-buffer-highlight-node-data ecb-path-selected-directory
                                                start)))))
        ;; now we update the sources buffer for `ecb-path-selected-directory'
        (ecb-update-sources-buffer last-dir)
        ;; now we run the hooks
        (run-hook-with-args 'ecb-after-directory-change-hook
                            last-dir ecb-path-selected-directory)
        )))
  
  ;; set the default-directory of each tree-buffer to current selected
  ;; directory so we can open files via find-file from each tree-buffer.
  ;; is this necessary if neither dir.- nor sources-buffer-contents have been
  ;; changed? I think not but anyway, doesn't matter, costs are very low.
  (save-excursion
    (dolist (buf ecb-tree-buffers)
      (set-buffer buf)
      (setq default-directory
            (concat ecb-path-selected-directory
                    (and (not (= (aref ecb-path-selected-directory
                                       (1- (length ecb-path-selected-directory)))
                                 (ecb-directory-sep-char ecb-path-selected-directory)))
                         (ecb-directory-sep-string ecb-path-selected-directory))))))
  ;; set the modelines of all visible tree-buffers new
  (ecb-mode-line-format))


(defun ecb-get-source-name (filename)
  "Returns the source name of a file."
  (let ((f (ecb-file-name-nondirectory filename)))
    (if ecb-show-source-file-extension
        f
      (ecb-file-name-sans-extension f))))


(defun ecb-select-source-file (filename &optional force)
  "Updates the directories, sources and history buffers to match the filename
given. If FORCE is not nil then the update of the directories buffer is done
even if current directory is equal to `ecb-path-selected-directory'."
  (save-selected-window
    (ecb-set-selected-directory (ecb-file-name-directory filename) force)
    (setq ecb-path-selected-source filename)
  
    ;; Update directory buffer
    (when (ecb-show-sources-in-directories-buffer-p)
      (ecb-exec-in-directories-window
       (tree-buffer-highlight-node-data ecb-path-selected-source)))
    
    ;; Update source buffer
    (ecb-exec-in-sources-window
     (tree-buffer-highlight-node-data ecb-path-selected-source))

    ;; Update history buffer always regardless of visibility of history window
    (ecb-add-item-to-history-buffer ecb-path-selected-source)
    (ecb-sort-history-buffer)
    ;; Update the history window only if it is visible
    (ecb-update-history-window ecb-path-selected-source)))


(defvar ecb-history-filter nil
  "A cons-cell where car is the filter-function and the cdr is a string how
the current active filter should be displayed in the modeline of the
History-buffer. The filter-function gets the filename of an existing
file-buffer and has to return not nil if for this filename a history-entry
should be added.")

(defun ecb-reset-history-filter ()
  "Reset the `ecb-history-filter' so all file-buffers are displayed."
  (setq ecb-history-filter '(identity . nil)))

(defun ecb-history-filter-reset-p ()
  (null (cdr ecb-history-filter)))

(ecb-reset-history-filter)

(defun ecb-add-all-buffers-to-history ()
  "Add all current file-buffers to the history-buffer of ECB.
Dependend on the value of `ecb-history-sort-method' afterwards the history is
sorted either by name or by extension. If `ecb-history-sort-method' is nil the
most recently used buffers are on the top of the history and the seldom used
buffers at the bottom."
  (interactive)
  (ecb-reset-history-filter)
  (ecb-add-buffers-to-history))

(defun ecb-add-buffers-to-history ()
  "Add exactly these currently existing file-buffers to the history-buffer
which are not filtered out by current value of `ecb-history-filter'."
    ;; first we clear out the history buffer
  (save-excursion
    (set-buffer ecb-history-buffer-name)
    (tree-buffer-clear))
  (mapc (function (lambda (buf)
                    (when (buffer-file-name buf)
                      (ecb-add-item-to-history-buffer
                       (buffer-file-name buf)))))
        (reverse (buffer-list)))
  (ecb-sort-history-buffer)
  (ecb-update-history-window (buffer-file-name ecb-last-source-buffer))
  (when (and (save-excursion
               (set-buffer ecb-history-buffer-name)
               (tree-buffer-empty-p))
             (not (ecb-history-filter-reset-p)))
    (ecb-add-all-buffers-to-history)
    (message "ECB has not applied this filter because it would filter out all entries!"))
  ;; now the modeline has to display the current filter
  (ecb-mode-line-format))

  
(defun ecb-history-filter-modeline-prefix (buffer-name sel-dir sel-source)
  "Compute a mode-line prefix for the History-buffer so the current filter
applied to the history-entries is displayed. This function is only for using
by the option `ecb-mode-line-prefixes'."
  (and (cdr ecb-history-filter)
       (format "[Filter: %s]" (cdr ecb-history-filter))))


(defun ecb-add-item-to-history-buffer (filename)
  "Add a new item for FILENAME to the history buffer if the current filter of
`ecb-history-filter' does not filter out this file."
  (save-excursion
    (ecb-buffer-select ecb-history-buffer-name)
    (tree-node-remove-child-data (tree-buffer-get-root) filename)
    (when (and (not (ecb-check-filename-for-history-exclude filename))
               (funcall (car ecb-history-filter) filename))
      (tree-node-add-child-first
       (tree-buffer-get-root)
       (tree-node-new
        (let ((file-1 (if (eq ecb-history-item-name 'buffer-name)
                          (let ((b (get-file-buffer filename)))
                            (if b
                                (buffer-name b)
                              (ecb-get-source-name filename)))
                        (ecb-get-source-name filename)))
              (dir (ecb-file-name-directory filename)))
          (if (and (ecb-vc-directory-should-be-checked-p dir)
                   (ecb-vc-managed-dir-p dir))
              (ecb-vc-generate-node-name file-1
                                         (nth 0 (ecb-vc-cache-get filename)))
            (ecb-generate-node-name file-1 -1 "leaf"
                                    ecb-sources-buffer-name)))
        ecb-history-nodetype-sourcefile
        filename t)))))


(defun ecb-sort-history-buffer ()
  "Sort the history buffer according to `ecb-history-sort-method'."
  (when ecb-history-sort-method
    (save-excursion
      (ecb-buffer-select ecb-history-buffer-name)
      (tree-node-sort-children
       (tree-buffer-get-root)
       (cond ((equal ecb-history-sort-method 'name)
              (function (lambda (l r)
                          (let* ((l0 (tree-node-get-name l))
                                 (r0 (tree-node-get-name r))
                                 (l1 (save-match-data
                                       (if (string-match "^(.) \\(.+\\)$" l0)
                                           (match-string 1 l0)
                                         l0)))
                                 (r1 (save-match-data
                                       (if (string-match "^(.) \\(.+\\)$" r0)
                                           (match-string 1 r0)
                                         r0))))
                            (ecb-string< l1 r1 ecb-history-sort-ignore-case)))))
             ((equal ecb-history-sort-method 'extension)
              (function
               (lambda (l r)
                 (let* ((l0 (tree-node-get-name l))
                        (r0 (tree-node-get-name r))
                        (l1 (save-match-data
                              (if (string-match "^(.) \\(.+\\)$" l0)
                                  (match-string 1 l0)
                                l0)))
                        (r1 (save-match-data
                              (if (string-match "^(.) \\(.+\\)$" r0)
                                  (match-string 1 r0)
                                r0)))
                        (ext-l (ecb-file-name-extension l1 t))
                        (ext-r (ecb-file-name-extension r1 t)))
                   (if (ecb-string= ext-l ext-r ecb-history-sort-ignore-case)
                       (ecb-string< l1 r1 ecb-history-sort-ignore-case)
                     (ecb-string< ext-l ext-r ecb-history-sort-ignore-case))))))
             (t (function (lambda (l r)
                            nil))))))))


(defun ecb-update-history-window (&optional filename)
  "Updates the history window and highlights the item for FILENAME if given."
  (save-selected-window
    (ecb-exec-in-history-window
     (tree-buffer-update)
     (tree-buffer-highlight-node-data filename))))

(defun ecb-set-selected-source (filename other-edit-window
					 no-edit-buffer-selection hide)
  "Updates all the ECB buffers and loads the file. The file is also
displayed unless NO-EDIT-BUFFER-SELECTION is set to non nil. In such case the
file is only loaded invisible in the background, all semantic-parsing and
ECB-Buffer-updating is done but the content of the main-edit window is not
changed. For the allowed values of OTHER-EDIT-WINDOW see
`ecb-combine-ecb-button/edit-win-nr'. If HIDE is not nil then ECB hides the
ecb-windows after displaying the file in an edit-window."
  (ecb-select-source-file filename)
  (if no-edit-buffer-selection
      ;; load the selected source in an invisible buffer, do all the
      ;; updating and parsing stuff with this buffer in the background and
      ;; display the methods in the METHOD-buffer. We can not go back to
      ;; the edit-window because then the METHODS buffer would be
      ;; immediately updated with the methods of the edit-window.
      (save-excursion
        (set-buffer (find-file-noselect filename))
        (ecb-update-methods-buffer--internal 'scroll-to-begin))
    ;; open the selected source in the edit-window and do all the update and
    ;; parsing stuff with this buffer
    (ecb-find-file-and-display ecb-path-selected-source
			       other-edit-window)
    (ecb-update-methods-buffer--internal 'scroll-to-begin)
    (setq ecb-major-mode-selected-source major-mode)
    (ecb-tag-sync 'force)
    (if hide
        (ecb-hide-ecb-windows))))
             

(defun ecb-clear-history ()
  "Clears the ECB history-buffer."
  (interactive)
  (unless (or (not ecb-minor-mode)
              (not (equal (selected-frame) ecb-frame)))
    (save-selected-window
      (ecb-exec-in-history-window
       (tree-buffer-clear)
       (tree-buffer-update)
       (tree-buffer-highlight-node-data ecb-path-selected-source)))))



(defun ecb-update-directory-node (node)
  "Updates the directory node NODE and add all subnodes if any."
  (let ((old-children (tree-node-get-children node))
        (path (tree-node-get-data node)))
    (tree-node-set-children node nil)
    (if (ecb-file-accessible-directory-p path)
        (let ((files-and-dirs (ecb-get-files-and-subdirs path)))
          (ecb-tree-node-add-files node path (cdr files-and-dirs)
                                   ecb-directories-nodetype-directory
                                   t old-children)
          (if (ecb-show-sources-in-directories-buffer-p)
              (ecb-tree-node-add-files node path (car files-and-dirs)
                                       ecb-directories-nodetype-sourcefile
                                       ecb-show-source-file-extension
                                       old-children t))
          (tree-node-set-expandable node (or (tree-node-get-children node)))
          ;; if node is not expandable we set its expanded state to nil
          (tree-node-set-expanded node (if (not (tree-node-is-expandable node))
                                           nil
                                         (tree-node-is-expanded node)))))))


(defun ecb-get-source-paths-from-functions ()
  "Return a list of paths found by querying `ecb-source-path-functions'."
  (let ((func ecb-source-path-functions)
	(paths nil)
	(rpaths nil))
    (while func
      (setq paths (append paths (funcall (car ecb-source-path-functions)))
	    func (cdr func)))
    (while paths
      (setq rpaths (cons (ecb-fix-filename (car paths)) rpaths)
	    paths (cdr paths)))
    rpaths))


(defun ecb-update-directories-buffer ()
  "Updates the ECB directories buffer."
  (interactive)
  (unless (or (not ecb-minor-mode)
              (not (equal (selected-frame) ecb-frame)))
    (save-selected-window
      (ecb-exec-in-directories-window
       (let* ((node (tree-buffer-get-root))
              (old-children (tree-node-get-children node))
              (paths (append (ecb-get-source-paths-from-functions)
			     ecb-source-path)))
         (tree-node-set-children node nil)
	 (dolist (dir paths)
	   (let* ((path (if (listp dir) (car dir) dir))
                  (remote-path (ecb-remote-path path))
                  (norm-dir nil)
                  (name nil)
                  (not-accessible nil))
             (if (or (not remote-path)
                     (ecb-host-accessible-p (nth 1 remote-path)))
                 (progn
                   (setq norm-dir (ecb-fix-filename path nil t))
                   (setq name (if (listp dir) (cadr dir) norm-dir))
                   (if (ecb-file-accessible-directory-p norm-dir)
                       (tree-node-add-child
                        node
                        (ecb-new-child old-children name
                                       ecb-directories-nodetype-sourcepath
                                       norm-dir
                                       nil
                                       (if ecb-truncate-long-names
                                       'beginning)))
                     (setq not-accessible t)))
               (setq not-accessible t))
             (when not-accessible
               (if (listp dir)
                   (ecb-warning "Source-path %s with alias %s is not accessible - ignored!"
                                (car dir) (cadr dir))
                 (ecb-warning "Source-path %s is not accessible - ignored!" dir)))))
         (tree-buffer-update))))
    ))

;; remote-path stuff 

(defsubst ecb-host-accessible-valid-time (host)
  "Get the valid-cache-time of a remote HOST concering its ping-state. If host
doesn't match any regexp of `ecb-host-accessible-check-valid-time' then return
60 seconds."
  (or (ecb-match-regexp-list host ecb-host-accessible-check-valid-time
                             'car 'cdr)
      60))

;; (ecb-host-accessible-valid-time "ecb.sourceforge.net")

(defun ecb-host-accessible-p (host)
  "Return not nil if HOST is accessible."
  (let ((value (ecb-host-accessible-cache-get
                host (ecb-host-accessible-valid-time host))))
    (cond ((equal value 'NOT-ACCESSIBLE)
           nil)
          (value value)
          (t (let* ((options (append ecb-ping-options (list host)))
                    (result (equal 0 (apply 'call-process
                                            ecb-ping-program
                                            nil nil nil
                                            options))))
               (ecb-host-accessible-cache-add host (or result 'NOT-ACCESSIBLE))
               result)))))

;; (ecb-host-accessible-p "ecb.sourceforge.net")

(silentcomp-defun ange-ftp-ftp-name)
(silentcomp-defun efs-ftp-path)
(silentcomp-defun tramp-tramp-file-p)
(silentcomp-defun tramp-file-name-path)
(silentcomp-defun tramp-file-name-localname)
(silentcomp-defun tramp-file-name-host)
(silentcomp-defun tramp-dissect-file-name)
(defun ecb-remote-path (path)
  "Test if PATH is a remote path and dissect it into components if yes.
Returns a list (FULL-HOST-USER-PART HOST REAL-PATH), or nil if PATH is not a
remote path. FULL-HOST-USER-PART is that component from beginning of PATH to
the :-separator which separates user- and host-parts from the real path, i.e.
it always ends with a colon! HOST is the remote HOST and REAL-PATH is that
component after that :-separator. Supports tramp, ange-ftp and efs."
  (let ((value (ecb-remote-path-cache-get path)))
    (cond ((equal value 'NOT-REMOTE)
           nil)
          (value value)
          (t
           (let* ((dissection (or (and (featurep 'tramp) ;; tramp-support
                                       (tramp-tramp-file-p path)
                                       (tramp-dissect-file-name path))
                                  (and (featurep 'ange-ftp) ;; ange-ftp-support
                                       (ange-ftp-ftp-name path))
                                  (and (featurep 'efs) ;; efs support
                                       (efs-ftp-path path))))
                  (host/real-path
                   (if dissection
                       (or (and (featurep 'tramp) ;; tramp-support
                                (cons (tramp-file-name-host dissection)
                                      (if (fboundp 'tramp-file-name-localname)
                                          (tramp-file-name-localname dissection)
                                        (tramp-file-name-path dissection))))
                           (and (featurep 'ange-ftp) ;; ange-ftp-support
                                (cons (nth 0 dissection)
                                      (nth 2 dissection)))
                           (and (featurep 'efs) ;; efs support
                                (cons (nth 0 dissection)
                                      (nth 2 dissection))))
                     (cons nil path)))
                  (full-host-user-part
                   (substring path 0 (- (length path)
                                        (length (cdr host/real-path)))))
                  (result nil))
             (setq result
                   (and dissection
                        (list full-host-user-part
                              (car host/real-path)
                              (cdr host/real-path))))
             (ecb-remote-path-cache-add path (or result 'NOT-REMOTE))
             result)))))

;; (ecb-remote-path "/berndl@ecb.sourceforge.net:~")
;; (ecb-remote-path "~")


;; empty dirs

(defun ecb-check-emptyness-of-dir (dir)
  "Checks if DIR is an empty directory. If empty return not nil otherwise nil."
  (let ((cache-value (ecb-directory-empty-cache-get dir))
        (show-sources (ecb-show-sources-in-directories-buffer-p)))
    (if (and cache-value
             (equal (cdr cache-value) show-sources))
        (car cache-value)
      (ecb-directory-empty-cache-remove dir)
      (let ((entries (and (ecb-file-accessible-directory-p dir)
                          (ecb-directory-files dir nil nil t)))
            (just-files-means-empty (not show-sources))
            (full-file-name nil)
            (empty-p nil))
        (setq empty-p
              (catch 'found
                (dolist (e entries)
                  (when (not (member e '("." ".." "CVS")))
                    (setq full-file-name (ecb-fix-filename dir e))
                    (if (ecb-file-directory-p full-file-name)
                        (throw 'found 'nil)
                      (if (not just-files-means-empty)
                          (throw 'found 'nil)))))
                t))
        ;; now we add this value to the cache
        (ecb-directory-empty-cache-add (ecb-fix-filename dir)
                                       (cons empty-p show-sources))
        empty-p))))


(defecb-stealthy ecb-stealthy-empty-dir-check
  "Check for each current visible nodes in the directories buffer if the
underlying directory is empty or not and update the node if the current node
state and display is different from the empty-state of the associated
directory. This function is only for use by `ecb-stealthy-updates'!"
  (save-selected-window
    (when (equal 'window-not-visible
                 (ecb-exec-in-directories-window
                  (if (equal state 'restart)
                      (setq state 1))
                  ;; Here the state is an integer because a stealthy functions runs only
                  ;; when state != 'done
                  (let ((lines-of-buffer (count-lines (point-min) (point-max)))
                        (curr-node nil)
                        (dir-empty-p nil))
                    (save-excursion
                      (while (and (not (input-pending-p))
                                  (<= state lines-of-buffer))
                        (goto-line state)
                        (setq curr-node (tree-buffer-get-node-at-point))
                        (when (ecb-directory-should-prescanned-p
                               (tree-node-get-data curr-node))
                          (setq dir-empty-p
                                (ecb-check-emptyness-of-dir (tree-node-get-data curr-node)))
                          ;; we update the node only if we have an empty dir and the node is
                          ;; still expandable
                          (when (or (and dir-empty-p
                                         (tree-node-is-expandable curr-node))
                                    (and (not dir-empty-p)
                                         (not (tree-node-is-expandable curr-node))))
                            (tree-buffer-update-node nil
                                                     'use-old-value
                                                     'use-old-value
                                                     'use-old-value
                                                     'use-old-value
                                                     (not dir-empty-p)
                                                     t)))
                          (setq state (1+ state))))
                    (if (> state lines-of-buffer)
                        (setq state 'done)))))
      (setq state 'done))))

;; read-only-files?

(defun ecb-stealthy-read-only-check--internal (state)
  "Check for all sourcefile-nodes either in the directories- or the
sources-buffer if the associated file is writable or not. This function does
the real job and is is only for use by a stealthy function defined with
`defecb-stealthy'! STATE is the initial state-value the stealthy-function has
when called. Return the new state-value."
  (if (or (not ecb-sources-perform-read-only-check)
          (not (or (string= (buffer-name (current-buffer))
                            ecb-sources-buffer-name)
                   (and (string= (buffer-name (current-buffer))
                                 ecb-directories-buffer-name)
                        (ecb-show-sources-in-directories-buffer-p)))))
      'done
    ;; Now we are either in the sources-buffer or in the directories-buffer
    ;; when sources are displayed in the directories-buffer
    (if (equal state 'restart)
        (setq state 1))
    ;; Here the state is an integer because a stealthy functions runs only
    ;; when state != 'done
    (let ((lines-of-buffer (count-lines (point-min) (point-max)))
          (curr-node nil)
          (new-name nil)
          (read-only-p nil)
          (node-type-to-check (if (string= (buffer-name (current-buffer))
                                           ecb-sources-buffer-name)
                                  ecb-sources-nodetype-sourcefile
                                ecb-directories-nodetype-sourcefile)))
      (save-excursion
        (while (and (not (input-pending-p))
                    (<= state lines-of-buffer))
          (goto-line state)
          (setq curr-node (tree-buffer-get-node-at-point))
          (when (and (= (tree-node-get-type curr-node) node-type-to-check)
                     (ecb-sources-read-only-check-p
                      (ecb-file-name-directory (tree-node-get-data curr-node))))
            (setq new-name (tree-node-get-name curr-node))
            (setq read-only-p
                  (not (ecb-file-writable-p (tree-node-get-data curr-node))))
            (if read-only-p
                (ecb-merge-face-into-text new-name
                                          ecb-source-read-only-face))
            ;; we update the node only if we have an empty dir and the node is
            ;; still expandable
            (when read-only-p
              (tree-buffer-update-node
               nil
               new-name
               'use-old-value
               'use-old-value
               'use-old-value
               'use-old-value
               t)))
          (setq state (1+ state))))
      (if (> state lines-of-buffer)
          (setq state 'done)))
    state))


(defecb-stealthy ecb-stealthy-ro-check-in-directories-buf
  "Check for all sourcefile-nodes in the directories-buffer if the associated
file is writable or not."
  (if (ecb-show-sources-in-directories-buffer-p)
      (save-selected-window
        (when (equal 'window-not-visible
                     (ecb-exec-in-directories-window
                      (setq state
                            (ecb-stealthy-read-only-check--internal state))))
          (setq state 'done)))
    (setq state 'done)))

(defecb-stealthy ecb-stealthy-ro-check-in-sources-buf
  "Check for all sourcefile-nodes in the sources-buffer if the associated file
is writable or not."
  (save-selected-window
    (when (equal 'window-not-visible
                 (ecb-exec-in-sources-window
                  (setq state
                        (ecb-stealthy-read-only-check--internal state))))
      (setq state 'done))))

;; version control support

;; We use a cache which stores for
;; + a directory: either the function used to check the VC-state of its files
;;   (if the directory is managed by a VC-backend) or the symbol 'NO-VC (if
;;   the dir is not managed by a VC-backend).
;; + a file: the most recent VC-state plus the check-timestamp for this state.
;;
;; So we have to call only once the identify-backend-function (see above) for
;; a directory. The check-state-function must only be called if the file has
;; been modified since the stored check-state-timestamp. With this caching
;; even using real-VC-checks (as vc-recompute-state) which never uses
;; heuristics is possible without loosing to much informations (only if a file
;; is modified by another user can not be detected with this cache - but for
;; this we have the power-click which always throws away any cache-state)

(defconst ecb-vc-state-icon-alist '((up-to-date . ("vc-up-to-date" "(u)"))
                                    (edited . ("vc-edited" "(e)"))
                                    (added . ("vc-added" "(a)"))
                                    (needs-patch . ("vc-needs-patch" "(p)"))
                                    (needs-merge . ("vc-needs-merge" "(m)"))
                                    (ignored . ("vc-ignored" "(x)"))
                                    (unknown . ("vc-unknown" "(?)"))
                                    (nil . ("vc-unknown" "(?)")))
  "Associate an image-name and a textual icon to the allowed VC-states - see
`ecb-vc-supported-backends'. Each element is a cons-cell where the car is the
symbol of a supported VC-state and the cdr a 2-element list where the first
element is the name of the needed image-icon and the second element the
ascii-string which should be dislayed if Emacs doesn't support image-display.")

(defsubst ecb-vc-get-image-name-for-vc-state (state)
  "Return the associated image-name for the vc-state STATE."
  (or (nth 0 (cdr (assq state ecb-vc-state-icon-alist)))
      "vc-unknown"))
  
(defsubst ecb-vc-get-ascii-icon-for-vc-state (state)
  "Return the associated texual icon for the vc-state STATE."
  (or (nth 1 (cdr (assq state ecb-vc-state-icon-alist)))
      "(?)"))


(defconst ecb-vc-incr-searchpattern-node-prefix
  '("\\(\\(([uempx?])\\)? \\)?" . 2)
  "Prefix-pattern which ignores all not interesting vc-icon-stuff of a
node-name at incr. search. This ignores the \"(<vc-state-char>)\" whereas
<vc-state-char> is one of u, e, m, p or ?.
Format: cons with car is the pattern and cdr is the number of subexpr in this
pattern.")


(defun ecb-vc-check-state (file tree-buffer-name vc-state-fcn)
  "Check if the VC-state for FILE must be rechecked, i.e. if it is out of
date. If it is still valid and also already checked for TREE-BUFFER-NAME then
return the symbol 'unchanged \(if still valid but only not checked for
TREE-BUFFER-NAME then return the state and store the fact that it has been
check now also for this buffer). Otherwise check the new state for FILE with
VC-STATE-FCN, store it in the cache only for TREE-BUFFER-NAME and return the
new state."
  (let* ((cached-state (ecb-vc-cache-get file))
         (last-state (nth 0 cached-state))
         (last-check-time (nth 1 cached-state))
         (checked-tree-buffer-names (nth 2 cached-state))
         (no-need-for-state-check-p
          (and last-check-time
               (or (null last-state) ;; FILE has been checked but is not in VC
                   (not (ecb-time-less-p last-check-time
                                         (ecb-subseq (nth 5 (ecb-file-attributes file))
                                                     0 2))))))
         (result nil))
    (if no-need-for-state-check-p
        ;; FILE was not modified since our last vc-state-check
        (if (member tree-buffer-name checked-tree-buffer-names)
            ;; TREE-BUFFER-NAMES is in the list of buffer-names for which the
            ;; state of FILE has already been cached ==> there is no need to
            ;; update the cache we can just return 'unchanged to signalize
            ;; that nothing has to be updated
            (setq result 'unchanged)
          ;; now we add TREE-BUFFER-NAME to that list - this new list will be
          ;; added to the cache below. As result we will return the last-state
          ;; because the state itself is still valid - the only thing we now
          ;; have to store in the cache is that the last-state is now valid
          ;; for TREE-BUFFER-NAME too!
          (setq result last-state)
          (setq checked-tree-buffer-names
                (cons tree-buffer-name checked-tree-buffer-names)))

      ;; FILE was modified since our last vc-state-check, so we have to check
      ;; the state again
      
      ;; set the list of the buffer-names for which the check will be performed
      ;; and then cached to TREE-BUFFER-NAME ==> Only for this buffer-name the
      ;; cache is valid.
      (setq checked-tree-buffer-names (list tree-buffer-name))
      ;; get the new vc-state
      (setq result (and vc-state-fcn
                        (fboundp vc-state-fcn)
                        ;; TODO: Klaus Berndl <klaus.berndl@sdm.de>:
                        ;; vc-cvs-state seems to change the window-config
                        ;; (opens a new small window) if it fails...so maybe
                        ;; we have to save the window-config before this call
                        ;; and restore it when the call fails - later... ;-)

                        ;; we must ignore errors here because it could be that
                        ;; a user has a certain VC-system not installed onto
                        ;; his machine but opens directories which have a
                        ;; CVS-subdir for example - then for such a directory
                        ;; ECB would eventually call this backend - but this
                        ;; would fail because the needed program is not
                        ;; installed - so we ignore this an handle this as
                        ;; unknown-state. 
                        (ignore-errors (funcall vc-state-fcn file))))
      ;; now we map the backend-state to one of the ECB-VC-state-values
      (setq result (or (cdr (assoc result ecb-vc-state-mapping)) 'unknown)))
    (if (not (equal result 'unchanged))
        ;; add the new state to the cache because either the list of checked
        ;; buffers and/or the state has been modified.
        (ecb-vc-cache-add-file file
                               result
                               checked-tree-buffer-names))
    ;; return the result - either 'unchanged or the new VC-state
    result))

(defun ecb-vc-update-sources-cache (dir)
  "Update the SOURCES cache for DIR with the current-content of the
sources-buffer if DIR has currently either a filtered or full cache entry in
the SOURCES-cache."
  (let* ((full-sources-cache (ecb-sources-cache-get-full dir))
         (filtered-sources-cache (and full-sources-cache
                                      (ecb-sources-cache-get-filtered dir))))
    (if filtered-sources-cache
        ;; we have currently a filtered sources-buffer so we must update the
        ;; filtered sources-cache.
        (ecb-sources-cache-add-filtered dir
                                        (list (tree-buffer-get-root)
                                              (ecb-copy-list tree-buffer-nodes)
                                              (buffer-substring (point-min)
                                                                (point-max))
                                              ;; add the old-filter-spec
                                              ;; because it must be the same
                                              (nth 3 filtered-sources-cache)))
      (if full-sources-cache
          ;; we have currently a cached sources-buffer without an applied
          ;; filter so we must update the full sources-cache.
          (ecb-sources-cache-add-full dir
                                      (list (tree-buffer-get-root)
                                            (ecb-copy-list tree-buffer-nodes)
                                            (buffer-substring (point-min)
                                                              (point-max))))))))

(defun ecb-vc-cvs-root-remote-p (root)
  "Return not nil if ROOT is a remote CVS-repository."
  (if (string-match "^:local:" root)
      nil
    (and (string-match "^\\(:ext:\\|:server:\\)?\\([^@]+@\\)?\\([^:]+\\):"
                       root)
         (match-string 3 root))))

;; some tests:
;; The following must all return cvs.sourceforge.net!
;; (ecb-vc-cvs-root-remote-p ":ext:berndl@cvs.sourceforge.net:/usr/local/root")
;; (ecb-vc-cvs-root-remote-p "berndl@cvs.sourceforge.net:/usr/local/root")
;; (ecb-vc-cvs-root-remote-p ":ext:cvs.sourceforge.net:/usr/local/root")
;; (ecb-vc-cvs-root-remote-p "cvs.sourceforge.net:/usr/local/root")
;; (ecb-vc-cvs-root-remote-p ":ext:berndl@cvs.sourceforge.net:C:/local/root")
;; (ecb-vc-cvs-root-remote-p "berndl@cvs.sourceforge.net:C:/local/root")
;; (ecb-vc-cvs-root-remote-p ":ext:cvs.sourceforge.net:C:/local/root")
;; (ecb-vc-cvs-root-remote-p "cvs.sourceforge.net:C:/local/root")
;; The following has to return nil!
;; (ecb-vc-cvs-root-remote-p "/local/root")
;; (ecb-vc-cvs-root-remote-p ":local:C:/local/root")
;; The following is allowed to return "C" because CVS forbids to use
;; windows-path as root without keyword :local:!
;; (ecb-vc-cvs-root-remote-p "C:/local/root")

(defun ecb-vc-dir-managed-by-CVS (directory)
  "Return 'CVS if DIRECTORY is managed by CVS. nil if not.

This function tries to be as smart as possible: First it checks if DIRECTORY
is managed by CVS by checking if there is a subdir CVS. If no then nil is
returned. If yes then for GNU Emacs it takes into account the value of
`vc-cvs-stay-local': If t then just return 'CVS. Otherwise ECB checks the root
repository if it is a remote repository. If not just 'CVS is returned. If a
remote repository it checks if the value of `vc-cvs-stay-local' is a string
and matches the host of that repository. If yes then just 'CVS is returned. If
not then ECB checks if that host is currently accessible by performing a ping.
If accessible 'CVS is returned otherwise nil. This has the advantage that ECB
will not be blocked by trying to get the state from a remote repository while
the host is not accessible \(e.g. because the user works offline).

Special remark for XEmacs: XEmacs has a quite outdated VC-package which has no
option `vc-cvs-stay-local' so the user can not work with remote
CVS-repositories if working offline for example. So if there is no option
`vc-cvs-stay-local' then ECB performs always the repository check mentioned
above and it depends on the value of `ecb-vc-xemacs-exclude-remote-repository'
if ECB treats such a directory as managed by CVS or not!"
  (and (ecb-file-exists-p (concat directory "/CVS/"))
       (or (ignore-errors (progn
                            (require 'vc)
                            (require 'vc-cvs)))
           t)
       (if (or (not (boundp 'vc-cvs-stay-local)) ;; XEmacs doesn't have this
               (not (eq vc-cvs-stay-local t)))
           ;; XEmacs has a quite outdated VC-package which has no option
           ;; `vc-cvs-stay-local' so the user can not work with remote
           ;; directories if working offline for example. so we use a
           ;; workaround by checking the root of the CVS-repsoitory (we can
           ;; get it from the file /CVS/Root) if it is a remote root and if
           ;; yes we ping the host of that root. If accessible ...
           (let* ((Root-content (ecb-file-content-as-string (concat directory
                                                                    "/CVS/Root")))
                  (host (and Root-content
                             (ecb-vc-cvs-root-remote-p Root-content))))
             (if (and host
                      ecb-vc-xemacs-exclude-remote-cvs-repository
                      (not (boundp 'vc-cvs-stay-local)))
                 nil
               (when (or (null host) ;; local repository
                         ;; vc-cvs-stay-local says VC should stay local for this
                         ;; host
                         (and (boundp 'vc-cvs-stay-local)
                              (stringp vc-cvs-stay-local)
                              (string-match vc-cvs-stay-local host))
                         ;; the host is at least accessible
                         (ecb-host-accessible-p host))
                 'CVS)))
         ;; VC always will stay local so we are satisfied ;-)
         'CVS)))


(defun ecb-vc-dir-managed-by-RCS (directory)
  "Return 'RCS if DIRECTORY is managed by RCS. nil if not."
  (and (ecb-file-exists-p (concat directory "/RCS/"))
       'RCS))

(defun ecb-vc-dir-managed-by-SVN (directory)
  "Return 'SVN if DIRECTORY is managed by SVN. nil if not."
  (and (ecb-file-exists-p (concat directory "/.svn/"))
       (locate-library "vc-svn")
       'SVN))

(defun ecb-vc-dir-managed-by-SCCS (directory)
  "Return 'SCCS if DIRECTORY is managed by SCCS. nil if not."
  (or (and (ecb-file-exists-p (concat directory "/SCCS/")) 'SCCS)
      ;; Remote SCCS project
      (let ((proj-dir (getenv "PROJECTDIR")))
        (if proj-dir
            (and (ecb-file-exists-p (concat proj-dir "/SCCS")) 'SCCS)
          nil))))

;; clearcase support

;; Problem: is this OK to assume, that the clearcase-specific
;; stuff is already loaded? may be we need more checks here.
(silentcomp-defun clearcase-file-is-in-view-p)
(defun ecb-vc-dir-managed-by-CC (directory)
  "Return 'CC if DIRECTORY is managed by ClearCase. nil if not."
  (and (fboundp 'clearcase-file-is-in-view-p)
       (if (clearcase-file-is-in-view-p directory)
           'CC)))

(silentcomp-defun clearcase-compute-next-action)
(defun ecb-vc-check-CC-state (file)
  "Checks the VC-state of FILE when under Control of Clearcase.
Returns the following different state-values: 'unknown, 'up-to-date, 'edited
and 'unlocked-changes."
  (let ((action (and (fboundp 'clearcase-compute-next-action)
                     (clearcase-compute-next-action file))))
    (cond
     ((eq action 'mkelem)
      'unknown)
     ((eq action 'checkout)
      'up-to-date)
     ((eq action 'uncheckout)
      'edited)
     ((eq action 'illegal-checkin)
      ;; ??? Is OK ???
      'unlocked-changes)
     ((eq action 'checkin)
      'edited))))

(defadvice clearcase-sync-from-disk (after ecb)
  "Ensures that the ECB-cache is reset and the entry for the currently
checked-in/out or added file is cleared. Does nothing if the function
`ecb-vc-dir-managed-by-CC' is not contained in `ecb-vc-supported-backends'!"
  (when (assoc 'ecb-vc-dir-managed-by-CC ecb-vc-supported-backends)
    (ecb-vc-cache-remove (ecb-fix-filename (ad-get-arg 0)))
    (ecb-vc-reset-vc-stealthy-checks)))

(defun ecb-vc-state (file)
  "Same as `vc-state' but it clears the internal caches of the VC-package for
FILE before calling `vc-state'. Finally calls `vc-state' and returns that value."
  (and (fboundp 'vc-file-clearprops) (vc-file-clearprops file))
  (vc-state file))

(defun ecb-vc-get-state-fcn-for-dir (directory)
  "Get that function which should be used for checking the VC-state for files
contained in DIRECTORY. Get it either from the VC-cache or call the car of
each element of `ecb-vc-supported-backends' and return the cdr of the first
elem where the car returns not nil. If Directory is not managed by a
version-control system then return nil. Store the result in the VC-cache for
speeding up things next time. Ange-ftp- or efs-directories will never be
checked for VC-states!"
  (let* ((norm-dir (ecb-fix-filename directory))
         (cache-val (ecb-vc-cache-get norm-dir)))
    (cond ((equal cache-val 'NO-VC)
           nil)
          (cache-val cache-val)
          (t
           (let ((vc-backend-fcn
                  (catch 'found
                    (dolist (elem ecb-vc-supported-backends)
                      (when (and (fboundp (car elem))
                                 (funcall (car elem) norm-dir))
                        (throw 'found (cdr elem))))
                    nil)))
             ;; Add it to the vc-cache: Either NO-VC if nil otherwise the
             ;; check-state-function
             (ecb-vc-cache-add-dir norm-dir (or vc-backend-fcn 'NO-VC))
             vc-backend-fcn)))))

(defalias 'ecb-vc-managed-dir-p 'ecb-vc-get-state-fcn-for-dir)

(defun ecb-vc-generate-node-name (name state)
  "Generate a node-name with an appropriate icon in the front of NAME
depending on STATE. If Emacs supports image-display then an image-icon wll be
used otherwise an ascii-icon."
  (let* ((ascii-icon (ecb-vc-get-ascii-icon-for-vc-state state))
         (node-name (concat ascii-icon " "
                            (save-match-data
                              (if (string-match "^(.) \\(.+\\)$" name)
                                  (match-string 1 name)
                                name)))))
    (ecb-generate-node-name node-name 4
                            (ecb-vc-get-image-name-for-vc-state state)
                            ;; even in the history- or the directories-buffers
                            ;; we use the icons of the sources-buffer because
                            ;; they are the same!
                            ecb-sources-buffer-name)))

;; (insert (ecb-vc-generate-node-name "test-name" 'needs-merge))

 (defun ecb-stealthy-vc-check--dir/history (state)
  "Check for all sourcefile-nodes either in the directories- or the
history-buffer the VC-state. This function does the real job and is is only
for use by a stealthy function defined with `defecb-stealthy'! STATE is the
initial state-value the stealthy-function has when called. Return the new
state-value."
  (if (not ecb-vc-enable-support)
      'done
    (if (not (or (string= (buffer-name (current-buffer))
                          ecb-history-buffer-name)
                 (and (string= (buffer-name (current-buffer))
                               ecb-directories-buffer-name)
                      (ecb-show-sources-in-directories-buffer-p))))
        'done
      ;; Now we are either in the history-buffer or in the directories-buffer
      ;; when sources are displayed in the directories-buffer
      (if (equal state 'restart)
          (setq state 1))
      ;; Here the state is an integer because a stealthy functions runs only
      ;; when state != 'done
      (let ((lines-of-buffer (count-lines (point-min) (point-max)))
            (curr-node nil)
            (curr-dir nil)
            (new-name nil)
            (vc-state-fcn nil)
            (new-state nil)
            (node-type-to-check (if (string= (buffer-name (current-buffer))
                                             ecb-history-buffer-name)
                                    ecb-history-nodetype-sourcefile
                                  ecb-directories-nodetype-sourcefile)))
        (save-excursion
          (while (and (not (input-pending-p))
                      (<= state lines-of-buffer))
            (goto-line state)
            (setq curr-node (tree-buffer-get-node-at-point))
            (setq curr-dir (ecb-file-name-directory (tree-node-get-data curr-node)))
            (when (and (= (tree-node-get-type curr-node) node-type-to-check)
                       (ecb-vc-directory-should-be-checked-p curr-dir))
              (setq vc-state-fcn (ecb-vc-get-state-fcn-for-dir curr-dir))
              (when vc-state-fcn ;; file is under VC-control
                (setq new-name (tree-node-get-name curr-node))
                (setq new-state
                      (ecb-vc-check-state (tree-node-get-data curr-node)
                                          (buffer-name (current-buffer))
                                          vc-state-fcn))
                ;; we update the node only if the state has changed 
                (when (not (equal 'unchanged new-state))
                  (setq new-name (ecb-vc-generate-node-name new-name new-state))
                  (tree-buffer-update-node
                   nil new-name
                   'use-old-value 'use-old-value 'use-old-value 'use-old-value t))))
            (setq state (1+ state))))
        (if (> state lines-of-buffer)
            (setq state 'done)))
      state)))

(defun ecb-stealthy-vc-check--sources (state)
  "Check for all sourcefile-nodes in sources-buffer the VC-state. This
function does the real job and is is only for use by a stealthy function
defined with `defecb-stealthy'! STATE is the initial state-value the
stealthy-function has when called. Return the new state-value."
  (if (not (ecb-vc-directory-should-be-checked-p ecb-path-selected-directory))
      'done
    (let ((vc-state-fcn (ecb-vc-get-state-fcn-for-dir ecb-path-selected-directory)))
      (if (null vc-state-fcn)
          ;; the sources-files are not under VC-control
          'done
        ;; Now we are either in the sources-, or history-buffer or in the
        ;; directories-buffer when sources are displayed in the
        ;; directories-buffer
        (if (equal state 'restart)
            (setq state 1))
        ;; Here the state is an integer because a stealthy functions runs only
        ;; when state != 'done
        (let ((lines-of-buffer (count-lines (point-min) (point-max)))
              (curr-node nil)
              (new-name nil)
              (new-state nil)
              (update-performed-for-dir nil))
          (save-excursion
            (while (and (not (input-pending-p))
                        (<= state lines-of-buffer))
              (goto-line state)
              (setq curr-node (tree-buffer-get-node-at-point))
              (setq new-name (tree-node-get-name curr-node))
              (setq new-state
                    (ecb-vc-check-state (tree-node-get-data curr-node)
                                        (buffer-name (current-buffer))
                                        vc-state-fcn))
              ;; we update the node only if the state has changed 
              (when (not (equal 'unchanged new-state))
                (setq new-name (ecb-vc-generate-node-name new-name new-state))
                (or update-performed-for-dir
                    (setq update-performed-for-dir
                          (ecb-fix-filename
                           (ecb-file-name-directory (tree-node-get-data curr-node)))))
                (tree-buffer-update-node
                 nil new-name
                 'use-old-value 'use-old-value 'use-old-value 'use-old-value t))
              (setq state (1+ state))))
          ;; if we have performed at least one update then we must update the
          ;; SOURCES-cache.
          (when update-performed-for-dir
            (ecb-vc-update-sources-cache update-performed-for-dir))
          (if (> state lines-of-buffer)
              (setq state 'done)))
        state))))

(defecb-stealthy ecb-stealthy-vc-check-in-history-buf
  "Check for all entries in the history-buffer their VC-state and
display an appropriate icon in front of the item."
  (save-selected-window
    (when (equal 'window-not-visible
                 (ecb-exec-in-history-window
                  (setq state
                        (ecb-stealthy-vc-check--dir/history state))))
      (setq state 'done))))


(defecb-stealthy ecb-stealthy-vc-check-in-sources-buf
  "Check for all sourcefile-nodes in the sources-buffer their VC-state and
display an appropriate icon in front of the file."
  (save-selected-window
    (when (equal 'window-not-visible
                 (ecb-exec-in-sources-window
                  (setq state
                        (ecb-stealthy-vc-check--sources state))))
      (setq state 'done))))

(defecb-stealthy ecb-stealthy-vc-check-in-directories-buf
  "Check for all sourcefile-nodes in the directories-buffer their VC-state and
display an appropriate icon in front of the file."
  (if (ecb-show-sources-in-directories-buffer-p)
      (save-selected-window
        (when (equal 'window-not-visible
                     (ecb-exec-in-directories-window
                      (setq state
                            (ecb-stealthy-vc-check--dir/history state))))
          (setq state 'done)))
    (setq state 'done)))

(defun ecb-vc-reset-vc-stealthy-checks ()
  "Resets all stealthy VC-checks."
  ;; we can call savely all these initialization because if one of the
  ;; following tree-windows is not visible nothing will be done (and the
  ;; directories-check will only run when sources are displayed in the
  ;; directories buffer!). If visible the vc-check will be performed for all
  ;; current visible file-nodes again in all visible tree-buffers of the
  ;; file-browser but because we have only removed the cache-entry for
  ;; exactly one file, the check will be very fast for all file-nodes
  ;; besides this file!

  ;; I think the read-only check must be performed too - because for
  ;; backends like Clearcase a changed VC-state can also result in a changed
  ;; read-only-state!
  (ecb-stealthy-function-state-init 'ecb-stealthy-ro-check-in-directories-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-ro-check-in-sources-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-sources-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-directories-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-history-buf)
  ;; This function is also used in write-file-hooks so we have to return nil
  ;; because otherwise a file will never be written - see documentation of
  ;; `write-file-hooks'!
  nil)
  
;; we have to add a smart piece of code to `vc-checkin-hook' which is able to
;; clear the cache entry for exactly that file checked-in with vc-checkin!
;; Problems to solve:
;; - unfortunatelly this hook is not called with the checked-in filename as
;;   argument but it is a normal hook runned with `run-hooks' :-( But we can
;;   not reset the stuff in the advice itself because this doesn't ensure that
;;   the after-advice-stuff is called *after* the checkin - seems that the
;;   after-advice runs already during the user inserts/edits the
;;   checkin-comment. But the vc-checkin-hook is really called after the
;;   checkin! ==> We use a combination of an after-advice and vc-checkin-hook!
;; - If a user uses PCL-CVS for CVS-operations this advice of vc-checkin will
;;   not run because pcl-cvs doesn't delegate the checkin-task to
;;   `vc-checkin'. Therefore also the `vc-checkin-hook' is not runned via
;;   pcl-cvs.
;; - What about other backends not supported by VC, e.g. clearcase.el? Well,
;;   with a good documentation what a user has to do.... ;-)


(defvar ecb-vc-advices '((vc-checkin . after)
                         (clearcase-sync-from-disk . after))
  "All advices needed for the builtin VC-support of ECB. Same format as
`ecb-basic-adviced-functions'.")

(defvar ecb-checkedin-file nil
  "Stored the filename of the most recent checked-in file. Is only set by the
after-advice of `vc-checkin' and `ecb-vc-checkin-hook' \(resets it to nil).
Evaluated only by `ecb-vc-checkin-hook'.

This is the communication-channel between `vc-checkin' and
`ecb-vc-checkin-hook' so this hook-function gets the filename of the
checked-in file.")

(defadvice vc-checkin (after ecb)
  "Simply stores the filename of the checked-in file in `ecb-checkedin-file'
so it is available in the `vc-checkin-hook'."
  (setq ecb-checkedin-file (ecb-fix-filename (ad-get-arg 0))))

(defun ecb-vc-checkin-hook ()
  "Ensures that the ECB-cache is reset and the entry for the most recent
checkedin file is cleared. Uses `ecb-checkedin-file' as last checked-in file."
  (when ecb-checkedin-file
    (ecb-vc-cache-remove ecb-checkedin-file)
    (ecb-vc-reset-vc-stealthy-checks)
    (setq ecb-checkedin-file nil)))

(defun ecb-vc-after-revert-hook ()
  "Ensures that the ECB-cache is reset and the entry for the currently
reverted file-buffer is cleared."
  (let ((file (ignore-errors (ecb-fix-filename buffer-file-name))))
    (when (and file (ecb-file-exists-p file))
      (ecb-vc-cache-remove file)
      (ecb-vc-reset-vc-stealthy-checks))))

(defun ecb-vc-enable-internals (arg)
  "Enable or disable \(if ARG < 0) all settings needed by the VC-support."
  (if (< arg 0)
      (progn
        (remove-hook 'after-revert-hook 'ecb-vc-after-revert-hook)
        (remove-hook 'write-file-hooks 'ecb-vc-reset-vc-stealthy-checks)
        (remove-hook 'vc-checkin-hook 'ecb-vc-checkin-hook)
        (ecb-disable-advices ecb-vc-advices))
    (add-hook 'after-revert-hook 'ecb-vc-after-revert-hook)
    (add-hook 'write-file-hooks 'ecb-vc-reset-vc-stealthy-checks)
    (add-hook 'vc-checkin-hook 'ecb-vc-checkin-hook)
    (ecb-enable-advices ecb-vc-advices)))

;; -- end of vc-support ---------------

;; TODO: Klaus Berndl <klaus.berndl@sdm.de>: Maybe we should run directly
;; `ecb-stealthy-updates' from within this after-update-hooks?!

(defun ecb-stealth-tasks-after-directories-update ()
  "After update hook for the directories-buffer. Runs directly after
performing a `tree-buffer-update' for this buffer."
  (ecb-stealthy-function-state-init 'ecb-stealthy-empty-dir-check)
  (ecb-stealthy-function-state-init 'ecb-stealthy-ro-check-in-directories-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-directories-buf)
  )

(defun ecb-stealth-tasks-after-sources-update ()
  "After update hook for the sources-buffer. Runs directly after
performing a `tree-buffer-update' for this buffer."
  (ecb-stealthy-function-state-init 'ecb-stealthy-ro-check-in-sources-buf)
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-sources-buf)
  )

(defun ecb-stealth-tasks-after-history-update ()
  "After update hook for the history-buffer. Runs directly after
performing a `tree-buffer-update' for this buffer."
  (ecb-stealthy-function-state-init 'ecb-stealthy-vc-check-in-history-buf)
  )

;; -- adding files ---------------------

(defun ecb-tree-node-add-files
  (node path files type include-extension old-children &optional not-expandable)
  "For every file in FILES add a child-node to NODE."
  (let* ((no-vc-state-display
          ;; no vc-state-display when the type of FILES means subdirs in
          ;; the directories-buffer
          (and (equal (buffer-name) ecb-directories-buffer-name)
               (= type ecb-directories-nodetype-directory)))
         (dir-managed-by-vc (if (or no-vc-state-display
                                    (not (ecb-vc-directory-should-be-checked-p path)))
                                nil
                              (ecb-vc-managed-dir-p path))))
    (dolist (file files)
      (let* ((filename (ecb-fix-filename path file))
             (file-1 (if include-extension
                         file
                       (ecb-file-name-sans-extension file))))
        (tree-node-add-child
         node
         (ecb-new-child
          old-children
          (if no-vc-state-display
              file-1
            (if dir-managed-by-vc
                (ecb-vc-generate-node-name file-1
                                           (nth 0 (ecb-vc-cache-get filename)))
              (ecb-generate-node-name file-1 -1 "leaf"
                                      ecb-sources-buffer-name)))
          type filename
          (or not-expandable
              (= type ecb-directories-nodetype-sourcefile)
              ;; The empty-dir-check is performed stealthy
              nil ;;(ecb-check-emptyness-of-dir filename)
              )
          (if ecb-truncate-long-names 'end)))))))

(defun ecb-new-child (old-children name type data
    &optional not-expandable shorten-name)
  "Return a node with type = TYPE, data = DATA and name = NAME. Tries to find
a node with matching TYPE and DATA in OLD-CHILDREN. If found no new node is
created but only the fields of this node will be updated. Otherwise a new node
is created."
  (catch 'exit
    (dolist (child old-children)
      (when (and (equal (tree-node-get-data child) data)
                 (= (tree-node-get-type child) type))
        (tree-node-set-name child name)
        (if not-expandable
            (tree-node-set-expandable child nil))
        (throw 'exit child)))
    (let ((node (tree-node-new name type data not-expandable nil
			       (if ecb-truncate-long-names 'end))))
      (tree-node-set-shorten-name node shorten-name)
      node)))


(defun ecb-add-source-path (&optional dir alias no-prompt-for-future-session)
  "Add a directory to the `ecb-source-path'."
  (interactive)
  ;; we must manually cut a filename because we must not add filenames to
  ;; `ecb-source-path'!
  (let* ((use-dialog-box nil)
         (my-dir (ecb-fix-filename
                  (or dir
                      (ecb-file-name-directory (read-file-name "Add source path: ")))
                  nil t))
         (my-alias (or alias
                       (read-string (format "Alias for \"%s\" (empty = no alias): "
                                            my-dir)))))
    (setq ecb-source-path (append ecb-source-path
                                  (list (if (> (length my-alias) 0)
                                            (list my-dir my-alias) my-dir))))
    (ecb-update-directories-buffer)
    (if (and (not no-prompt-for-future-session)
             (y-or-n-p "Add the new source-path also for future-sessions? "))
        (ecb-customize-save-variable 'ecb-source-path ecb-source-path)
      (customize-set-variable 'ecb-source-path ecb-source-path))))

(tree-buffer-defpopup-command ecb-add-source-path-node
  "Runs `ecb-add-source-path' from popup."
  (call-interactively 'ecb-add-source-path))


(tree-buffer-defpopup-command ecb-node-to-source-path
  "Add this node to the source-path."
  (ecb-add-source-path (tree-node-get-data node)))


(defun ecb-delete-s (child children sources)
  (when children
    (if (eq child (car children))
	(cdr sources)
      (cons (car sources) (ecb-delete-s child (cdr children) (cdr sources))))))


(tree-buffer-defpopup-command ecb-delete-source-path
  "Delete this source-path via popup."
  (let ((path (tree-node-get-data node)))
    (when (ecb-confirm (concat "Really delete source-path " path "?"))
      (setq ecb-source-path (ecb-delete-s
                             node (tree-node-get-children (tree-node-get-parent node))
                             ecb-source-path))
      (ecb-update-directories-buffer)
      (if (y-or-n-p "Delete source-path also for future-sessions? ")
          (ecb-customize-save-variable 'ecb-source-path ecb-source-path)
        (customize-set-variable 'ecb-source-path ecb-source-path)))))


(defun ecb-remove-dir-from-caches (dir)
  "Remove DIR from the caches SUBDIR, EMPTY-DIR and SOURCES."
  (ecb-files-and-subdirs-cache-remove dir)
  (ecb-directory-empty-cache-remove dir)
  (ecb-sources-cache-remove dir))

(defun ecb-directory-update-speedbar (dir)
  "Update the integrated speedbar if necessary."
  (and (ecb-speedbar-active-p)
       ;; depending on the value of `ecb-directory-update-speedbar' we have to
       ;; check if it is senseful to update the speedbar.
       (or (equal ecb-directories-update-speedbar t)
           (and (equal ecb-directories-update-speedbar 'auto)
                (not (or (get-buffer-window ecb-sources-buffer-name ecb-frame)
                         (member ecb-layout-name
                                 ecb-show-sources-in-directories-buffer))))
           (and (not (equal ecb-directories-update-speedbar 'auto))
                (functionp ecb-directories-update-speedbar)
                (funcall ecb-directories-update-speedbar dir)))
       (ecb-speedbar-update-contents)))


(defun ecb-directory-clicked (node ecb-button edit-window-nr shift-mode meta-mode)
  "Handle clicking onto NODE in the directories-buffer. ECB-BUTTON can be 1, 2
or 3. If 3 then EDIT-WINDOW-NR contains the number of the edit-window the NODE
should be displayed. For 1 and 2 the value of EDIT-WINDOW-NR is ignored."
  (if (= 3 (tree-node-get-type node))
      (funcall (tree-node-get-data node))
    (ecb-update-directory-node node)
    (if shift-mode
        (ecb-mouse-over-directory-node node nil nil 'force))
    (if (or (= ecb-directories-nodetype-directory
               (tree-node-get-type node))
            (= ecb-directories-nodetype-sourcepath
               (tree-node-get-type node)))
        (progn
          (if (= 2 ecb-button)
              (when (tree-node-is-expandable node)
                (tree-node-toggle-expanded node)
                (ecb-exec-in-directories-window
                 ;; Update the tree-buffer with optimized display of NODE
                 (tree-buffer-update node)))
            
            ;; Removing the element from the sources-cache, the
            ;; files-and-subdirs-cache and the empty-dirs-cache (incl. all
            ;; subdirs)
            (when shift-mode
              (ecb-remove-dir-from-caches (tree-node-get-data node))
              (ecb-directory-empty-cache-remove-all (tree-node-get-data node))
              ;; a powerclick should remove all vc-caches of contained files
              (ecb-vc-cache-remove-files-of-dir (tree-node-get-data node))
              )
            
            (ecb-set-selected-directory (tree-node-get-data node) shift-mode)
            ;; if we have running an integrated speedbar we must update the
            ;; speedbar 
            (ecb-directory-update-speedbar (tree-node-get-data node))))
          
;;           (ecb-exec-in-directories-window
;;            ;; Update the tree-buffer with optimized display of NODE
;;            (tree-buffer-update node)))
      (ecb-set-selected-source (tree-node-get-data node)
                               (ecb-combine-ecb-button/edit-win-nr ecb-button edit-window-nr)
			       shift-mode meta-mode))))


(defun ecb-source-clicked (node ecb-button edit-window-nr shift-mode meta-mode)
  "Handle clicking onto NODE in the sources-buffer. ECB-BUTTON can be 1, 2 or
3. If 3 then EDIT-WINDOW-NR contains the number of the edit-window the NODE
should be displayed. For 1 and 2 the value of EDIT-WINDOW-NR is ignored."
  (if shift-mode
      (ecb-mouse-over-source-node node nil nil 'force))
  (ecb-set-selected-source (tree-node-get-data node)
                           (ecb-combine-ecb-button/edit-win-nr ecb-button edit-window-nr)
			   shift-mode meta-mode))


(defun ecb-history-clicked (node ecb-button edit-window-nr shift-mode meta-mode)
  "Handle clicking onto NODE in the history-buffer. ECB-BUTTON can be 1, 2 or
3. If 3 then EDIT-WINDOW-NR contains the number of the edit-window the NODE
should be displayed. For 1 and 2 the value of EDIT-WINDOW-NR is ignored."
  (if shift-mode
      (ecb-mouse-over-history-node node nil nil 'force))
  (ecb-set-selected-source (tree-node-get-data node)
                           (ecb-combine-ecb-button/edit-win-nr ecb-button edit-window-nr)
                           shift-mode meta-mode))

(defun ecb-expand-directory-nodes (level)
  "Set the expand level of the nodes in the ECB-directories-buffer.
For argument LEVEL see `ecb-expand-methods-nodes'.

Be aware that for deep structured paths and a lot of source-paths this command
can last a long time - depending of machine- and disk-performance."
  (interactive "nLevel: ")
  (save-selected-window
    (ecb-exec-in-directories-window
     (dolist (node (tree-node-get-children (tree-buffer-get-root)))
       (tree-buffer-expand-node node level))
     (tree-buffer-update)))
  (ecb-current-buffer-sync 'force))


(defun ecb-get-file-info-text (file)
  "Return a file-info string for a file in the ECB sources buffer"
  (let ((attrs (ecb-file-attributes file)))
    (format "%s %8s %4d %10d %s %s"
	    (nth 8 attrs)
	    (user-login-name (nth 2 attrs))
	    (nth 3 attrs)
	    (nth 7 attrs)
	    (format-time-string "%Y/%m/%d %H:%M" (nth 5 attrs))
            (if (equal (ecb-show-node-info-what ecb-sources-buffer-name)
                       'file-info-full)
                file
              (ecb-file-name-nondirectory file)))
    ))


(defun ecb-mouse-over-directory-node (node &optional window no-message click-force)
  "Displays help text if mouse moves over a node in the directory buffer or if
CLICK-FORCE is not nil and always with regards to the settings in
`ecb-show-node-info-in-minibuffer'. NODE is the node for which help text
should be displayed, WINDOW is the related window, NO-MESSAGE defines if the
help-text should be printed here."
  (if (= (tree-node-get-type node) ecb-directories-nodetype-sourcefile)
      (ecb-mouse-over-source-node node window no-message click-force)
    (if (not (= (tree-node-get-type node) 3))
        (let ((str (when (or click-force
                             (ecb-show-minibuffer-info node window
                                                       ecb-directories-buffer-name)
                             (and (not (equal (ecb-show-node-info-when ecb-directories-buffer-name)
                                              'never))
                                  (not (ecb-string= (tree-node-get-data node)
                                                    (tree-node-get-name node)))
                                  (eq (tree-node-get-parent node)
                                      (tree-buffer-get-root))))
                     (if (equal (ecb-show-node-info-what ecb-directories-buffer-name)
                                'name)
                         (tree-node-get-name node)
                       (tree-node-get-data node)))))
          (prog1 str
            (unless no-message
              (tree-buffer-nolog-message str)))))))


(defun ecb-mouse-over-source-node (node &optional window no-message click-force)
  "Displays help text if mouse moves over a node in the sources buffer or if
CLICK-FORCE is not nil and always with regards to the settings in
`ecb-show-node-info-in-minibuffer'. NODE is the node for which help text
should be displayed, WINDOW is the related window, NO-MESSAGE defines if the
help-text should be printed here."
  (let ((str (ignore-errors ;; For buffers that hasn't been saved yet
               (when (or click-force
                         (ecb-show-minibuffer-info node window
                                                   ecb-sources-buffer-name))
                 (if (equal (ecb-show-node-info-what ecb-sources-buffer-name)
                            'name)
                     (tree-node-get-name node)
                   (ecb-get-file-info-text (tree-node-get-data node)))))))
    (prog1 str
      (unless no-message
        (tree-buffer-nolog-message str)))))


(defun ecb-mouse-over-history-node (node &optional window no-message click-force)
  "Displays help text if mouse moves over a node in the history buffer or if
CLICK-FORCE is not nil and always with regards to the settings in
`ecb-show-node-info-in-minibuffer'. NODE is the node for which help text
should be displayed, WINDOW is the related window, NO-MESSAGE defines if the
help-text should be printed here."
  (let ((str (ignore-errors ;; For buffers that hasn't been saved yet
               (when (or click-force
                         (ecb-show-minibuffer-info node window
                                                   ecb-history-buffer-name))
                 (if (equal (ecb-show-node-info-what ecb-history-buffer-name)
                            'name)
                     (tree-node-get-name node)
                   (tree-node-get-data node))))))
    (prog1 str
      (unless no-message
        (tree-buffer-nolog-message str)))))

;; popups

;; needs methods
(tree-buffer-defpopup-command ecb-create-source
  "Creates a new sourcefile in current directory."
  (let* ((use-dialog-box nil)
         (dir (ecb-fix-filename
               (funcall (if (ecb-file-directory-p (tree-node-get-data node))
                            'identity
                          'ecb-file-name-directory)
                        (tree-node-get-data node))))
         (filename (ecb-file-name-nondirectory
                    (read-file-name "Source name: " (concat dir "/")))))
    (ecb-select-edit-window)
    (if (string-match "\\.java$" filename)
        (ecb-jde-gen-class-buffer dir filename)
      (find-file (concat dir "/" filename)))
    (when (= (point-min) (point-max))
      (set-buffer-modified-p t)
      (let ((ecb-auto-update-methods-after-save nil))
        (save-buffer))
      (ecb-rebuild-methods-buffer-with-tagcache nil nil t))
    (ecb-remove-dir-from-caches dir)
    (ecb-set-selected-directory dir t)
    (ecb-current-buffer-sync)))


(defun ecb-grep-directory-internal (node find)
  (ecb-select-edit-window)
  (let* ((node-data (tree-node-get-data node))
         (default-directory (concat (ecb-fix-filename
                                     (if (ecb-file-directory-p node-data)
                                         node-data
                                       (ecb-file-name-directory node-data)))
                                    (ecb-directory-sep-string node-data))))
    (call-interactively (if find
                            (or (and (fboundp ecb-grep-find-function)
                                     ecb-grep-find-function)
                                'grep-find)
                          (or (and (fboundp ecb-grep-function)
                                   ecb-grep-function)
                              'grep)))))


(tree-buffer-defpopup-command ecb-grep-find-directory
  "Runs grep-find for current directory."
  (ecb-grep-directory-internal node t))


(tree-buffer-defpopup-command ecb-grep-directory
  "Runs grep for current directory."
  (ecb-grep-directory-internal node nil))


(defun ecb-create-directory (parent-node)
  (make-directory (concat (tree-node-get-data parent-node) "/"
                          (read-from-minibuffer "Directory name: ")))
  (ecb-update-directory-node parent-node)
  (tree-buffer-update))


(tree-buffer-defpopup-command ecb-delete-directory
  "Delete current directory."
  (let ((dir (tree-node-get-data node)))
    (when (ecb-confirm (concat "Really delete directory" dir "? "))
      (delete-directory (tree-node-get-data node))
      (ecb-update-directory-node (tree-node-get-parent node))
      (tree-buffer-update))))


(defun ecb-dired-directory-internal (node &optional other)
  (ecb-select-edit-window)
  (let ((dir (ecb-fix-filename
              (funcall (if (ecb-file-directory-p (tree-node-get-data node))
                           'identity
                         'ecb-file-name-directory)
                       (tree-node-get-data node)))))
    (ecb-with-adviced-functions
     (funcall (if other
                  'dired-other-window
                'dired)
              dir))))


(tree-buffer-defpopup-command ecb-dired-directory
  "Run dired for this directory."
  (ecb-dired-directory-internal node))


(tree-buffer-defpopup-command ecb-dired-directory-other-window
  "Run dired for this directory in the other window."
  (ecb-dired-directory-internal node 'other))


(defun ecb-dir-run-cvs-op (node op op-arg-list)
  (let ((dir (tree-node-get-data node)))
    (funcall op dir op-arg-list)))


(tree-buffer-defpopup-command ecb-dir-popup-cvs-status
  "Check status of directory \(and below) in pcl-cvs mode."
  (ecb-dir-run-cvs-op node 'cvs-status '("-v")))


(tree-buffer-defpopup-command ecb-dir-popup-cvs-examine
  "Examine directory \(and below) in pcl-cvs mode."
  (ecb-dir-run-cvs-op node 'cvs-examine '("-d" "-P")))


(tree-buffer-defpopup-command ecb-dir-popup-cvs-update
  "Update directory \(and below) in pcl-cvs mode."
  (ecb-dir-run-cvs-op node 'cvs-update '("-d" "-P")))


(defvar ecb-common-directories-menu nil)


(setq ecb-common-directories-menu
      '(("Grep"
         (ecb-grep-directory "Grep Directory")
         (ecb-grep-find-directory "Grep Directory recursive"))
        ;;("---")
        ("Dired"
         (ecb-dired-directory "Open in Dired")
         (ecb-dired-directory-other-window "Open in Dired other window"))
        ("---")
	(ecb-create-source "Create Sourcefile")
	(ecb-create-directory "Create Child Directory")
	(ecb-delete-directory "Delete Directory")
        ("---")
	(ecb-add-source-path-node "Add Source Path")))


(defvar ecb-directories-menu nil
  "Built-in menu for the directories-buffer for directories which are not a
source-path of `ecb-source-path'.")
(setq ecb-directories-menu
      (append
       ecb-common-directories-menu
       '((ecb-node-to-source-path "Make This a Source Path")
         ("---")
         (ecb-maximize-ecb-window-menu-wrapper "Maximize window"))))


(defvar ecb-directories-menu-title-creator
  (function (lambda (node)
              (let ((node-type (tree-node-get-type node))
                    (node-data (tree-node-get-name node)))
                    (cond ((= node-type ecb-directories-nodetype-directory)
                           (format "%s  (Directory)" node-data))
                          ((= node-type ecb-directories-nodetype-sourcefile)
                           (format "%s  (File)" node-data))
                          ((= node-type ecb-directories-nodetype-sourcepath)
                           (format "%s  (Source-path)" node-data))))))
  "The menu-title for the directories menu. Has to be either a string or a
function which is called with current node and has to return a string.")


(tree-buffer-defpopup-command ecb-open-source-in-editwin1
  "Open current source-file the 1. edit-window."
  ;; We can use `ecb-source-clicked' for history-buffer too because shift-mode
  ;; is nil.
  (ecb-source-clicked node 3 1 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin2
  "Open current source-file the 2. edit-window."
  (ecb-source-clicked node 3 2 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin3
  "Open current source-file the 3. edit-window."
  (ecb-source-clicked node 3 3 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin4
  "Open current source-file the 4. edit-window."
  (ecb-source-clicked node 3 4 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin5
  "Open current source-file the 5. edit-window."
  (ecb-source-clicked node 3 5 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin6
  "Open current source-file the 6. edit-window."
  (ecb-source-clicked node 3 6 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin7
  "Open current source-file the 7. edit-window."
  (ecb-source-clicked node 3 7 nil nil))
(tree-buffer-defpopup-command ecb-open-source-in-editwin8
  "Open current source-file the 8. edit-window."
  (ecb-source-clicked node 3 8 nil nil))

(defun ecb-dir/source/hist-menu-editwin-entries ()
  "Generate popup-menu-entries for each edit-window if there are at least 2
edit-windows. Otherwise return nil."
  (let ((edit-win-list (ecb-canonical-edit-windows-list))
        (result nil))
    (when (> (length edit-win-list) 1)
      (dotimes (i (min 8 (length edit-win-list)))
        (setq result
              (append result
                      (list (list (intern (format "ecb-open-source-in-editwin%d" (1+ i)))
                                  (format "edit-window %d" (1+ i)))))))
      (append (list (list "---")) ;; we want a separator
              (list (append (list "Open source-file in ...")
                            result))))))


(defun ecb-directories-menu-creator (tree-buffer-name)
  "Creates the popup-menus for the directories-buffer."
  (setq ecb-layout-prevent-handle-ecb-window-selection t)
  (let ((dyn-user-extension
         (and (functionp ecb-directories-menu-user-extension-function)
              (funcall ecb-directories-menu-user-extension-function)))
        (dyn-builtin-extension (ecb-dir/source/hist-menu-editwin-entries)))
    (list (cons ecb-directories-nodetype-directory
                (funcall (or ecb-directories-menu-sorter
                             'identity)
                         (append dyn-user-extension
                                 ecb-directories-menu-user-extension
                                 ecb-directories-menu)))
          (cons ecb-directories-nodetype-sourcefile
                (funcall (or ecb-sources-menu-sorter
                             'identity)
                         (append dyn-user-extension
                                 ecb-sources-menu-user-extension
                                 ecb-sources-menu
                                 dyn-builtin-extension)))
          (cons ecb-directories-nodetype-sourcepath
                (funcall (or ecb-directories-menu-sorter
                             'identity)
                         (append dyn-user-extension
                                 ecb-directories-menu-user-extension
                                 ecb-source-path-menu))))))

;; source-path tokens

(defvar ecb-source-path-menu nil
  "Built-in menu for the directories-buffer for directories which are elements of
`ecb-source-path'.")
(setq ecb-source-path-menu
      (append
       ecb-common-directories-menu
       '((ecb-delete-source-path "Delete Source Path")
         ("---")
         (ecb-maximize-ecb-window-menu-wrapper "Maximize window"))))


(tree-buffer-defpopup-command ecb-delete-source
  "Deletes current sourcefile."
  (let* ((file (tree-node-get-data node))
         (dir (ecb-fix-filename (ecb-file-name-directory file))))
    (when (ecb-confirm (concat "Really delete " (ecb-file-name-nondirectory file) "? "))
      (when (get-file-buffer file)
        (kill-buffer (get-file-buffer file)))
      (ecb-delete-file file)
      (ecb-remove-dir-from-caches dir)
      (ecb-set-selected-directory dir t))))


(tree-buffer-defpopup-command ecb-file-popup-ediff-revision
  "Diff file against repository with ediff."
  (let ((file (tree-node-get-data node)))
    (ediff-revision file)))


(tree-buffer-defpopup-command ecb-file-popup-vc-next-action
  "Checkin/out file."
  (let ((file (tree-node-get-data node)))
    (find-file file)
    (vc-next-action nil)))


(tree-buffer-defpopup-command ecb-file-popup-vc-log
  "Print revision history of file."
  (let ((file (tree-node-get-data node)))
    (find-file file)
    (vc-print-log)))


(tree-buffer-defpopup-command ecb-file-popup-vc-annotate
  "Annotate file"
  (let ((file (tree-node-get-data node)))
    (find-file file)
    (vc-annotate nil)))

(tree-buffer-defpopup-command ecb-file-popup-vc-diff
  "Diff file against last version in repository."
  (let ((file (tree-node-get-data node)))
    (find-file file)
    (vc-diff nil)))

(tree-buffer-defpopup-command ecb-file-popup-vc-refresh-file
  "Recompute the VC-state for this file."
  (let ((file (tree-node-get-data node)))
    (ecb-vc-cache-remove file)
    (ecb-vc-reset-vc-stealthy-checks)))

(tree-buffer-defpopup-command ecb-file-popup-vc-refresh-dir
  "Recompute the VC-state-values for the whole directory."
  (let ((dir (ecb-fix-filename (ecb-file-name-directory (tree-node-get-data node)))))
    (ecb-vc-cache-remove-files-of-dir dir)
    (ecb-vc-reset-vc-stealthy-checks)))

(defvar ecb-sources-menu nil
  "Built-in menu for the sources-buffer.")

(setq ecb-sources-menu
      '(("Grep"
         (ecb-grep-directory "Grep Directory")
         (ecb-grep-find-directory "Grep Directory recursive"))
        ("Dired"
         (ecb-dired-directory "Open Dir in Dired")
         (ecb-dired-directory-other-window "Open Dir in Dired other window"))
        ("Filter"
         (ecb-popup-sources-filter-by-ext "Filter by extension")
         (ecb-popup-sources-filter-by-regexp "Filter by a regexp")
         (ecb-popup-sources-filter-none "No filter"))
        ("---")        
	(ecb-create-source "Create Sourcefile")
        (ecb-delete-source "Delete Sourcefile")
        ("---")
        (ecb-maximize-ecb-window-menu-wrapper "Maximize window")))


(defvar ecb-sources-menu-title-creator
  (function (lambda (node)
              (ecb-file-name-nondirectory (tree-node-get-data node))))
  "The menu-title for the sources menu. See
`ecb-directories-menu-title-creator'.")

(defun ecb-sources-menu-creator (tree-buffer-name)
  "Creates the popup-menus for the sources-buffer."
  (setq ecb-layout-prevent-handle-ecb-window-selection t)
  (let ((dyn-user-extension
         (and (functionp ecb-sources-menu-user-extension-function)
              (funcall ecb-sources-menu-user-extension-function)))
        (dyn-builtin-extension (ecb-dir/source/hist-menu-editwin-entries)))
    (list (cons ecb-sources-nodetype-sourcefile
                (funcall (or ecb-sources-menu-sorter
                             'identity)
                         (append dyn-user-extension
                                 ecb-sources-menu-user-extension
                                 ecb-sources-menu
                                 dyn-builtin-extension))))))

;; history popups

(tree-buffer-defpopup-command ecb-history-kill-buffer
  "Kills the buffer for current entry."
  (let ((data (tree-node-get-data node)))
    (when (get-file-buffer data)
      (kill-buffer (get-file-buffer data)))))

(defun ecb-history-filter-by-ext (ext-str)
  "Filter history entries by extension."
  (if (= (length ext-str) 0)
      (setq ecb-history-filter
            (cons `(lambda (filename)
                     (save-match-data
                       (string-match "^[^.]+$" filename)))
                  "No ext."))
    (setq ecb-history-filter
          (cons `(lambda (filename)
                   (save-match-data
                     (string-match ,(format "\\.%s\\'" ext-str)
                                   filename)))
                (format "*.%s" ext-str))))
  (ecb-add-buffers-to-history))

(tree-buffer-defpopup-command ecb-popup-history-filter-by-ext
  "Filter history entries by extension by popup."
  (let ((ext-str (read-string "Insert the filter-extension without leading dot: "
                              (and node
                                   (ecb-file-name-extension (tree-node-get-data node))))))
    (ecb-history-filter-by-ext ext-str)))

(defun ecb-history-filter-by-regexp ()
  "Filter history entries by regexp."
  (let ((regexp-str (read-string "Insert the filter-regexp: ")))
    (if (> (length regexp-str) 0)
        (setq ecb-history-filter
              (cons `(lambda (filename)
                       (save-match-data
                         (string-match ,regexp-str filename)))
                    regexp-str))))
  (ecb-add-buffers-to-history))

(tree-buffer-defpopup-command ecb-popup-history-filter-by-regexp
  "Filter history entries by regexp by popup."
  (ecb-history-filter-by-regexp))
  
(tree-buffer-defpopup-command ecb-popup-history-filter-all-existing
  "No history filter, i.e. add all existing file-buffers to the history."
  (ecb-add-all-buffers-to-history))
  
(tree-buffer-defpopup-command ecb-file-popup-vc-refresh-all-files
  "Recompute the VC-state for the whole history."
  (when (equal (buffer-name) ecb-history-buffer-name)
    (let ((files (mapcar (function (lambda (node)
                                     (tree-node-get-data node)))
                         (tree-node-get-children (tree-buffer-get-root)))))
      (dolist (file files)
        (ecb-vc-cache-remove file))
      (ecb-vc-reset-vc-stealthy-checks))))

(defun ecb-history-filter ()
  "Apply a filter to the history-buffer to reduce the number of entries.
So you get a better overlooking. There are three choices:
- Filter by extension: Just insert the extension you want the History-buffer
  being filtered. Insert the extension without leading dot!
- Filter by regexp: Insert the filter as regular expression.
- No filter: This means to display an entry for all currently living
  file-buffers."
  (interactive)
  (let ((choice (ecb-query-string "Filter history by:"
                                  '("extension" "regexp" "no filter"))))
    (cond ((ecb-string= choice "extension")
           (ecb-history-filter-by-ext
            (read-string "Insert the filter-extension without leading dot: ")))
          ((ecb-string= choice "regexp")
           (ecb-history-filter-by-regexp))
          (t (ecb-add-all-buffers-to-history)))))

(defvar ecb-history-menu nil
  "Built-in menu for the history-buffer.")


(setq ecb-history-menu
      '(("Grep"
         (ecb-grep-directory "Grep Directory")
         (ecb-grep-find-directory "Grep Directory recursive"))
        ;;("---")
        ("Dired"
         (ecb-dired-directory "Open Dir in Dired")
         (ecb-dired-directory-other-window "Open Dir in Dired other window"))
	("Filter"
         (ecb-popup-history-filter-by-ext "Filter by extension")
         (ecb-popup-history-filter-by-regexp "Filter by regexp")
         (ecb-popup-history-filter-all-existing "No filter"))
        ("---")
        (ecb-popup-history-filter-all-existing "Exactly all living file-buffers")
        (ecb-history-kill-buffer "Kill Buffer")
        (ecb-delete-source "Delete Sourcefile")
        ("---")
        (ecb-maximize-ecb-window-menu-wrapper "Maximize window")))


(defvar ecb-history-menu-title-creator
  (function (lambda (node)
              (tree-node-get-name node)))
  "The menu-title for the history menu. See
`ecb-directories-menu-title-creator'.")

(defun ecb-history-menu-creator (tree-buffer-name)
  "Creates the popup-menus for the history-buffer."
  (setq ecb-layout-prevent-handle-ecb-window-selection t)
  (let ((dyn-user-extension
         (and (functionp ecb-history-menu-user-extension-function)
              (funcall ecb-history-menu-user-extension-function)))
        (dyn-builtin-extension (ecb-dir/source/hist-menu-editwin-entries)))
    (list (cons ecb-history-nodetype-sourcefile
                (funcall (or ecb-history-menu-sorter
                             'identity)
                         (append dyn-user-extension
                                 ecb-history-menu-user-extension
                                 ecb-history-menu
                                 dyn-builtin-extension))))))

;; create the tree-buffers

(defun ecb-create-directories-tree-buffer ()
  "Create the tree-buffer for directories"
  (tree-buffer-create
   ecb-directories-buffer-name
   ecb-frame
   ecb-tree-mouse-action-trigger
   'ecb-interpret-mouse-click
   'ecb-tree-buffer-node-select-callback
   'ecb-tree-buffer-node-expand-callback
   'ecb-tree-buffer-node-collapsed-callback
   'ecb-mouse-over-directory-node
   'equal
   (list ecb-directories-nodetype-directory)
   ;; Now no longer tree-buffer decides if a node is displayed as leave but
   ;; now the file-browser does it in the function `ecb-tree-node-add-files' -
   ;; Reason: We have now to deal with the VC-support
   nil ;;(list ecb-directories-nodetype-sourcefile)
   'ecb-directories-menu-creator
   (list (cons ecb-directories-nodetype-directory
               ecb-directories-menu-title-creator)
         (cons ecb-directories-nodetype-sourcefile
               ecb-directories-menu-title-creator)
         (cons ecb-directories-nodetype-sourcepath
               ecb-directories-menu-title-creator))
   (nth 0 ecb-truncate-lines)
   t
   ecb-tree-indent
   ecb-tree-incremental-search
   ecb-vc-incr-searchpattern-node-prefix
   ecb-tree-navigation-by-arrow
   ecb-tree-easy-hor-scroll
   (nth 0 ecb-tree-image-icons-directories)
   (nth 1 ecb-tree-image-icons-directories)
   ecb-tree-buffer-style
   ecb-tree-guide-line-face
   (list (cons ecb-directories-nodetype-sourcefile
               ecb-source-in-directories-buffer-face))
   ecb-tree-expand-symbol-before
   ecb-directory-face
   ecb-directories-general-face
   ;; we add an after-create-hook to the tree-buffer
   (append
    (list (function (lambda ()
                      (local-set-key [f2] 'ecb-customize)
                      (local-set-key [f3] 'ecb-show-help)
                      (local-set-key [f4] 'ecb-add-source-path)
                      (local-set-key (kbd "C-t")
                                     'ecb-toggle-RET-selects-edit-window)
                      (if (not ecb-running-xemacs)
                          (define-key tree-buffer-key-map
                            [mode-line mouse-2]
                            'ecb-toggle-maximize-ecb-window-with-mouse)))))
    ecb-common-tree-buffer-after-create-hook
    ecb-directories-buffer-after-create-hook)
   'ecb-stealth-tasks-after-directories-update
   ))

(defun ecb-create-sources-tree-buffer ()
  "Create the tree-buffer for sources"
  (tree-buffer-create
   ecb-sources-buffer-name
   ecb-frame
   ecb-tree-mouse-action-trigger
   'ecb-interpret-mouse-click
   'ecb-tree-buffer-node-select-callback
   'ecb-tree-buffer-node-expand-callback
   'ecb-tree-buffer-node-collapsed-callback
   'ecb-mouse-over-source-node
   'equal
   nil
   ;; If we want to display the VC-state in the sources-icon then we should
   ;; set this argument to nil because then we must compute the needed icon in
   ;; the file-browser and not in the tree-buffer-library (analogue to the
   ;; methods-icons computet in the methods-browser).
   nil ;; (list ecb-sources-nodetype-sourcefile)
   'ecb-sources-menu-creator
   (list (cons ecb-sources-nodetype-sourcefile ecb-sources-menu-title-creator))
   (nth 1 ecb-truncate-lines)
   t
   ecb-tree-indent
   ecb-tree-incremental-search
   ecb-vc-incr-searchpattern-node-prefix
   ecb-tree-navigation-by-arrow
   ecb-tree-easy-hor-scroll
   (nth 0 ecb-tree-image-icons-directories)
   (nth 2 ecb-tree-image-icons-directories)
   ecb-tree-buffer-style
   ecb-tree-guide-line-face
   nil
   ecb-tree-expand-symbol-before
   ecb-source-face
   ecb-sources-general-face
   (append
    (list (function (lambda ()
                      (local-set-key (kbd "C-t")
                                     'ecb-toggle-RET-selects-edit-window)
                      (if (not ecb-running-xemacs)
                          (define-key tree-buffer-key-map
                            [mode-line mouse-2]
                            'ecb-toggle-maximize-ecb-window-with-mouse)))))
    ecb-common-tree-buffer-after-create-hook
    ecb-sources-buffer-after-create-hook)
   'ecb-stealth-tasks-after-sources-update))

(defun ecb-create-history-tree-buffer ()
  "Create the tree-buffer for history"
  (tree-buffer-create
   ecb-history-buffer-name
   ecb-frame
   ecb-tree-mouse-action-trigger
   'ecb-interpret-mouse-click
   'ecb-tree-buffer-node-select-callback
   'ecb-tree-buffer-node-expand-callback
   'ecb-tree-buffer-node-collapsed-callback
   'ecb-mouse-over-history-node
   'equal
   nil
   nil
   'ecb-history-menu-creator
   (list (cons ecb-history-nodetype-sourcefile
               ecb-history-menu-title-creator))
   (nth 3 ecb-truncate-lines)
   t
   ecb-tree-indent
   ecb-tree-incremental-search
   ecb-vc-incr-searchpattern-node-prefix
   ecb-tree-navigation-by-arrow
   ecb-tree-easy-hor-scroll
   (nth 0 ecb-tree-image-icons-directories)
   (nth 4 ecb-tree-image-icons-directories)
   ecb-tree-buffer-style
   ecb-tree-guide-line-face
   nil
   ecb-tree-expand-symbol-before
   ecb-history-face
   ecb-history-general-face
   (append
    (list (function (lambda ()
                      (local-set-key (kbd "C-t")
                                     'ecb-toggle-RET-selects-edit-window)
                      (if (not ecb-running-xemacs)
                          (define-key tree-buffer-key-map
                            [mode-line mouse-2]
                            'ecb-toggle-maximize-ecb-window-with-mouse)))))
    ecb-common-tree-buffer-after-create-hook
    ecb-history-buffer-after-create-hook)
   'ecb-stealth-tasks-after-history-update))


(silentcomp-provide 'ecb-file-browser)

;;; ecb-file-browser.el ends here