Source

xetla / xetla-core.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
;;; xetla-core.el --- Core of xetla

;; Copyright (C) 2003-2004 by Stefan Reichoer (GPL)
;; Copyright (C) 2004 Steve Youngs (BSD)

;; Author:        Steve Youngs <steve@eicq.org>
;; Maintainer:    Steve Youngs <steve@eicq.org>
;; Created:       2004-11-25
;; Keywords:      arch archive tla

;; Based on xtla-core.el by: Stefan Reichoer, <stefan@xsteve.at>

;; This file is part of XEtla.

;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;;    notice, this list of conditions and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright
;;    notice, this list of conditions and the following disclaimer in the
;;    documentation and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the author nor the names of any contributors
;;    may be used to endorse or promote products derived from this
;;    software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
;; OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
;; IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

;;; Commentary:

;; Contributions from:
;;    Matthieu Moy <Matthieu.Moy@imag.fr>
;;    Masatake YAMATO <jet@gyve.org>
;;    Milan Zamazal <pdm@zamazal.org>
;;    Martin Pool <mbp@sourcefrog.net>
;;    Robert Widhopf-Fenk <hack@robf.de>
;;    Mark Triggs <mst@dishevelled.net>


;; This file provides the low-level functions used by xetla.el


;;; Code:

(require 'xetla-defs)
(require 'ewoc)

;; --------------------------------------
;; Compatibility stuff
;; --------------------------------------
(eval-when-compile
  (require 'cl)
  (autoload 'read-passwd "passwd"))

(require 'pp)

(defvar xetla-buffer-type-alist
  '((changes   "*xetla-changes*"   root)
    (inventory "*xetla-inventory*" path)
    (missing   "*xetla-missing*"   single)
    (cat-log   "*xetla-cat-log(%s)*" string)
    (file-diff "*xetla-file-diff*" path)
    (changelog "*xetla-changelog*" root)
    (tree-lint "*xetla-tree-lint*" root)
    (logs      "*xetla-logs*"      root)
    (errors    "*xetla-error*"     multiple)
    (generic   "*xetla-process*"   multiple)
    (browse    "*xetla-browse*"    single)
    (changeset "*xetla-changeset(%s)*" string))
  "List of (type name mode) used to generate a name for a buffer.

TYPE is the type of buffer to create, passed as the first argument to
`xetla-get-buffer-create'.

NAME is a string, used as a name for the returned buffer.

MODE is a symbol defining the way to manage (value of
`default-directory' in the created buffer) paths for this type of
buffers. It can have the following values:

 * 'root: `default-directory' will be the tree-root of the specified
    directory.

 * 'path: `default-directory' will be the path specified.

For 'root and 'path, `xetla-get-buffer-create' will return the existing
buffer for this type and this path if it exists, or create a new one
otherwise.

 * 'single: There is only one buffer of this type for each Emacs
   instance. If a path is provided, `default-directory' is set to that
   path. Otherwise, the path is left unchanged when a buffer is
   reused, and set to the current directory on buffer creation.

 * 'multiple: `default-directory' is set to the path specified. A new
   buffer is returned anyway. (No buffer reuse).

 * 'string: The path specified is actually a string. It won't be used
   to set `default-directory'. The name of the created buffer will be
   (format name string).")

(defvar xetla-buffers-tree nil
  "Tree containing all xetla buffers.

Must be of the form
 ((type1 (\"path1\" buffer \"original name of buffer\")
         (\"path2\" buffer2 \"original name of buffer2\"))
  (type2 (\"path1\" buffer3 \"original name of buffer3\")
         (\"path3\" buffer4 \"original name of buffer4\")))
Used to keep track of all the xetla related buffers.")

(defun xetla-buffers-tree-remove (buffer)
  "Remove BUFFER from the buffers tree."
    (dolist (type-cons xetla-buffers-tree)
      (dolist (path-buffer (cdr type-cons))
        (when (eq (cadr path-buffer) buffer)
          (setcdr type-cons (delete path-buffer (cdr type-cons)))))))

(defun xetla-buffers-tree-add (type path buffer)
  "Add a buffer of TYPE visiting PATH to the buffers tree.
BUFFER should be the buffer to add."
  (let ((current-assoc (assoc type xetla-buffers-tree)))
    (if current-assoc
        (setcdr current-assoc
                (cons (list path buffer (buffer-name buffer))
                      (cdr current-assoc)))
      (setq xetla-buffers-tree
            (cons `(,type (,path ,buffer ,(buffer-name buffer))) xetla-buffers-tree)))))

(defvar xetla-temp-directory (temp-directory)
  "Temporary directory for some xetla operations.")

(defun xetla-make-temp-name (file)
  "Generate a temporary file name based on FILE.
The path for the file name can be set via `xetla-temp-directory'."
  (make-temp-name (concat (xetla-uniquify-file-name xetla-temp-directory) file)))

(defun xetla-uniquify-file-name (path)
  "Return a unique string designating PATH.
If PATH is a directory,the returned contains one and exactly one trailing
slash.  If PATH is nil, then nil is returned."
  (and path
       (let ((expanded (expand-file-name
                        (if (file-directory-p path)
                            (file-name-as-directory path)
                          path))))
         (if (featurep 'xemacs)
             (replace-regexp-in-string "/+$" "/" expanded)
           expanded))))

(defun xetla-config-file-full-path (file &optional create-config-dir)
  "Return the full path for the config file FILE.
FILE will be stored in the `xetla-config-directory'.
If CREATE-CONFIG-DIR is non nil, ensure that the `xetla-config-directory'
does exist."
  (let ((full-name (xetla-uniquify-file-name
                    (concat xetla-config-directory file))))
    (unless (file-exists-p xetla-config-directory)
      (when create-config-dir
        (make-directory xetla-config-directory t)
        (message "The config files of Xetla will be stored in %s!"
                 xetla-config-directory)
        (sit-for 5)))
    ;; TODO remove migration code as some time in the future
    (unless (file-exists-p (expand-file-name xetla-bookmarks-file-name
                                             xetla-config-directory))
      (let ((old-ones (list (list (expand-file-name xetla-bookmarks-file-name
                                                    xetla-config-directory)
                                  "~/.xetla-bookmarks.el"
                                  "~/.xetla/.xetla-bookmarks.el")))
            o olds n)
        (while old-ones
          (setq olds (car old-ones) old-ones (cdr old-ones))
          (if olds (setq n (car olds) olds (cdr olds)))
          (while olds
            (setq o (expand-file-name (car olds)) olds (cdr olds))
            (if (file-exists-p o)
                (if (yes-or-no-p (format "Migrate %s to %s? " o n))
                    (rename-file o n)
                  (if (yes-or-no-p (format "Delete %s? " o))
                      (delete-file o))))))))
    ;; return full-name
    full-name))

(defun xetla-stringise (uberstring &rest args)
  "Create a string from UBERSTRING.
I.e. you can pass 
- a string which evals to itself
- a variable whose value is a string
- a function which is called and should eval to a string
- a form which is evaluated and should return a string.

All results are run against `xetla-stringise' again
until finally a string is produced."
  (cond ((stringp uberstring)
         uberstring)
        ((and (symbolp uberstring)
              (boundp uberstring))
         (xetla-stringise (symbol-value uberstring)))
        ((and (symbolp uberstring)
              (fboundp uberstring))
         (xetla-stringise (apply uberstring args)))
        ((ignore-errors (xetla-stringise (eval uberstring))))
        ((ignore-errors (xetla-stringise (eval (cons 'progn uberstring)))))
        (t nil)))

;; this is useful since i can now have something like:
;;
;; (set-alist 'xetla-buffer-type-alist
;;            'inventory
;;            '((format "*xetla-inventory%s*"
;;                      (let ((dir (replace-regexp-in-string
;;                                  "^.+/\\([^/]+\\).?$"
;;                                  "\\1"
;;                                  (expand-file-name path))))
;;                        (if dir (format " (%s)" dir)
;;                          "")))))
;;
;; to always have the path in the buffer name of the inventory

(defun xetla-get-buffer-type (type)
  "Get entry in `xetla-buffer-type-alist' for given TYPE."
  (assoc type xetla-buffer-type-alist))

(defun xetla-get-buffer-name (type)
  "Get name part of `xetla-buffer-type-alist' for given TYPE."
  (let ((name (cadr (xetla-get-buffer-type type))))
    (xetla-stringise name)))

(defun xetla-get-buffer-mode (type)
  "Get name part of `xetla-buffer-type-alist' for given TYPE."
  (let ((mode (caddr (xetla-get-buffer-type type))))
    mode))

(eval-when-compile
  (autoload 'xetla-tree-root "xetla"))

(defun xetla-get-buffer-create (type &optional path)
  "Get a buffer of type TYPE for the path PATH.

Maybe reuse one if it exists, according to the value of
`xetla-buffer-type-alist' (see its docstring), or, call
`create-file-buffer' to create the buffer.

See also `xetla-get-buffer'"
  ;; Inspired from `cvs-get-buffer-create'
  (let* ((path (or path default-directory))
         (elem (assoc type xetla-buffer-type-alist))
         (mode (caddr elem)))
    (or (xetla-get-buffer type path mode)
        ;; Buffer couldn't be reused. Create one
        (let ((path (case mode
                      (root (xetla-uniquify-file-name
                             (xetla-tree-root path)))
                      (string path)
                      (t (xetla-uniquify-file-name path))))
              (name (xetla-get-buffer-name type)))
          (let ((buffer
                 (if (eq mode 'string)
                     (get-buffer-create (format name path))
                   (let ((default-directory (or path default-directory)))
                     (create-file-buffer (or name "*xetla-buffer*"))))))
            (with-current-buffer buffer
              (xetla-buffers-tree-add type path buffer)
              buffer))))))

(add-hook 'kill-buffer-hook 'xetla-kill-buffer-function)

(defun xetla-kill-buffer-function ()
  "Function run when a buffer is killed."
  (xetla-buffers-tree-remove (current-buffer))
  (xetla-kill-process-maybe (current-buffer)))

(defun xetla-get-buffer (type &optional path mode)
  "Get a buffer of type TYPE for the path PATH.

Maybe reuse one if it exists, depending on the value of MODE (see
`xetla-buffer-type-alist' 's third element), otherwise, return nil.  See
also `xetla-get-buffer-create'."
  (let ((mode (or mode (xetla-get-buffer-mode type)))
        (path (or path default-directory)))
    (if (eq mode 'single)
        ;; nothing to do about PATH. Reuse anyway
        (let* ((list-path (cdr (assoc type xetla-buffers-tree)))
               (first-elem (car list-path)))
          (if list-path
              (if (string= (buffer-name (cadr first-elem))
                           (caddr first-elem))
                  (cadr first-elem)
                (setcdr (assoc type xetla-buffers-tree) nil)
                nil)
            nil))
      (let ((path (and path
                       (case mode
                         (root (xetla-uniquify-file-name
                                (xetla-tree-root path)))
                         (string path)
                         (t (xetla-uniquify-file-name path))))))
        (if (eq mode 'multiple)
            ;; no need to search an existing buffer
            nil
          (let* ((list-path (assoc type xetla-buffers-tree))
                 (elem (assoc path (cdr list-path)))
                 (buffer (cadr elem)))
            (when buffer
              (if (and (buffer-live-p buffer)
                       ;; the buffer has not been renamed
                       (string= (buffer-name buffer)
                                (caddr elem)))
                  buffer
                ;; remove the buffer and try again
                (setcdr list-path
                        (delq (assoc path (cdr list-path))
                              (cdr list-path)))
                (xetla-get-buffer type path mode)))))))))

(defun xetla-add-buffer-type (type name)
  "Define a new TYPE of buffer whose buffer will be named NAME."
  (unless (assoc type xetla-buffer-type-alist)
    (push (list type name) xetla-buffer-type-alist)))

(defun xetla-position (item seq)
  "Position of ITEM in list, or nil if not found.
Return 0 if ITEM is the first element of SEQ"
  (let ((pos 0)
        (seq-int seq))
    (while (and seq-int
                (not (eq (car seq-int) item)))
      (setq seq-int (cdr seq-int))
      (setq pos (1+ pos)))
    (when seq-int pos)))


(defun xetla-last-visited-inventory-buffer ()
  "Return the last visited xetla's inventory buffer."
  (let ((inventories (remove nil (mapcar
                                  (lambda (elt)
                                    (when (buffer-live-p (cadr elt))
                                      elt))
                                  (cdr (assoc 'inventory xetla-buffers-tree)))))
        (bl (buffer-list)))
    (cadr (car (sort inventories (lambda (a b)
                                   (let ((aindex (xetla-position (cadr a) bl))
                                         (bindex (xetla-position (cadr b) bl)))
                                     (< aindex bindex))))))))

(defun xetla-show-inventory-buffer ()
  "Switch to the last visited inventory buffer."
  (interactive)
  (xetla-switch-to-buffer (xetla-last-visited-inventory-buffer)))

;; --------------------------------------
;; Process buffers
;; --------------------------------------

(defcustom xetla-process-buffer " *xetla-process*"
  "*Name of the process buffer."
  :type 'string
  :group 'xetla-internal)

(defcustom xetla-error-buffer " *xetla-errors*"
  "*Name of the buffer to which xetla's stderr is redirected."
  :type 'string
  :group 'xetla-internal)

(defcustom xetla-number-of-dead-process-buffer 20
  "*Number of process buffers to keep after process termination.
When the number of process buffers exceeds this number, the most ancient
is killed.  This includes both the process buffer and the error
buffer (to which stderr is redirected).

A nil value here means \"Never kill any process buffer\". Useful for
debugging, but this will eat the memory of your computer ;-)"
  :type 'integer
  :group 'xetla-internal)

(defcustom xetla-show-internal-buffers-on-menu nil
  "Toggle display of dead process buffers in the buffer menu."
  :type 'boolean
  :group 'xetla-internal)

(defvar xetla-dead-process-buffer-queue nil
  "List of process buffers belonging to terminated processes.
When the list is greater than `xetla-number-of-dead-process-buffer', the last
ones are killed.")

(defun xetla-kill-process-buffer (buffer)
  "Don't actually kill BUFFER, but add it to `xetla-dead-process-buffer-queue'.
It will eventually be killed when the number of buffers in
`xetla-dead-process-buffer-queue'exceeds `xetla-number-of-dead-process-buffer'."
  (add-to-list 'xetla-dead-process-buffer-queue buffer t)
  (setq xetla-dead-process-buffer-queue
        (remove-if-not #'buffer-live-p xetla-dead-process-buffer-queue))
  (when xetla-number-of-dead-process-buffer
    (while (> (length xetla-dead-process-buffer-queue)
              (max 2 xetla-number-of-dead-process-buffer))
      (let ((currbuf (car xetla-dead-process-buffer-queue)))
        ;; just to be completely certain
        (when (buffer-live-p currbuf)
          (kill-buffer currbuf))
        ;; now remove that killed buffer
        (setq xetla-dead-process-buffer-queue
              (cdr xetla-dead-process-buffer-queue))))))

(defvar xetla-last-process-buffer nil
  "The last created process buffer.")

(defvar xetla-last-error-buffer nil
  "The last created process buffer.")

(defun xetla-new-process-buffer (to-be-deleted)
  "Create a new process buffer.
If TO-BE-DELETED is non-nil, make this buffer a candidate for eventually
being deleted."
  (let ((buffer (create-file-buffer xetla-process-buffer)))
    (setq xetla-last-process-buffer buffer)
    (when to-be-deleted (xetla-kill-process-buffer buffer))
    buffer))

(defun xetla-new-error-buffer (to-be-deleted)
  "Create a new error buffer.
If TO-BE-DELETED is non-nil, make this buffer a candidate for eventually
being deleted."
  (let ((buffer (create-file-buffer xetla-error-buffer)))
    (setq xetla-last-error-buffer buffer)
    (when to-be-deleted (xetla-kill-process-buffer buffer))
    buffer))

;; --------------------------------------
;; Process management
;; --------------------------------------

;; Candidates for process handlers
(defun xetla-default-error-function (output error status arguments)
  "Default function called when a xetla process ends with a non-zero status.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (if (> (with-current-buffer error (point-max)) 1)
      (xetla-show-error-buffer error)
    (if (> (with-current-buffer output (point-max)) 1)
        (xetla-show-error-buffer output)
      (error "`tla %s' failed with code %d and no output!"
             (mapconcat 'identity arguments " ")
             status)))
  (error "`tla %s' failed with code %d"
         (mapconcat 'identity arguments " ")
         status))

(defvar xetla-default-killed-function-noerror 0
  "The number of killed processes we will ignore until throwing an error.
If the value is 0, `xetla-default-killed-function' will throw an error.
See `xetla-default-killed-function'.")

(defun xetla-default-killed-function (output error status arguments)
  "Default function called when a xetla process is killed.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (if (> xetla-default-killed-function-noerror 0)
      (setq xetla-default-killed-function-noerror
            (- xetla-default-killed-function-noerror 1))
    (xetla-switch-to-buffer error)
    (error "`tla %s' process killed !"
           (mapconcat 'identity arguments " "))))

(defun xetla-null-handler (output error status arguments)
  "Handle a finished process without doing anything.
Candidate as an argument for one of the keywords :finished, :error or :killed
in `xetla-run-tla-sync' or `xetla-run-tla-async'.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  nil)

(defun xetla-status-handler (output error status arguments)
  "Return an integer value that reflects the process status.
Candidate as an argument for one of the keywords :finished, :error or :killed
in `xetla-run-tla-sync' or `xetla-run-tla-async'.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (cond ((numberp status) status)
        ((string-match "^exited abnormally with code \\(.*\\)" status)
         (string-to-int (match-string 1)))
        (t (error status))))

(defun xetla-output-buffer-handler (output error status arguments)
  "Return the output of a finished process, stripping any trailing newline.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (xetla-buffer-content output))

(defun xetla-output-buffer-split-handler (output error status arguments)
  "Return the output of a finished process as a list of lines.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (split-string (xetla-buffer-content output) "\n"))

(defun xetla-default-finish-function (output error status arguments)
  "Default function called when a xetla process terminates.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (with-current-buffer output
    (xetla-process-buffer-mode))
  (xetla-switch-to-buffer output)
  (message "`tla %s' process finished !"
           (mapconcat 'identity arguments " "))
  status)

(defun xetla-finish-function-without-buffer-switch (output error status arguments)
  "Similar to `xetla-default-finish-function' but no buffer switch.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
STATUS indicates the return status of the program.
ARGUMENTS is a list of the arguments that the process was called with."
  (message "`tla %s' process finished !"
           (mapconcat 'identity arguments " "))
  status)

(defvar xetla-log-cookie nil)

(defstruct (xetla-event) output-buffer error-buffer related-buffer
  command tree event time)

(defun xetla-strip-final-newline (string)
  "Strip the final newline from STRING if there's one."
  (if (eq (aref string (- (length string) 1)) ?\n)
      (substring string 0 (- (length string) 1))
    string))

(defsubst xetla-log-printer-print-buffer (buffer function)
  "Helper function for `xetla-log-printer'.
Print a buffer filed for BUFFER during printing a log event.
The printed name of BUFFER is mouse sensitive.  If the user
clicks it, FUNCTION is invoked."
  (xetla-face-add
   (or (buffer-name buffer)
       (pp-to-string buffer))
   'xetla-buffer
   (when (buffer-live-p buffer)
     (let ((map (make-sparse-keymap)))
       (define-key map [button2] function)
       map))
   nil
   "Show the buffer"))

(defun xetla-log-printer (elem)
  "XEtla event printer which prints ELEM."
  (let ((event (xetla-event-event elem))
        (p (point)))
    (insert
     "Command: " (xetla-event-command elem)
     "\nDirectory: " (xetla-face-add (xetla-event-tree elem)
                                    'xetla-local-directory)
     "\nDate: " (format-time-string "%c" (xetla-event-time elem))
     "\nRelated Buffer: " (xetla-log-printer-print-buffer
                           (xetla-event-related-buffer elem)
                           'xetla-switch-to-related-buffer-by-mouse)
     "\nOutput Buffer: "  (xetla-log-printer-print-buffer
                           (xetla-event-output-buffer elem)
                           'xetla-switch-to-output-buffer-by-mouse)
     "\nError Buffer: "   (xetla-log-printer-print-buffer
                           (xetla-event-error-buffer elem)
                           'xetla-switch-to-error-buffer-by-mouse)
     (if (not (string= event "started"))
         (concat "\nEvent: " event)
       "")
     "\n")
    ;; Reflect the point to `default-directory'.
    ;; NOTE: XEmacs doesn't have `point-entered' special text property.
    (put-text-property
     p (point)
     'point-entered (lambda (old new)
                      (setq default-directory
                            (xetla-event-tree
                             (ewoc-data
                              (ewoc-locate xetla-log-cookie))))))
    ))

(defvar xetla-process-running nil
  "List of xetla processes running.
A value of nil indicates no processes are running.

The list is a list of pairs (process event) where EVENT is the event
corresponding to the beginning of the execution of process.  It can be
used to get more info about the process.")

(defmacro xetla-switch-to-buffer-macro (function accessor)
  "Define a FUNCTION for switching to the buffer associated with some event.
ACCESSOR is a function for retrieving the appropriate buffer from a
`xetla-event'structure."
  `(defun ,function ()
     "In a log buffer, pops to the output or error buffer corresponding to the
process at point"
     (interactive)
     (let ((buffer (,accessor
                    (ewoc-data (ewoc-locate xetla-log-cookie)))))
       (cond ((buffer-live-p buffer)
              (xetla-switch-to-buffer buffer)
              (unless (member buffer
                              (mapcar (lambda (p)
                                        (process-buffer (car p)))
                                      xetla-process-running))
                (xetla-process-buffer-mode)))
             (t (error "Buffer has been killed"))))))

(xetla-switch-to-buffer-macro xetla-switch-to-output-buffer
                             xetla-event-output-buffer)

(xetla-switch-to-buffer-macro xetla-switch-to-error-buffer
                             xetla-event-error-buffer)

(xetla-switch-to-buffer-macro xetla-switch-to-related-buffer
                             xetla-event-related-buffer)

(defmacro xetla-make-bymouse-function (function)
  "Create a new function by adding mouse interface to FUNCTION.
The new function is named FUNCTION-by-mouse; and takes one argument,
a mouse click event.
Thew new function moves the point to the place where mouse is clicked
then invoke FUNCTION."
  `(defun ,(intern (concat (symbol-name function) "-by-mouse")) (event)
     ,(concat "`" (symbol-name function) "'" " with mouse interface.")
     (interactive "e")
     (mouse-set-point event)
     (,function)))

(xetla-make-bymouse-function xetla-switch-to-output-buffer)
(xetla-make-bymouse-function xetla-switch-to-error-buffer)
(xetla-make-bymouse-function xetla-switch-to-related-buffer)

(defun xetla-log-event (output error command tree event)
  "Log an event in the `xetla-log-buffer' buffer.
OUTPUT is the buffer containing process standard output.
ERROR is the buffer containing process error output.
COMMAND is the command that was executed.
TREE is the process's working directory.
EVENT is the event that occurred.
Returns that event."
  (unless (and xetla-log-cookie
               (buffer-live-p (ewoc-buffer xetla-log-cookie)))
    (with-current-buffer (get-buffer-create xetla-log-buffer)
      (setq xetla-log-cookie
            (ewoc-create 'xetla-log-printer))
      (xetla-log-buffer-mode)))
  (let ((related-buffer (current-buffer)))
    (with-current-buffer (ewoc-buffer xetla-log-cookie)
      (let ((elem (make-xetla-event :output-buffer output
                                   :error-buffer error
                                   :related-buffer related-buffer
                                   :command command
                                   :tree tree
                                   :event event
                                   :time (current-time)))
            buffer-read-only)
        (ewoc-enter-last xetla-log-cookie elem)
        (ewoc-refresh xetla-log-cookie)
        elem))))

(defun xetla-log-next ()
  "Move to the next log entry."
  (interactive)
  (let ((next (ewoc-next xetla-log-cookie
                         (ewoc-locate xetla-log-cookie))))
    (when next (goto-char (ewoc-location next)))))

(defun xetla-log-prev ()
  "Move to the previous log entry."
  (interactive)
  (let ((prev (ewoc-prev xetla-log-cookie
                         (ewoc-locate xetla-log-cookie))))
    (when prev (goto-char (ewoc-location prev)))))

(define-derived-mode xetla-log-buffer-mode fundamental-mode "XEtla Log"
  "Major mode for Xetla's internal log buffer. You can open this buffer
with `xetla-open-internal-log-buffer'."
  (toggle-read-only 1))

(define-derived-mode xetla-process-buffer-mode fundamental-mode
  "XEtla Process"
  "Major mode for process buffers. Mainly defines \\[bury-buffer]
to quit the buffer"
  (toggle-read-only 1))

(defmacro xetla-with-keywords (keywords plist &rest body)
  "Execute a body of code with keywords bound.
Each keyword listed in KEYWORDS is bound to its value from PLIST, then
BODY is evaluated."
  (flet ((keyword-to-symbol (keyword)
                            (intern (substring (symbol-name keyword) 1))))
    (let ((keyword (make-symbol "keyword"))
          (default (make-symbol "default")))
      `(let ,(mapcar (lambda (keyword-entry)
                       (keyword-to-symbol (if (consp keyword-entry)
                                              (car keyword-entry)
                                            keyword-entry)))
                     keywords)
         (dolist (keyword-entry ',keywords)
           (let ((,keyword (if (consp keyword-entry)
                               (car keyword-entry)
                             keyword-entry))
                 (,default (if (consp keyword-entry)
                               (cadr keyword-entry)
                             nil)))
             (set (intern (substring (symbol-name ,keyword) 1))
                  (or (cadr (member ,keyword ,plist))
                      ,default))))
         ,@body))))
(put 'xetla-with-keywords 'lisp-indent-function 1)

(defun xetla-build-xetla-command (list-args)
  "Build a shell command to run tla with args LIST-ARGS."
  (mapconcat 'shell-quote-argument
             (cons xetla-tla-executable
                   (delq nil list-args))
             " "))


(defcustom xetla-password-prompt-regexp
  "[Pp]ass\\(word\\|phrase\\).*:\\s *\\'"
  "*Regexp matching prompts for passwords in the inferior process.
This is used by `eshell-watch-for-password-prompt'."
  :type 'regexp
  :group 'xetla)

(defun xetla-process-filter (proc string)
  "Filter PROC's STRING.
Prompt for password with `read-passwd' if the output of PROC matches
`xetla-password-prompt-regexp'."
  (with-current-buffer (process-buffer proc)
    (insert (replace-regexp-in-string "\015" "\n" string))
    (when (string-match xetla-password-prompt-regexp string)
      (string-match "^\\([^\n]+\\)\n*\\'" string)
      (let ((passwd (read-passwd (match-string 1 string))))
        (process-send-string proc (concat passwd "\n"))))))

(defun xetla-run-tla-async (arguments &rest keys)
  "Run tla asynchronously.
ARGUMENTS is a list of arguments.  nil values in this list are removed.
KEYS is a list of keywords and values.  Possible keywords are:

 :finished ....... Function run when the process finishes.  If none
                   specified, `xetla-default-finish-function' is run.

 :killed ......... Function run when the process is killed.  If none
                   specified, `xetla-default-killed-function' is run.

 :error .......... Function run when the process exits with a non 0
                   status.  If none specified,
                   `xetla-default-error-function' is run.

All these functions take 4 arguments : output, error, status, and
arguments.

   - \"output\" is the output buffer
   - \"error\" is the buffer where standard error is redirected
   - \"status\" is the numeric exit-status or the signal number
   - \"arguments\" is the list of arguments, as a list of strings,
              like '(\"changes\" \"-diffs\")

   `xetla-null-handler' can be used here if there's nothing to do.

 :output-buffer .. Buffer where the output of the process should be
                   redirected.  If none specified, a new one is
                   created, and will be entered in
                   `xetla-dead-process-buffer-queue' to be killed
                   later.

 :error-buffer ... Buffer where the standard error of the process
                   should be redirected.

 :related-buffer . Defaults to `current-buffer'.  This is the buffer
                   where the result of the process will be used.  If
                   this buffer is killed before the end of the
                   execution, the user is prompted if he wants to kill
                   the process.

Example:
  (xetla-run-tla-async `(\"changes\" ,(unless arg \"-diffs\"))
                      :finished
                      (lambda (output error status arguments)
                        (message \"No changes in this working copy\"))
                      :error
                      (lambda (output error status arguments)
                        (xetla-show-changes-buffer output)))"
  (xetla-with-keywords
      (:finished :killed :error :output-buffer :error-buffer :related-buffer)
    keys
    (let* ((output-buf (or (and output-buffer (get-buffer-create output-buffer))
                           (xetla-new-process-buffer nil)))
           (error-buf  (or (and error-buffer (get-buffer-create error-buffer))
                           (xetla-new-error-buffer nil)))
           (error-file (xetla-make-temp-name "arch-errors"))
           (command (xetla-build-xetla-command arguments))
           ;; Make the `default-directory' unique. The trailing slash
           ;; may be necessary in some cases.
           (default-directory (xetla-uniquify-file-name default-directory))
           (process (start-process
                     xetla-tla-executable output-buf
                     "sh" "-c"
                     (format "%s 2> %s"
                             command error-file)))
           (process-event
            (list process
                  (xetla-log-event output-buf
                                  error-buf
                                  command
                                  default-directory "started"))))
      (with-current-buffer (or related-buffer (current-buffer))
        (message "running process `%s' in `%s'" command default-directory)
        (add-to-list 'xetla-process-running process-event)
        (set-process-filter process 'xetla-process-filter)
        (set-process-sentinel
         process
         `(lambda (process event)
            (let ((default-directory ,default-directory))
              (xetla-log-event ,output-buf ,error-buf ,command
                              ,default-directory
                              (xetla-strip-final-newline event))
              (setq xetla-process-running
                    (delq ',process-event xetla-process-running))
              (when (file-exists-p ,error-file)
                (with-current-buffer ,error-buf
                  (insert-file-contents ,error-file))
                (delete-file ,error-file))
              (let ((state (process-status process))
                    (status (process-exit-status process)))
                (unwind-protect
                    (cond ((and (eq state 'exit) (= status 0))
                           (funcall (or (quote ,finished)
                                        'xetla-default-finish-function)
                                    ,output-buf ,error-buf
                                    status (quote ,arguments)))
                          ((eq state 'signal)
                           (funcall (or (quote ,killed)
                                        'xetla-default-killed-function)
                                    ,output-buf ,error-buf status
                                    (quote ,arguments)))
                          ((eq state 'exit) ;; status != 0
                           (funcall (or (quote ,error)
                                        'xetla-default-error-function)
                                    ,output-buf ,error-buf status
                                    (quote ,arguments)))))
                ;; Schedule any buffers we created for killing
                (unless ,output-buffer (xetla-kill-process-buffer ,output-buf))
                (unless ,error-buffer (xetla-kill-process-buffer ,error-buf))))))
        process))))

(defun xetla-run-tla-sync (arguments &rest keys)
  "Run tla synchronously.
See `xetla-run-tla-async' for details on possible ARGUMENTS and KEYS."
  (xetla-with-keywords
      (:finished :killed :error :output-buffer :error-buffer :related-buffer)
    keys
    (let ((output-buf (or (and output-buffer (get-buffer-create output-buffer))
                          (xetla-new-process-buffer t)))
          (error-buf  (or (and error-buffer (get-buffer-create error-buffer))
                          (xetla-new-error-buffer t)))
          (command (xetla-build-xetla-command arguments))
          (error-file (xetla-make-temp-name "arch-errors"))
          ;; Make the `default-directory' unique. The trailing slash
          ;; may be necessary in some cases.
          (default-directory (xetla-uniquify-file-name default-directory)))
      (with-current-buffer (or related-buffer (current-buffer))
        (xetla-log-event output-buf error-buf command default-directory "started")
        (let ((status (call-process "sh" nil output-buf nil "-c"
                                    (format "%s 2> %s"
                                            command
                                            error-file))))
          (when (file-exists-p error-file)
            (with-current-buffer error-buf
              (insert-file-contents error-file))
            (delete-file error-file))
          (unwind-protect
              (cond ((stringp status)
                     (when (string= status "Terminated")
                       (funcall (or killed 'xetla-default-killed-function)
                                output-buf error-buf status arguments)))
                    ((numberp status)
                     (if (zerop status)
                         (funcall (or finished 'xetla-default-finish-function)
                                  output-buf error-buf status arguments)
                       (funcall (or error 'xetla-default-error-function)
                                output-buf error-buf status arguments)))
                    (t (message "Unknown status - %s" status)))
            ;; Schedule any buffers we created for killing
            (unless output-buffer (xetla-kill-process-buffer output-buf))
            (unless error-buffer (xetla-kill-process-buffer error-buf))))))))

(defun xetla-kill-process-maybe (buffer)
  "Prompts and possibly kill process whose related buffer is BUFFER."
  (let ((process-list nil))
    (dolist (process-buffer xetla-process-running)
      (when (eq (xetla-event-related-buffer (cadr process-buffer))
                buffer)
        (add-to-list 'process-list (car process-buffer))))
    (let ((l (length process-list)))
      (when (and process-list
                 (y-or-n-p (format "%s process%s running in buffer %s.  Kill %s? "
                                   l (if (> l 1) "es" "")
                                   (buffer-name buffer)
                                   (if (> l 1) "Them" "it"))))
        (dolist (process process-list)
          (setq xetla-default-killed-function-noerror
                (1+ xetla-default-killed-function-noerror))
          (if (eq (process-status process) 'run)
              (kill-process process)))))))

;;;###autoload
(add-to-list 'minor-mode-alist
             '(xetla-process-running
               (:eval (if (equal (length xetla-process-running) 1)
                          " tla running"
                        (concat " tla running("
                                (int-to-string (length xetla-process-running))
                                ")")))))

(eval-when-compile
  (autoload 'xetla-flash-line "xetla"))

(defun xetla-open-internal-log-buffer ()
  "Switch to the XEtla's internal log buffer.
This buffer contains a list of all the tla commands previously executed.
The buffer uses the mode `xetla-log-buffer-mode'"
  (interactive)
  (let ((buffer-name (buffer-name)))
    (xetla-switch-to-buffer xetla-log-buffer)
    (goto-char (point-max))
    (when (re-search-backward (concat " Buffer: "
                                      (regexp-quote buffer-name)
                                      "$")
                              nil t)
      (xetla-flash-line))))

(defun xetla-clear-log-buffer ()
  "Kill the log buffer."
  (when (bufferp (get-buffer xetla-log-buffer))
    (kill-buffer xetla-log-buffer)))

(defun xetla-buffer-content (buffer)
  "Return the content of BUFFER as a string.
Strips the final newline if there is one."
  (with-current-buffer buffer
    (buffer-substring-no-properties
     (point-min)
     (progn (goto-char (point-max))
            (if (eq (char-before) ?\n)
                (- (point) 1)
              (point))))))

(defun xetla-get-process-output ()
  "Return the content of the last process buffer.
Strips the final newline if there is one."
  (xetla-buffer-content xetla-last-process-buffer))

(defun xetla-get-error-output ()
  "Return the content of the last error buffer.
Strips the final newline if there is one."
  (xetla-buffer-content xetla-last-error-buffer))

(defvar xetla-switched-buffer nil)
(defvar xetla-switched-from-buffer nil)

(defun xetla-switch-to-buffer (buffer)
  "Switch to BUFFER using the user's preferred method.
See `xetla-switch-to-buffer-mode' for possible settings."
  (setq xetla-switched-from-buffer (current-buffer))
  (cond ((eq xetla-switch-to-buffer-mode 'pop-to-buffer)
         (pop-to-buffer buffer))
        ((eq xetla-switch-to-buffer-mode 'single-window)
         (switch-to-buffer buffer))
        ((eq xetla-switch-to-buffer-mode 'show-in-other-window)
         (pop-to-buffer buffer)
         (setq xetla-switched-buffer (current-buffer))
         (pop-to-buffer xetla-switched-from-buffer))
        ;; TODO : dedicated frame.
        (t
         (error "Switch mode %s not implemented" xetla-switch-to-buffer-mode))))

(defun xetla-post-switch-to-buffer ()
  "Executed when showing a changeset.

If `xetla-switched-buffer' is non-nil, show this buffer, but keep
cursor position in previous buffer."
  (when xetla-switched-buffer
    (pop-to-buffer xetla-switched-buffer)
    (setq xetla-switched-buffer nil)
    (goto-char (point-min))
    (pop-to-buffer xetla-switched-from-buffer)))


(defun xetla-show-process-buffer ()
  "Show the process buffer of the last started xetla command."
  (interactive)
  (xetla-switch-to-buffer xetla-last-process-buffer)
  (unless (member xetla-last-process-buffer
                  (mapcar (lambda (p)
                            (process-buffer (car p)))
                          xetla-process-running))
    (xetla-process-buffer-mode)))

(defun xetla-show-last-process-buffer (&optional type mode path)
  "Switch to the last used process buffer in a new buffer of TYPE.
If MODE is specified, it is a function that will be run in the
new buffer.  Otherwise, the buffer will remain in fundamental mode, in
read-only.

If PATH is specified, it will be passed to `xetla-get-buffer-create'."
  (when (buffer-live-p xetla-last-process-buffer)
    (let ((content (with-current-buffer xetla-last-process-buffer
                     (buffer-string))))
      (xetla-switch-to-buffer (xetla-get-buffer-create
                             (or type 'generic) path))
      (let ((inhibit-read-only t))
        (erase-buffer)
        (insert content)))
    (if mode
        (funcall mode)
      (xetla-process-buffer-mode))))

(defun xetla-show-error-buffer (buffer &optional type mode)
  "Pops up the error buffer.
Works like `xetla-show-last-process-buffer', but displays BUFFER, of type
'errors if TYPE is not specified.
If MODE is specified, the buffer will use that mode."
  (when (buffer-live-p buffer)
    (let ((content (with-current-buffer buffer
                     (buffer-string))))
      (xetla-switch-to-buffer (xetla-get-buffer-create
                             (or type 'errors)))
      (let ((inhibit-read-only t))
        (erase-buffer)
        (insert content)))
    (if mode
        (funcall mode)
      (xetla-process-buffer-mode))))

;; --------------------------------------
;; Arch name manipulators
;; ======================
;;
;; Normally in XEtla, a name, a revision specifier is represented as a
;; list like:
;;
;;    ("archive" "category" "branch" "version" "revision")
;;
;; Nil is permitted as the element. However the list length must be 5
;; like:
;;
;;    (nil "category" "branch" nil nil)
;;
;; In other hand, in tla command, the name must be represented as a
;; string like:
;;
;;    "archive/category-branch-version-revision"
;;
;; So we have to convert a name in different representation in many
;; cases.
;;
;; * xetla-name-split-* is for converting from a string representation
;;   to a list representation. There are semi-qualified version and
;;   fully-qualified version.
;;
;;   - semi-qualified: "category-branch-version-revision".
;;     `xetla-name-split-semi-qualified' expects a name string without
;;     archive component. The archive field of returned list is filled
;;     with nil.
;;
;;   - fully-qualified: "archive/category-branch-version-revision".
;;     `xetla-name-split' expects a name string including archive.
;;
;; * xetla-name-construct-* is for converting from a list
;;   representation to a string representation. The functions accept
;;   arguments two ways.
;;
;;   - normal passing: (xetla-name-construct "archive" "category"...)
;;   - packed passing: (xetla-name-construct '("archive" "category"...))
;;
;;   There are semi-qualified version and fully-qualified version.
;;   - semi-qualified: `xetla-name-construct-semi-qualified' connects
;;     arguments with "-".
;;   - fully-qualified: `xetla-name-construct" connects the first argument
;;     and the rest with "/". About the rest,
;;     `xetla-name-construct-semi-qualified' is applied.
;;
;; * xetla-name-{archive|category|branch|version|revision} is for
;;   extracting a component from a name. The both representations are
;;   acceptable.
;;
;; * xetla-name-mask is for replace a component in the name list with nil.
;;
;; --------------------------------------

;;
;; String representation -> List representation
;;
(defun xetla-name-split-semi-qualified (name &optional archive)
  "Split \"--\" connected string NAME into 5 elements list.
The first element is always nil if ARCHIVE is not given.
If ARCHIVE is given, use it as the first.
Even if the elements in name are less than 5, the list is filled by nil
to make the length 5.

  ELISP> (xetla-name-split-semi-qualified \"branch--category--version--revision\"
                                        \"archive\")
  (\"archive\" \"branch\" \"category\" \"version\" \"revision\")

  ELISP> (xetla-name-split-semi-qualified
            \"branch--category--version--revision\")
  (nil \"branch\" \"category\" \"version\" \"revision\")

  ELISP> (xetla-name-split-semi-qualified \"branch--category--version\")
  (nil \"branch\" \"category\" \"version\" nil)

  ELISP> (xetla-name-split-semi-qualified
            \"branch--category--version\" \"archive\")
  (\"archive\" \"branch\" \"category\" \"version\" nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category\" \"archive\")
  (\"archive\" \"branch\" \"category\" nil nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category\"nil)
  (nil \"branch\" \"category\" nil nil)

  ELISP> (xetla-name-split-semi-qualified \"branch--category--\" nil)
  (nil \"branch\" \"category\" \"\" nil)"
  (let ((list (xetla-name-split-semi-qualified-internal name)))
    (while (> 4 (length list))
      (setq list (cons nil list)))
    (let ((result (cons archive (nreverse list))))
      (when (xetla-is-version-string (caddr result))
        (setq result (list (car result)
                           (cadr result)
                           ""
                           (caddr result)
                           (cadddr result))))
      result)))

(defun xetla-is-version-string (string)
  "Non-nil if STRING is a candidate for a version name.
That is, if it contains only digits and dots.
The regexp here is less strict than the one of xetla, but must verify
\(xetla-is-version-string string) => string can't be a branch name."
  (and string (string-match "^[0-9\.]+$" string)))

(defun xetla-name-split-semi-qualified-internal (name)
  "Helper function for `xetla-name-split-semi-qualified'.
Splits a semi-qualified NAME."
  (if (string-match "^\\(.+\\)--\\(\\([^-]\\|-[^-]\\)*\\)" name)
      (cons (match-string 2 name)
            (xetla-name-split-semi-qualified-internal
             (match-string 1 name)))
    (cons name nil)))

(defun xetla-name-split (name)
  "Parse a fully qualified revision NAME, but possibly incomplete.
email@address.com--arch/cat--branch--ver ->
  (\"email@address.com--arch\" \"cat\" \"branch\" \"ver\" nil)
email@address.com--arch/cat ->
  (\"email@address.com--arch\" \"cat\" nil nil nil)
email@address.com--arch ->
  (\"email@address.com-arch\" nil nil nil nil)"
  (if (string-match "\\(.*\\)/\\(.*\\)" name)
      (xetla-name-split-semi-qualified (match-string 2 name) (match-string 1 name))
    (if (string= name "")
        (list nil nil nil nil nil)
      (list name nil nil nil nil))))


;;
;; List representation -> string
;;
(defun xetla-name-construct-semi-qualified (&rest comp)
  "Concatenate COMP with \"-\".
This function can accept strings or a list which contains strings.

    ELISP> (xetla-name-construct-semi-qualified \"a\" \"b\" \"c\")
    \"a--b--c\"
    ELISP> (xetla-name-construct-semi-qualified (list \"a\" \"b\" \"c\"))
    \"a--b--c\""
  (if (consp (car comp)) (setq comp (car comp)))
  (if (string= (cadr comp) "")
      ;; Unnamed branch.
      (concat (car comp) "--"
              (mapconcat 'identity (remove nil (cddr comp)) "--"))
    (mapconcat 'identity (remove nil comp) "--")))

(defun xetla-name-construct (archive &optional
                                    category
                                    branch
                                    version
                                    revision)
  "Create the revision name ARCHIVE/CATEGORY-BRANCH-VERSION-REVISION.
The arguments may be nil. If ARCHIVE is a revision name list like
 (archive category branch version revision), the list element is mapped
to arguments before creating the fully qualified revision name.

If the branch name is the empty string and the version is defined,
then, we have an unnamed branch. The full name is
archive/category-version."
  (when (consp archive)
    (setq category (xetla-name-category archive)
          branch   (xetla-name-branch archive)
          version  (xetla-name-version archive)
          revision (xetla-name-revision archive)
          ;; archive must be last
          archive  (xetla-name-archive archive)))
  (let ((semi (xetla-name-construct-semi-qualified
               category branch version revision)))
    (concat
     (and archive (not (string= archive ""))
          (concat archive (when category "/")))
     semi)))

;;
;; Get a component from a list or string.
;;
(defun xetla-name-archive (target)
  "Get archive component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (car target))

(defun xetla-name-category (target)
  "Get category component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadr target))

(defun xetla-name-branch (target)
  "Get branch component from a TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (caddr target))

(defun xetla-name-version (target)
  "Get version component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadddr target))

(defun xetla-name-revision (target)
  "Get revision component from TARGET.
Both representation of TARGET, a string and a list is acceptable."
  (when (stringp target)
    (setq target (xetla-name-split target)))
  (cadddr (cdr target)))

;;
;; Utilities
;; Mask a specified component in the name.
;;
(defun xetla-name-mask (original do-construct-p
                                &optional
                                archive-mask
                                category-mask
                                branch-mask
                                version-mask
                                revision-mask)
  "Mask ORIGINAL, a xetla revision name by masks; and return the masked value.

If DO-CONSTRUCT-P is given, the result is converted to a string by
`xetla-name-construct'.

ARCHIVE-MASK, CATEGORY-MASK, BRANCH-MASK, VERSION-MASK and REVISION-MASK should
be either nil or t, and indicate whether that field should be masked.

If a mask value is nil, the associated element in ORIGINAL is set to nil.
Else If a mask value is a string, the associated element in ORIGINAL is set
to the string.
Else the associated element in ORIGINAL is not changed.

Examples:
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") nil t t t t nil)
 (\"a\" \"c\" \"b\" \"v\" nil)

 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") nil t t t nil nil)
 (\"a\" \"c\" \"b\" nil nil)

 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t t t t nil nil)
 \"a/c-b\"
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t nil nil nil nil t)
 \"r\"
 ELISP> (xetla-name-mask '(\"a\" \"c\" \"b\" \"v\" \"r\") t nil nil nil t t)
 \"v-r\"
 ELISP>"
  (when (consp original)
    (let ((masked (list
                   (if archive-mask
                       (if (stringp archive-mask)
                           archive-mask
                         (xetla-name-archive original)))
                   (if category-mask
                       (if (stringp category-mask)
                           category-mask
                         (xetla-name-category original)))
                   (if branch-mask
                       (if (stringp branch-mask)
                           branch-mask
                         (xetla-name-branch original)))
                   (if version-mask
                       (if (stringp version-mask)
                           version-mask
                         (xetla-name-version original)))
                   (if revision-mask
                       (if (stringp revision-mask)
                           revision-mask
                         (xetla-name-revision original))))))
      (if do-construct-p
          (xetla-name-construct masked)
        masked))))

(defun xetla-name-match (target mask)
"Compare the fully qualified revision list TARGET with a MASK.
Each parameter is a list.  The elements of the both lists are compared
via a regexp match.  When the mask part of a component is nil, this
comparision is skipped.
Here are some examples:
\(xetla-name-match
 '(\"xsteve@nit.at-public\" \"xetla\" \"main\" \"0.1\" \"patch-116\")
 '(nil \"xt.*\" \"main\" nil nil)) => t
\(xetla-name-match
 '(\"xsteve@nit.at-public\" \"xetla\" \"main\" \"0.1\" \"patch-116\")
 '(nil \"xt.*\" \"devel\" nil nil)) => nil"  ;"
  (let ((tl target)
        (ml mask)
        (t-part)
        (m-part)
        (matching t))
    (while tl
      (setq t-part (car tl))
      (setq m-part (car ml))
      (when m-part
        (setq matching (string-match m-part t-part)))
      (if matching
          (progn
            (setq tl (cdr tl))
            (setq ml (cdr ml)))
        (setq tl nil)))
    (if matching t nil)))


(defun xetla-name-match-from-list (target match-list)
  "Match TARGET against a list of possible matches.
Every entry of MATCH-LIST is a list that contains a
match element and a possible result.
The target is matched against the elements in the match-list.
If a match is found return the corresponding result,
otherwise return nil."
  (let ((ml match-list)
        (match)
        (data)
        (result))
    (while (and (not result) ml)
      (setq match (caar ml))
      (setq data (cadar ml))
      (message "match: %s, data: %s" match data)
      (setq result (when (xetla-name-match target match) data))
      (setq ml (cdr ml)))
    result))

;; TODO: Use xetla-archive-tree.
(defun xetla-version-head (archive category branch version)
  "Return the newest revision for ARCHIVE/CATEGORY-BRANCH-VERSION."
  (xetla-run-tla-sync (list "revisions"
                           (xetla-name-construct
                            archive
                            category
                            branch
                            version))
                     :finished (lambda (output error status arguments)
                                 (with-current-buffer output
                                   (goto-char (point-max))
                                   (re-search-backward "^.")
                                   (buffer-substring-no-properties
                                    (point) (point-at-eol))))))

;; --------------------------------------
;; Archive tree manipulators
;; --------------------------------------

(defvar xetla-archive-tree nil
  "Arch archive/category/branch/version/revision are stored in assoc list:

 ((\"xsteve@nit.at-public\" \"http://arch.xsteve.at/2004\")
 [...]
  (\"mbp@sourcefrog.net-2004\"
   \"http://sourcefrog.net/arch/mbp@sourcefrog.net-2004\"
   (\"xetla\")
   (\"tilly\")
 [...]
   (\"dupes\"
    (\"mainline\"
     (\"0.1\")))
 [...]
   (\"archzoom\"))
  (\"mark@dishevelled.net-2003-mst\"
   \"http://members.iinet.net.au/~mtriggs/arch/\")
  (\"lord@emf.net-2004\"
   \"http://regexps.srparish.net/{archives}/lord@emf.net-2004\")
 [...]
  (\"Matthieu.Moy@imag.fr-public\"
   \"http://www-verimag.imag.fr/webdav/moy/public\"
   (\"xetla\"
    (\"main\"
     (\"0.1\"
      (\"patch-228\"
       \"Merged from Robert (patch8-9), Milan (patch21-22), Stefan (patch5-8)\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-06-03 20:13:11 GMT\")
      (\"patch-227\"
       \"Fix default-directory in xetla-run-tla-sync, fix in xetla-changes-ediff\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-06-03 15:26:15 GMT\")
 [...]
      (\"patch-1\"
       \"typo\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\"
       \"2004-04-07 22:57:00 GMT\")
      (\"base-0\"
       \"tag of xsteve@nit.at-public/xetla-main-0.1-patch-5\"
       \"Matthieu Moy <Matthieu.Moy@imag.fr>\" \"2004-04-07 22:52:39 GMT\")))))
 [...]
   )

This list is initially empty, and is built/rebuilt on demand.")

;; Utilities
(defun xetla-archive-tree-setcdr (parent value &optional rest)
  "In PARENT, update VALUE.
REST are the items that are already present."
  (let* ((current (cdr parent))
         (list-details (assoc value current)))
    (if (or (null current) (null list-details))
        ;; rest is '("summary" "creator" "date") when value is "patch-N"
        (setcdr parent (cons (cons value rest) current))
      (if (and list-details rest)
          ;; Field already there. update details.
          (setcdr list-details rest)))))

(defun xetla-archive-tree-setcddr (parent value)
  "In PARENT, update VALUE."
  (let ((current (cddr parent)))
    (if (or (null current) (null (assoc value current)))
        (setcdr (cdr parent) (cons (cons value nil) current)))))

;; Archive
(defun xetla-archive-tree-add-archive (archive location &optional old)
  "Add ARCHIVE  at LOCATION to the archive tree.
If OLD is provided, it is an old archive tree from which some
information can be found (this is useful to keep the category/branch/version
info for existing archives)."
  (if (xetla-archive-tree-get-archive archive)
      (let* ((a (xetla-archive-tree-get-archive archive))
             (val (cdr a))
             (oldlocation (car val))
             (category (cdr val)))
        (setcdr a (cons (or location oldlocation) category)))
    (let ((oldinfo (xetla-archive-tree-get-archive archive old))
          (newinfo (list archive location)))
      (when oldinfo
        (setcdr (cdr newinfo) (cddr oldinfo))) ;; list of versions.
      (setq xetla-archive-tree (cons newinfo
                                    xetla-archive-tree)))))

(defun xetla-archive-tree-get-archive (archive &optional archive-tree)
  "Get the value of ARCHIVE from ARCHIVE-TREE.
If ARCHIVE-TREE is not given, `xetla-archive-tree' is used."
  (assoc archive (or archive-tree xetla-archive-tree)))

;; Category
(defun xetla-archive-tree-add-category (archive category)
  "Add a new category to ARCHIVE named CATEGORY."
  (xetla-archive-tree-add-archive archive nil)
  (xetla-archive-tree-setcddr
   (xetla-archive-tree-get-archive archive)
   category))

(defun xetla-archive-tree-get-category (archive category)
  "From ARCHIVE, get CATEGORY."
  (assoc category (cdr (cdr (xetla-archive-tree-get-archive archive)))))

;; Branch
(defun xetla-archive-tree-add-branch (archive category branch)
  "Add a new branch to ARCHIVE's CATEGORY named BRANCH."
  (xetla-archive-tree-add-category archive category)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-category archive category)
   branch))

(defun xetla-archive-tree-get-branch (archive category branch)
  "Get a branch from ARCHIVE's CATEGORY named BRANCH."
  (assoc branch (cdr (xetla-archive-tree-get-category
                      archive category))))

;; Version
(defun xetla-archive-tree-add-version (archive category branch version)
  "Add a new version to ARCHIVE CATEGORY BRANCH named VERSION."
  (xetla-archive-tree-add-branch archive category branch)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-branch archive category branch )
   version))

(defun xetla-archive-tree-get-version (archive category branch version)
  "Get a version from ARCHIVE CATEGORY BRANCH named VERSION."
  (assoc version (cdr (xetla-archive-tree-get-branch
                       archive category branch))))

;; Revision
(defun xetla-archive-tree-add-revision (archive category branch version revision
                                               &optional summary creator date)
  "Add a new revision to ARCHIVE CATEGORY BRANCH VERSION named REVISION."
  (xetla-archive-tree-add-version archive category branch version)
  (xetla-archive-tree-setcdr
   (xetla-archive-tree-get-version archive category branch version)
   revision (list summary creator date)))

(defun xetla-archive-tree-get-revision (archive category branch version revision)
  "Get a revision from ARCHIVE CATEGORY BRANCH VERSION named REVISION."
  (assoc revision (cdr (xetla-archive-tree-get-version
                        archive category branch version))))

;; Archive tree builders
(defun xetla-archive-tree-build (basename &optional use-cache ignore-error)
  "Generic version of xetla-archive-tree-build-*.
BASENAME is used as a base for this tree.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (stringp basename)
    (setq basename (xetla-name-split basename)))
  (let ((archive (xetla-name-archive basename))
        (category (xetla-name-category basename))
        (branch (xetla-name-branch basename))
        (version (xetla-name-version basename)))
  (cond
   (version
    (xetla-archive-tree-build-revisions archive
                                       category
                                       branch
                                       version
                                       use-cache
                                       ignore-error))
   (branch
    (xetla-archive-tree-build-versions archive
                                      category
                                      branch
                                      use-cache
                                      ignore-error))
   (category
    (xetla-archive-tree-build-branches archive
                                      category
                                      use-cache
                                      ignore-error))
   (archive
    (xetla-archive-tree-build-categories archive
                                        use-cache
                                        ignore-error))
   (t
    (xetla-archive-tree-build-archives use-cache
                                      ignore-error)))))

(defun xetla-archive-tree-build-archives (&optional use-cache ignore-error)
  "Builds the list of archives.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not xetla-archive-tree))
    (xetla-run-tla-sync '("archives")
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (let ((old-archive-tree xetla-archive-tree))
      (setq xetla-archive-tree nil)
      (save-excursion
        (let ((archive-name)
              (archive-location))
          (set-buffer xetla-last-process-buffer)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq archive-name (buffer-substring-no-properties
                                (point-at-bol)
                                (point-at-eol)))
            (beginning-of-line-text 2)
            (setq archive-location (buffer-substring-no-properties
                                    (point) (point-at-eol)))
            (forward-line 1)
            (xetla-archive-tree-add-archive archive-name
                                           archive-location
                                           old-archive-tree)))))))

(defun xetla-archive-tree-build-categories (archive &optional
                                                   use-cache
                                                   ignore-error)
  "Build the list of categories for ARCHIVE in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cddr (xetla-archive-tree-get-archive archive))))
    (let ((basename archive))
      (message "building categories for `%s'..." basename)
      (xetla-run-tla-sync (list "categories" "-A" basename)
                         :finished 'xetla-null-handler
                         :error
                         (if ignore-error
                             'xetla-null-handler
                           'xetla-default-error-function))
      (message "building categories for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (category)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq category (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-category archive category)
          )))))

(defun xetla-archive-tree-build-branches (archive category
                                                 &optional
                                                 use-cache
                                                 ignore-error)
  "Build the list of branches for ARCHIVE/CATEGORY in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-category archive category))))
    (let ((basename (xetla-name-construct archive category)))
      (message "building branches for `%s'..." basename)
      (xetla-run-tla-sync (list "branches" basename)
                         :finished 'xetla-null-handler
                         :error
                         (if ignore-error
                             'xetla-null-handler
                           'xetla-default-error-function))
      (message "building branches for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (branch)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq branch (buffer-substring-no-properties
                        (point-at-bol)
                        (point-at-eol)))
          (xetla-archive-tree-add-branch
           archive
           category
           (if (looking-at ".*-")
               (xetla-name-branch (xetla-name-split-semi-qualified
                                  branch))
             ;; unnamed branch
             ""))
          (forward-line 1))))))

(defun xetla-archive-tree-build-versions (archive category branch
                                                 &optional
                                                 use-cache
                                                 ignore-error)
  "Build the version list in ARCHIVE/CATEGORY-BRANCH in `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-branch archive category
                                                    branch))))
    (let ((basename (xetla-name-construct archive category branch)))
      (message "building versions for `%s'..." basename)
      (xetla-run-tla-sync (list "versions" basename)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
      (message "building versions for `%s'...done" basename)
      (sit-for 0)
      (message nil))
    (with-current-buffer xetla-last-process-buffer
      (let (version)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq version (buffer-substring-no-properties
                         (point-at-bol)
                         (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-version
           archive
           category
           branch
           (xetla-name-version (xetla-name-split-semi-qualified version))))))))

(defun xetla-archive-tree-build-revisions (archive category branch version
                                                  &optional
                                                  use-cache
                                                  ignore-error)

  "Build the revision list in ARCHIVE/CATEGORY-BRANCH-VERSION.
Updates `xetla-archive-tree'.
If USE-CACHE is non-nil, load details from the cache where possible.
If IGNORE-ERROR is non-nil, don't throw errors."
  (when (or (not use-cache)
            (not (cdr (xetla-archive-tree-get-version archive category branch
                                                     version))))
    (let ((details (or xetla-revisions-shows-summary
                       xetla-revisions-shows-date
                       xetla-revisions-shows-creator))
          (basename (xetla-name-construct
                     archive category branch version)))
      (message "building revisions for `%s'..." basename)
      (if details
          (progn
            (xetla-run-tla-sync (list "revisions"
                                     "--summary" "--date" "--creator"
                                     basename)
                               :finished 'xetla-null-handler
                               :error (if ignore-error
                                          'xetla-null-handler
                                        'xetla-default-error-function)))
        (progn
          (xetla-run-tla-sync (list "revisions" basename)
                             :finished 'xetla-null-handler
                             :error (if ignore-error
                                        'xetla-null-handler
                                      'xetla-default-error-function))))
      (message "building revisions for `%s'...done" basename)
      (sit-for 0)
      (message nil)
      (with-current-buffer xetla-last-process-buffer
        (let (revision date creator summary)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq revision (buffer-substring-no-properties
                            (point-at-bol)
                            (point-at-eol)))
            (forward-line 1)
            (when details
              (skip-chars-forward " ")
              (setq date (buffer-substring-no-properties (point)
                                                         (point-at-eol)))
              (forward-line 1)
              (skip-chars-forward " ")
              (setq creator (buffer-substring-no-properties (point)
                                                            (point-at-eol)))
              (forward-line 1)
              (skip-chars-forward " ")
              (setq summary (buffer-substring-no-properties
                             (point)
                             (progn (re-search-forward "^\\([^ \t]\\|$\\)")
                                    (previous-line 1)
                                    (end-of-line)
                                    (point))))
              (forward-line 1))
            (xetla-archive-tree-add-revision
             archive
             category
             branch
             version
             revision
             summary
             creator
             date)))))))


(defun xetla-revisions-tree-contains-details
  (archive category branch version)
  "Whether VERSION has already been listed full details.
Details include summary lines, dates, and creator in the archive tree."
  (let ((vtree (xetla-archive-tree-get-version archive category branch
                                              version)))
    (and (cdr vtree) ;; revision list is here
         (cadr (cadr vtree))))) ;; summary line also

;; --------------------------------------
;; Revlib tree manipulators
;; --------------------------------------
(defvar xetla-revlib-tree nil)
(defun xetla-revlib-tree-get-archive (archive &optional archive-tree)
  "Get ARCHIVE from ARCHIVE-TREE.
If ARCHIVE-TREE is not given, `xetla-revlib-tree' is used instead."
  (assoc archive (or archive-tree xetla-revlib-tree)))

(defun xetla-revlib-tree-build-archives (&optional use-cache ignore-error)
  "Build the list of archives in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for archives are updated."
  (when (or (not use-cache)
            (not xetla-revlib-tree))
    (xetla-run-tla-sync '("library-archives")
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (let ((old-revlib-tree xetla-revlib-tree) )
      (setq xetla-revlib-tree nil)
      (save-excursion
        (let ((archive-name)
              (tmp xetla-archive-tree)
              (xetla-archive-tree xetla-revlib-tree)
              result)
          (set-buffer xetla-last-process-buffer)
          (goto-char (point-min))
          (while (> (point-at-eol) (point-at-bol))
            (setq result t)
            (setq archive-name (buffer-substring-no-properties
                                (point-at-bol)
                                (point-at-eol)))
            (forward-line 1)
            (xetla-archive-tree-add-archive archive-name
                                           nil
                                           old-revlib-tree))
          (setq xetla-revlib-tree xetla-archive-tree
                xetla-archive-tree tmp)
          result)))))

(defun xetla-revlib-tree-get-category (archive category)
  "Get a category from ARCHIVE named CATEGORY."
  (assoc category (cdr (cdr (xetla-revlib-tree-get-archive archive)))))

(defun xetla-revlib-tree-build-categories (archive &optional
                                                  use-cache
                                                  ignore-error)
  "Builds the list of categories for an ARCHIVE in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for categories are updated."
  (when (or (not use-cache)
            (not (cddr (xetla-revlib-tree-get-archive archive))))
    (xetla-run-tla-sync (list "library-categories" "-A" archive)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (category
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq category (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-category archive category))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-branch (archive category branch)
  "From ARCHIVE/CATEGORY, get BRANCH."
  (assoc branch (cdr (xetla-revlib-tree-get-category
                      archive category))))

(defun xetla-revlib-tree-build-branches (archive category
                                                &optional
                                                use-cache
                                                ignore-error)
  "Build the list of branches for ARCHIVE/CATEGORY in `xetla-revlib-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for branches are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-category archive category))))
    (xetla-run-tla-sync (list "library-branches" "-A" archive category)
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (branch
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq branch (buffer-substring-no-properties
                        (point-at-bol)
                        (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-branch
           archive
           category
           (xetla-name-branch (xetla-name-split-semi-qualified branch))))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-version (archive category branch version)
  "Get ARCHIVE/CATEGORY-BRANCH-VERSION from the revlib tree."
  (assoc version (cdr (xetla-revlib-tree-get-branch
                       archive category branch))))

(defun xetla-revlib-tree-build-versions (archive category branch
                                                &optional
                                                use-cache
                                                ignore-error)
  "Build the versions list in ARCHIVE/CATEGORY/BRANCH in `xetla-archive-tree'.
If USE-CACHE is non-nil, load from the cache where possible.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for versions are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-branch archive category
                                                   branch))))
    (xetla-run-tla-sync (list "library-versions"
                             (xetla-name-construct
                              archive category branch))
                       :finished 'xetla-null-handler
                       :error
                       (if ignore-error
                           'xetla-null-handler
                         'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (version
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)
        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq version (buffer-substring-no-properties
                         (point-at-bol)
                         (point-at-eol)))
          (forward-line 1)
          (xetla-archive-tree-add-version
           archive
           category
           branch
           (xetla-name-version (xetla-name-split-semi-qualified version))))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result))))

(defun xetla-revlib-tree-get-revision (archive category branch version revision)
  "Get ARCHIVE/CATEGORY-BRANCH-VERSION-REVISION from the revlib tree."
  (assoc revision (cdr (xetla-revlib-tree-get-version
                        archive category branch version))))

(defun xetla-revlib-tree-build-revisions (archive category branch version
                                                 &optional
                                                 use-cache
                                                 ignore-error)

  "Build the revision list of ARCHIVE/CATEGORY-BRANCH-VERSION.
Updates `xetla-revlib-tree'.
If IGNORE-ERROR is non-nil, error is not reported.
Return non-nil if the tree entry for revisions are updated."
  (when (or (not use-cache)
            (not (cdr (xetla-revlib-tree-get-version archive category branch
                                                    version))))
    (xetla-run-tla-sync (list "library-revisions"
                             "--summary" "--date" "--creator"
                             (xetla-name-construct
                              archive category branch version))
                       :finished 'xetla-null-handler
                       :error (if ignore-error
                                  'xetla-null-handler
                                'xetla-default-error-function))
    (with-current-buffer xetla-last-process-buffer
      (let (revision
            date
            creator
            summary
            (tmp xetla-archive-tree)
            (xetla-archive-tree xetla-revlib-tree)
            result)

        (goto-char (point-min))
        (while (> (point-at-eol) (point-at-bol))
          (setq result t)
          (setq revision (buffer-substring-no-properties
                          (point-at-bol)
                          (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq date (buffer-substring-no-properties (point)
                                                     (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq creator (buffer-substring-no-properties (point)
                                                        (point-at-eol)))
          (forward-line 1)
          (skip-chars-forward " ")
          (setq summary (buffer-substring-no-properties
                         (point)
                         (progn (re-search-forward "^\\([^ \t]\\|$\\)")
                                (previous-line 1)
                                (end-of-line)
                                (point))))
          (forward-line 1)
          (xetla-archive-tree-add-revision
           archive
           category
           branch
           version
           revision
           summary
           creator
           date))
        (setq xetla-revlib-tree xetla-archive-tree
              xetla-archive-tree tmp)
        result
        ))))

;; --------------------------------------
;; Name reading engine
;; --------------------------------------
;;Currently only able to read a full revision starting from nothing.
(defun xetla-name-read-refresh-cache ()
  "Function to be called from the minibuffer while reading a name."
  (interactive)
  (xetla-archive-tree-build
   (xetla-name-construct
    (butlast (delete nil (xetla-name-split (buffer-substring))))))
  (setq xetla-archive-tree nil))

(defvar xetla-name-read-arguments "This value should not be refereed."
  "Used to suppress warnings from the byte code compiler.
This variable is a just placeholder introduced to suppress the
warnings from byte code compiler.  Variable `xetla-name-read-arguments'
should be bound in `let'.  Variable `xetla-name-read-arguments' is used
for passing information from `xetla-name-read' to functions called internally
from `xetla-name-read'.  Use function `xetla-name-read-arguments' to get the
information")

(defun xetla-name-read-arguments (key)
  "Get `xetla-name-read' context information associated to KEY.
`xetla-name-read' calls some functions to read a xetla name.
In the functions, the arguments passed to `xetla-name-read'(context information)
are needed to know.  However, `xetla-name-read' cannot pass the context
information directly to the functions because the functions are something to do
with Emacs's completion mechanism; and the mechanism specifies the number
of arguments of the functions.  So the context information is passed via
a local variable, `xetla-name-read-arguments', defined in let.

Symbol `archive', `category', `branch', `version', or `revision' are
acceptable as KEY."
  (cdr (assoc key xetla-name-read-arguments)))


(defun xetla-name-read-complete (string predicate what)
  "Completion function for name reading.

Displays STRING and prompts for something satisfying PREDICATE.

This function uses the free variables archive, category, branch,
version, and revision.  If one of these variables is non-nil, it means
the corresponding value must be read from keyboard.

REMINDER: this function may be called several times, with different
values for WHAT:

 - nil : The function must return the longest prefix
 - t : The function must return the list of completions
 - 'lambda : The function must return t if the completion correspond
   to an exact match, nil otherwise.  (so that Emacs can distinguish
   between \"sole completion\" and \"complete, but not unique\"."
  (if (and (eq what 'lambda)
           (string-match "/\\(.*--\\)?$" string))
      ;; The caller just want to know whether this is a full
      ;; completion. This can not be the case with such suffix.
      nil
    (let* ((empty-branch nil)
           (use-cache (not current-prefix-arg))
           (splited (xetla-name-split string))
           (archive-loc  (xetla-name-archive  splited))
           (category-loc (xetla-name-category splited))
           (branch-loc   (xetla-name-branch   splited))
           (version-loc  (xetla-name-version  splited))
           (revision-loc (xetla-name-revision splited))
           (suffix (cond
                    ((and (xetla-name-read-arguments 'category)
                          (not category-loc) "/"))
                    ((and (xetla-name-read-arguments 'branch)
                          (not branch-loc)   "--"))
                    ((and (xetla-name-read-arguments 'version)
                          (not version-loc)  "--"))
                    ((and (xetla-name-read-arguments 'revision)
                          (not revision-loc) "--"))
                    (t nil)))
           (maybep (cond
                    ((eq 'maybe (xetla-name-read-arguments 'category))
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'branch))
                          archive-loc category-loc)
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'version))
                          archive-loc category-loc branch-loc)
                     t)
                    ((and (eq 'maybe (xetla-name-read-arguments 'revision))
                          archive-loc category-loc branch-loc version-loc)
                     t)
                    (t nil)))
           (completions
            (cond
             ;; If the user started to write a revision ...
             (revision-loc
              ;; ... and if the user is supposed to be prompted a
              ;; revision
              (when (xetla-name-read-arguments 'revision)
                (let ((xetla-revisions-shows-summary nil)
                      (xetla-revisions-shows-date nil)
                      (xetla-revisions-shows-creator nil))
                  (xetla-archive-tree-build-revisions
                   archive-loc category-loc branch-loc version-loc use-cache t))
                (cdr (xetla-archive-tree-get-version
                      archive-loc category-loc branch-loc version-loc))))
             (version-loc
              (when (xetla-name-read-arguments 'version)
                (xetla-archive-tree-build-versions
                 archive-loc category-loc branch-loc use-cache t)
                (cdr (xetla-archive-tree-get-branch
                      archive-loc category-loc branch-loc))))
             ;; If the user started a branch ...
             (branch-loc
              ;; And a branch is needed
              (when (xetla-name-read-arguments 'branch)
                (xetla-archive-tree-build-branches
                 archive-loc category-loc use-cache t)
                (let ((result (cdr (xetla-archive-tree-get-category
                                    archive-loc category-loc))))
                  (when (and (string= branch-loc "")
                             (xetla-name-read-arguments 'version)
                             (let ((empty-br-exists nil))
                               (dolist (branch
                                        (cdr (xetla-archive-tree-get-category
                                              archive-loc category-loc)))
                                 (when (string= (car branch) "")
                                   (setq empty-br-exists t)))
                               empty-br-exists))
                    (xetla-archive-tree-build-versions
                     archive-loc category-loc "")
                    (setq empty-branch (xetla-archive-tree-get-branch
                                        archive-loc category-loc ""))
                    (when empty-branch
                      ;; Remove the "" branch to avoid the --
                      ;; completion.
                      (let ((tmp result))
                        (setq result nil)
                        (while tmp
                          (when (not (string= (caar tmp) ""))
                            (setq result (cons (car tmp) result)))
                          (setq tmp (cdr tmp))))))
                  result)))
             (category-loc
              (when (xetla-name-read-arguments 'category)
                (xetla-archive-tree-build-categories archive-loc use-cache t)
                (cddr (xetla-archive-tree-get-archive archive-loc))))
             (t
              (when (xetla-name-read-arguments 'archive)
                (xetla-archive-tree-build-archives use-cache t)
                xetla-archive-tree)))))
      (let* ((base (mapcar (lambda (x)
                             (xetla-name-construct
                              (delete
                               nil
                               (list
                                (when category-loc archive-loc)
                                (when branch-loc category-loc)
                                (when version-loc branch-loc)
                                (when revision-loc version-loc)
                                (car x)))))
                           completions))
             (sans-suffix
              (and maybep suffix))
             (empty-branch-versions
              (and empty-branch
                   (mapcar (lambda (x)
                             (xetla-name-construct
                              archive-loc category-loc "" (car x)))
                           (cdr empty-branch))))
             (completions (funcall 'all-completions
                                   string
                                   (nconc (mapcar
                                           (lambda (x)
                                             (list (concat x suffix)))
                                           base)
                                          (when sans-suffix
                                            (mapcar
                                             (lambda (x) (list x))
                                             base))
                                          (when empty-branch
                                            (mapcar
                                             (lambda (x) (list x))
                                             empty-branch-versions)))
                                   predicate)))
        (let ((result
               (cond ((eq what t)
                      ;; We just want the list of completions
                      completions)
                     ((eq (length completions) 1)
                      ;; There's only one completion
                      (if (eq what 'lambda)
                          (string= (car completions) string)
                        (cond ((string= (car completions) string) t)
                              (t (car completions)))))
                     ;; there are several possible completions
                     (t (if (eq what 'lambda)
                            ;; complete, but not unique ?
                            (member string completions)
                          (try-completion string (mapcar 'list
                                                         completions)))))))
;;          (xetla-trace "string=%s predicate=%S what=%s ==> result=%S\ncompletions=%S"
;;                      string predicate what result completions)
          result)))))

;; Test cases
;; (xetla-name-read "enter category: " "Matthieu.Moy@imag.fr--public" 'prompt)
;; (xetla-name-read "branch: " "lord@emf.net--2004" 'prompt 'prompt)
;; (xetla-name-read "revision: " 'prompt 'prompt 'prompt 'prompt 'prompt)
;; (xetla-name-read "revision or version: " 'prompt 'prompt 'prompt 'prompt 'maybe)
;; (xetla-name-read "revision or version: " "jet@gyve.org--xetla" "xetla" "jet" 'prompt 'maybe)
;;
(defvar xetla-name-read-history nil)     ; TODO: multiple history list?
(defvar xetla-name-read-debug nil
  "If non-nil, `condition-case' in `xetla-name-read' is made disabled.")
(defun xetla-name-read (&optional prompt archive category
                                 branch version revision)
  "Read a name.
To get help on the user interface of `xetla-name-read', please type
M-x xetla-name-read-help RET.

Function reading an archive location from keyboard.
Read name is expressed in a list built by `xetla-name-split'.

First argument PROMPT is the prompt the user will get. Next arguments
ARCHIVE CATEGORY BRANCH VERSION and REVISION are either the default
value, or a request for a value. They can take four values:

 - A string means the default value, and will be used as an initial
   input.

 - The symbol 'prompt means the value will be prompted from the user.
   The user will HAVE to give this value.

 - The symbol 'maybe means the value will be prompted, but is optional
   for the user.

 - nil means the value won't be prompted.

They should appear in the same order as above.

Example:
- Read a category in archive \"Matthieu.Moy@imag.fr--public\":
 (xetla-name-read \"enter category: \" \"Matthieu.Moy@imag.fr--public\" 'prompt)
- Read a revision, anywhere:
 (xetla-name-read \"revision: \" 'prompt 'prompt 'prompt 'prompt 'prompt)
- Read either a revision or a version:
 (xetla-name-read \"revision: \" 'prompt 'prompt 'prompt 'prompt 'maybe)

While prompting, a menu \"Xetla\" is added to the menubar. The
following commands are available:

\\{xetla-name-read-minibuf-map}"
  (let ((xetla-name-read-arguments `((archive  . ,archive)
                                    (category . ,category)
                                    (branch   . ,branch)
                                    (version  . ,version)
                                    (revision . ,revision))))
    (if xetla-name-read-debug
        (xetla-name-read-internal prompt archive category branch version revision)
      (condition-case reason
          (xetla-name-read-internal prompt archive category branch version revision)
        ((quit error)
         (run-hooks 'xetla-name-read-error-hook)
         (signal (car reason) (cdr reason)))))))

(defun xetla-name-read-internal (prompt archive category branch version revision)
  "See `xetla-name-read'."
  (run-hooks 'xetla-name-read-init-hook)
  (let* ((minibuffer-local-completion-map xetla-name-read-minibuf-map)
         (result (xetla-name-construct
                  (delete
                   'maybe
                   (delete 'prompt (list archive category
                                         branch version)))))
         (first-try t)
         not-finished too-long last-empty)
    ;; Without in some case 'maybe is ignored by xetla-prompt-not-finished
    ;; and never the control flow enters the while loop.
    ;; We need C language's do-while loop.
    (while (or first-try
               not-finished
               too-long
               last-empty)
      (unless first-try
        (unless (eq this-command 'choose-completion)
          (ding)
          (message (cond (not-finished "%s%s [incomplete input: %s]")
                         (too-long "%s%s [too long input for: %s]")
                         (last-empty (concat "%s%s [empty " last-empty
                                             " name]"))
                         (t (error
                             (concat "case not managed."
                                     " Please submit a bug report"))))
                   prompt result
                   (xetla-name-read-required-input archive
                                                  category
                                                  branch
                                                  version
                                                  revision))
          (sit-for 2)
          (message nil)))

      (setq result (completing-read
                    (or prompt "Location: ")
                    'xetla-name-read-complete
                    nil nil result
                    'xetla-name-read-history)
            first-try nil)
      (setq not-finished (xetla-prompt-not-finished
                          result archive category branch
                          version revision))
      (setq too-long (xetla-prompt-too-long
                      result archive category branch
                      version revision))
      (setq last-empty (xetla-prompt-last-empty result)))

    (when result
      (setq result (xetla-name-split result)))
    (run-hook-with-args 'xetla-name-read-final-hook result)
    result))

(defun xetla-prompt-not-finished (result archive category branch
                                        version revision)
  "Check whether user input is complete.
True if RESULT (a string) is not sufficient when the user is
prompted for ARCHIVE CATEGORY BRANCH VERSION REVISION."
  (let ((res-split (xetla-name-split result)))
    (or (and (eq archive 'prompt) ;; archive required
             (not (xetla-name-archive res-split))) ;; but not provided
        (and (eq category 'prompt)
             (not (xetla-name-category res-split)))
        (and (eq branch 'prompt)
             (not (xetla-name-branch res-split)))
        (and (eq version 'prompt)
             (not (xetla-name-version res-split)))
        (and (eq revision 'prompt)
             (not (xetla-name-revision res-split))))))

(defun xetla-prompt-too-long (result archive category branch
                                    version revision)
  "Check whether the user has entered too many elements.
True if RESULT (a string) contains too many elements when the user
is prompted for ARCHIVE CATEGORY BRANCH VERSION REVISION.

For example, will return true if the user entered
foo@bar-2004/xetla-main while prompted only for a category."
  (let ((res-split (xetla-name-split result)))
    (or (and (not revision) ;; revision not needed
             (xetla-name-revision res-split)) ;; but provided
        (and (not version)
             (xetla-name-version res-split))
        (and (not branch)
             (xetla-name-branch res-split))
        (and (not category)
             (xetla-name-category res-split))
        (and (not archive)
             (xetla-name-archive res-split)))))

(defun xetla-prompt-last-empty (result)
  "Check whether the last field is empty.
Non-nil if RESULT (a string) is terminated by \"--\" or \"/\". This
means the user entered a delimiter but not the element after.

When non-nil, the returned value is a string giving the name of the
item that is currently empty. (eg: archive, category, ...)"
  (let ((res-split (xetla-name-split result)))
    (cond ((equal (xetla-name-archive  res-split) "") "archive" )
          ((equal (xetla-name-category res-split) "") "category")
          ((and (equal (xetla-name-branch res-split) "")
                (not (xetla-name-version res-split))) "branch"  )
          ((equal (xetla-name-version  res-split) "") "version" )
          ((equal (xetla-name-revision res-split) "") "revision")
          (t nil))))


(defun xetla-name-read-required-input (archive
                                      category
                                      branch
                                      version
                                      revision)
  "Return string which represents the elements to be readin `xetla-name-read'.
If ARCHIVE, CATEGORY, BRANCH, VERSION or REVISION are equal to 'maybe, the
corresponding element will be optionally read.
If any of these are non-nil (but not 'maybe), the corresponding element will be
required.
If any of these are nil, the correpsonding element is not required."
  (concat
   (cond ((eq archive 'maybe) "[A]")
         (archive "A")
         (t ""))
   (cond ((eq category 'maybe) "[/C]")
         (category "/C")
         (t ""))
   (cond ((eq branch 'maybe) "[--B]")
         (branch "--B")
         (t ""))
   (cond ((eq version 'maybe) "[--V]")
         (version "--V")
         (t ""))
   (cond ((eq revision 'maybe) "[--R]")
         (revision "--R")
         (t ""))))



(defun xetla-location-type (location)
  "Return the type of LOCATION."
  (cond
   ((string-match "^ftp://" location) 'ftp)
   ((string-match "^sftp://" location) 'sftp)
   ((string-match "^http://" location) 'http)
   (t 'local)))

(defun xetla-archive-type (archive)
  "Return the type of ARCHIVE."
  (cond
   ((string-match "SOURCE$" archive) 'source)
   ;; archive-MIRROR, archive-MIRROR-2 should be treated as mirror
   ((string-match ".+-MIRROR" archive) 'mirror)
   (t 'normal)))

;; (xetla-archive-name-source "a")
;; (xetla-archive-name-source "a-SOURCE")
;; (xetla-archive-name-source "a-MIRROR")
(defun xetla-archive-name-source (archive &optional existence-check)
  "Make source archive name from ARCHIVE.
If EXISTENCE-CHECK is non-nil, check whether the made source archive name
already exists or not; return nil if it doesn't exists.
Example:
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla\")
\"jet@gyve.org-xetla-SOURCE\"
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla-MIRROR\")
\"jet@gyve.org-xetla\"
ELISP> (xetla-archive-name-source \"jet@gyve.org-xetla-SOURCE\")
nil"
  (let* ((type (xetla-archive-type archive))
         (source (cond
                 ((eq 'normal type)
                  (concat archive "-SOURCE"))
                 ((eq 'mirror type)
                  (string-match "\\(.*\\)-MIRROR$" archive)
                  (match-string 1 archive))
                 (t nil))))
    (if existence-check
        (progn
          (xetla-archive-tree-build-archives t)
          (when (and source (xetla-archive-tree-get-archive source))
            source))
      source)))

;; (xetla-archive-name-mirror "a")
;; (xetla-archive-name-mirror "a-SOURCE")
;; (xetla-archive-name-mirror "a-MIRROR")
(defun xetla-archive-name-mirror (archive &optional existence-check)
  "Make mirror archive name from ARCHIVE.
If EXISTENCE-CHECK is non-nil, check whether the made mirror archive name
already exists or not; return nil if it doesn't exists.
Example:
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla\")
\"jet@gyve.org--xetla-MIRROR\"
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla-SOURCE\")
\"jet@gyve.org--xetla\"
ELISP> (xetla-archive-name-mirror \"jet@gyve.org--xetla-MIRROR\")
nil"
  (let* ((type (xetla-archive-type archive))
         (mirror (cond
                  ((eq 'normal type)
                   (concat archive "-MIRROR"))
                  ((eq 'source type)
                   (string-match "\\(.*\\)-SOURCE" archive)
                   (match-string 1 archive))
                  (t nil))))
    (if existence-check
        (progn
          (xetla-archive-tree-build-archives t)
          (when (and mirror (xetla-archive-tree-get-archive mirror))
            mirror))
      mirror)))

(defun xetla-compute-direct-ancestor (&optional revision)
  "Compute the direct ancestor of REVISION.
REVISION must be provided as a list, and a list is returned.
If revision is nil, return the ancestor of the last revision
of the local tree."
  (interactive
   (list (xetla-name-read "Compute direct ancestor of: "
                         'prompt 'prompt 'prompt 'prompt 'prompt)))
  (let ((ancestor
         (xetla-run-tla-sync (list "ancestry-graph" "--immediate"
                                  (and revision
                                       (xetla-name-construct revision)))
                            :finished (lambda (output error status arguments)
                                        (xetla-name-split
                                         (xetla-buffer-content
                                          output))))))
    (when (interactive-p)
      (message "Ancestor of: %s\n         is: %s"
               (xetla-name-construct ancestor)
               (xetla-name-construct revision)))
    ancestor))

;; Copied from ediff-mouse-event-p. I prefer keeping this duplication
;; to avoid one more dependancy on ediff.el (whose interface may
;; change one day ...)
(defsubst xetla-mouse-event-p (event)
  "Return true if EVENT is a mouse-related event."
  (if (featurep 'xemacs)
      (xetla-do-in-xemacs (button-event-p event))
    (xetla-do-in-gnu-emacs
      (string-match "mouse" (format "%S" (event-basic-type event))))))

;; --------------------------------------
;; Face manipulators
;; --------------------------------------
(defun xetla-face-add (str face &optional keymap menu help)
  "Add to string STR the face FACE.
Optionally, also add the text properties KEYMAP, MENU and HELP.

If KEYMAP is a symbol, (symbol-value KEYMAP) is used
as a keymap; and `substitute-command-keys' result
against (format \"\\{%s}\" (symbol-name keymap)) is appended to HELP.

If HELP is nil and if MENU is non nil, the MENU title is used as HELP."
  (if xetla-highlight
      (let* ((strcpy (copy-sequence str))
             (key-help (when (symbolp keymap)
                         (substitute-command-keys (format "\\{%s}" (symbol-name keymap)))))
             (prefix-help (if help help (when (and menu (stringp (cadr menu))) (cadr menu))))
             (long-help (if key-help
                            (if prefix-help (concat prefix-help "\n"
                                             ;; Sigh. Font used on tooltips in GNU Emacs with Gtk+
                                             ;; is a proportional.
                                             ;; (make-string (length help) ?=) "\n"
                                             "================" "\n"
                                             key-help) key-help)
                          help))
             (keymap (if (symbolp keymap) (symbol-value keymap) keymap)))
        (add-text-properties 0 (length strcpy)
                             `(face ,face
;;; Even if we define a face in a buffer, it seems that
;;; font-lock mode just ignore it or remove the face property.
;;; I don't know the detail but in xetla-inventory buffer,
;;; I cannot make both font-lock keywords and faces put by tl-face-add
;;; highlight at once. When font-lock-face is defined, I can do.
;;; See "Special Properties" subsection in the emacs lisp reference manual.
;;; `font-lock-face' property is new in Emacs 21.4. However, I guess there is
;;; no wrong side effect if I define font-lock-face property here.
                                    font-lock-face ,face
                                    ,@(when keymap
                                        `(mouse-face highlight
                                                     keymap ,keymap
                                                     help-echo ,long-help))
                                    ,@(when menu
                                        `(menu ,menu))
                                    )
                             strcpy)
        strcpy)
    str))

;; --------------------------------------
;; Debugging facilities
;; --------------------------------------
(defvar xetla-debug t)

(defun xetla-trace (&rest msg)
  "Display the trace message MSG.
Same as `message' if `xetla-debug' is non-nil.
Does nothing otherwise.  Please use it for your debug messages."
  (when xetla-debug
    (apply 'message (concat "xetla: " (car msg)) (cdr msg))))

(defun xetla-reload (directory)
  "Reloads xetla \(usually for debugging purpose\).

With prefix arg, prompts for the DIRECTORY in which xetla should be
loaded.  Useful to switch from one branch to the other.

If a Makefile is present in the directory where xetla is to be loaded,
run \"make\"."
  (interactive
   (list (when current-prefix-arg
           (let* ((other (read-directory-name
                         "Load XEtla from: "))
                  (lispdir (concat (file-name-as-directory other)
                                   "lisp")))
             (if (file-directory-p lispdir)
                 lispdir
               other)))))
  (when directory
    (let ((current-path (file-name-directory (locate-library
                                              "xetla"))))
      (setq load-path
            (cons directory (remove current-path load-path)))))
  (let ((default-directory (file-name-directory (locate-library "xetla"))))
    (when (file-exists-p
           "Makefile")
      (shell-command "make")))
  (when (featurep 'xetla-tips)      (unload-feature 'xetla-tips      t))
  (when (featurep 'xetla-browse)    (unload-feature 'xetla-browse    t))
  (when (featurep 'xetla)           (unload-feature 'xetla           t))
  (when (featurep 'xetla-core)      (unload-feature 'xetla-core      t))
  (when (featurep 'xetla-defs)      (unload-feature 'xetla-defs      t))
  (when (featurep 'xetla-autoloads) (unload-feature 'xetla-autoloads t))
  (ignore-errors (require 'xetla-autoloads))
  (require 'xetla))

;; --------------------------------------
;; Supports spaces in filenames
;; --------------------------------------
(defvar xetla-supports-spaces-in-filenames nil
  "Wether xetla supports spaces in filenames.

Possible values are nil (don't know), 'yes, or 'no.  Don't use this
variable directly.  Use `xetla-supports-spaces-in-filenames' instead.")

(defun xetla-supports-spaces-in-filenames ()
  "Wether xetla supports spaces in filenames.

Returns 't or nil.

If `xetla-supports-spaces' is non-nil, use its value.  Otherwise, test
if \"escape\" is listed by \"xetla help\", and memorize the result in
`xetla-supports-spaces-in-filenames'"
  (interactive)
  (let ((answer
         (cond ((eq xetla-supports-spaces-in-filenames 'yes) t)
               ((eq xetla-supports-spaces-in-filenames 'no) nil)
               (t (xetla-run-tla-sync
                   '("help")
                   :finished (lambda (output error status arguments)
                               (with-current-buffer output
                                 (goto-char (point-min))
                                 (search-forward "escape :"
                                                 nil t))))))))
    (when (interactive-p)
      (message (if answer "Yes" "No")))
    (setq xetla-supports-spaces-in-filenames
          (if answer 'yes 'no))
    answer))

(defun xetla-escape (string &optional unescape message)
  "Return the pika escaped value of STRING.
If pika escaping is not supported by xetla, return STRING.
If UNESCAPE is non-nil, returns the unescaped version of string.
If MESSAGE is non-nil or if run interactively, also display the value
as a message."
  (interactive "sString to escape: ")
  (let ((res (if (and (string-match (if unescape "\\\\"
                                      "[^a-zA-Z._+,{}-]") string)
                      ;; We need to do the (un)escaping
                      (xetla-supports-spaces-in-filenames))
                 (xetla-run-tla-sync
                  (list "escape" (when unescape "--unescaped") string)
                  :finished (lambda (output error status arguments)
                              (xetla-buffer-content output)))
               string)))
    (when (or (interactive-p) message)
      (message res))
    res))

(defun xetla-unescape (string)
  "Run \"tla escape -unescaped\" on STRING.

Return STRING if \"tla escape\" is not available."
  (interactive "sString to unescape: ")
  (xetla-escape string t (interactive-p)))

(defun xetla-regexp-quote (string)
  "Return a regexp string which matches exactly STRING and nothing else.
Special characters are escaped to leave STRING in a suitable form for
Arch."
  (let ((quoted (regexp-quote string)))
    (replace-regexp-in-string
     "\\([{}()|]\\)"
     (concat "\\\\"                     ; leading slash
             "\\1")                     ; quoted character
     quoted)))

;; --------------------------------------
;; Saving and loading state variables
;; --------------------------------------
(defun xetla-pp-to-string (sexp)
  "Return sexp pretty printed by `pp-to-string'."
  (let ((print-readably t)
        print-level print-length)
    (pp-to-string sexp)))

(defun xetla-save-state (&optional vars state-file pp)
  "Save variables from VARS list to file STATE-FILE.
The default for VARS is `xetla-state-variables-list'
The default for STATE-FILE is `xetla-state-file-name'.
If PP is non-nil use `xetla-pp-to-string' to format object.

The file will contain a setq setting the vars during loading by
`xetla-load-state'."
  (let ((state-file (or state-file
                        (expand-file-name xetla-state-file-name
                                          xetla-config-directory)))
        (vars (or vars xetla-state-variables-list))
        v)
    (if (not (file-exists-p (file-name-directory state-file)))
        (make-directory (file-name-directory state-file) t))
    (save-excursion
      (set-buffer (get-buffer-create " *xetla-state*"))
      (erase-buffer)
      (insert ";; Generated file. Do not edit!!!\n(setq\n")
      (if pp
          (while vars
            (setq v (car vars) vars (cdr vars))
            (insert (format "%s\n'%s"
                            (symbol-name v)
                            (xetla-pp-to-string (symbol-value v)))))
        (while vars
          (setq v (car vars) vars (cdr vars))
          (insert (format "      %s '%S\n"
                          (symbol-name v)
                          (symbol-value v)))))
      (insert "      )")
      (write-region (point-min) (point-max) state-file))))

(defun xetla-load-state (&optional state-file)
  "Load `xetla-state-file-name`, i.e. evaluate its content."
  (let ((state-file (or state-file
                        (expand-file-name xetla-state-file-name
                                          xetla-config-directory))))
    (if (file-exists-p state-file)
        (load state-file nil t t))))

;; (setq xetla-archive-tree nil)
;; (setq xetla-revlib-tree nil)

(provide 'xetla-core)
;;; xetla-core.el ends here